The personal finance app for everyone (by everyone)
Ruby
Add RentCast & Realie integration for automatic property data and valuations (#2727)
kianrafieed267288a451a
diff --git a/app/controllers/properties_controller.rb b/app/controllers/properties_controller.rbindex 9b00d4ceec..3e069d853e 100644--- a/app/controllers/properties_controller.rb+++ b/app/controllers/properties_controller.rb@@ -6,9 +6,12 @@ class PropertiesController < ApplicationControllerdef new@account = Current.family.accounts.build(accountable: Property.new)+ @avm_providers = configured_avm_providersenddef create+ return create_via_avm_provider if params[:avm_provider].present?+@account = Current.family.accounts.create!(property_params.merge(balance: 0,@@ -99,6 +102,119 @@ class PropertiesController < ApplicationControllerendprivate+ def create_via_avm_provider+ @avm_providers = configured_avm_providers+ provider_key = params[:avm_provider].to_s++ unless @avm_providers.map(&:to_s).include?(provider_key)+ redirect_to new_property_path, alert: t("providers.property_valuation.not_configured") and return+ end++ if params[:avm_step] == "confirm"+ # The signed token proves the lookup step actually ran (and spent its+ # provider request) — a direct confirm POST with fabricated data+ # would otherwise create provider-linked properties that the daily+ # refresh job then spends quota on. Everything is rebuilt from the+ # token payload, so nothing user-editable is trusted.+ payload = verify_avm_preview_token!++ importer = Property::AvmImport.new(+ family: Current.family,+ owner: Current.user,+ provider_key: payload["provider_key"],+ name: payload["name"],+ address_attributes: payload["address"].symbolize_keys+ )++ @account = importer.create_account(avm_data_from_payload(payload))++ # The provider lookup fills in what the manual wizard's balance and+ # address steps would have collected, so the account is complete —+ # land on the account page (or the flow that initiated the wizard).+ return_path = safe_return_to(session.delete(:return_to)) || account_path(@account)++ respond_to do |format|+ format.html { redirect_to return_path }+ format.turbo_stream { stream_redirect_to return_path }+ end+ else+ # Step 1: spend one provider request, then show the fetched data for+ # review before anything is created.+ importer = Property::AvmImport.new(+ family: Current.family,+ owner: Current.user,+ provider_key: provider_key,+ name: params.dig(:account, :name),+ address_attributes: avm_address_params.to_h.symbolize_keys+ )++ @avm_preview = importer.lookup+ @avm_preview_token = avm_preview_verifier.generate(+ {+ "provider_key" => provider_key,+ "name" => params.dig(:account, :name),+ "address" => avm_address_params.to_h,+ "data" => @avm_preview.to_h.transform_values(&:to_s)+ },+ expires_in: 1.hour,+ purpose: avm_preview_token_purpose+ )+ @avm_provider_key = provider_key+ @account = Current.family.accounts.build(name: params.dig(:account, :name), accountable: Property.new)+ @avm_address = Address.new(avm_address_params.to_h)+ render :new+ end+ rescue Property::AvmImport::Error => error+ @avm_provider_key = provider_key+ @error_message = error.message+ @account = Current.family.accounts.build(name: params.dig(:account, :name), accountable: Property.new)+ # The confirm step doesn't resubmit the address fields, so build+ # defensively — an expired token re-renders an empty lookup form.+ @avm_address = Address.new(params.dig(:account, :address)&.permit(:line1, :locality, :region, :postal_code)&.to_h || {})+ render :new, status: :unprocessable_entity+ end++ def avm_address_params+ params.require(:account).require(:address).permit(:line1, :locality, :region, :postal_code)+ end++ def avm_preview_verifier+ Rails.application.message_verifier(:avm_preview)+ end++ # Scoping the token's purpose to the family means a token minted in one+ # family's session can't be replayed to seed a property in another —+ # a purpose mismatch fails verification just like a bad signature.+ def avm_preview_token_purpose+ "avm_preview/family/#{Current.family.id}"+ end++ def verify_avm_preview_token!+ avm_preview_verifier.verify(params[:avm_preview_token].to_s, purpose: avm_preview_token_purpose)+ rescue ActiveSupport::MessageVerifier::InvalidSignature+ raise Property::AvmImport::Error.new(t("providers.property_valuation.preview_expired"))+ end++ # Rebuilds the valuation data from the signed preview payload (values+ # were stringified for serialization; blanks were nil).+ def avm_data_from_payload(payload)+ raw = payload["data"] || {}++ Provider::PropertyValuationConcept::PropertyValuation.new(+ valuation: raw["valuation"].to_d,+ currency: raw["currency"].presence || "USD",+ property_type: raw["property_type"].presence,+ year_built: raw["year_built"].presence&.to_i,+ area_value: raw["area_value"].presence&.to_i,+ area_unit: raw["area_unit"].presence || "sqft"+ )+ end++ def configured_avm_providers+ registry = Provider::Registry.for_concept(:property_valuations)+ registry.provider_keys.select { |key| registry.get_provider(key).present? }+ end+def balance_paramsparams.require(:account).permit(:balance, :currency)enddiff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rbindex d1ae5f475b..f3082fd2b1 100644--- a/app/controllers/settings/hostings_controller.rb+++ b/app/controllers/settings/hostings_controller.rb@@ -47,6 +47,11 @@ class Settings::HostingsController < ApplicationController@yahoo_finance_provider = Provider::Registry.get_provider(:yahoo_finance)@yahoo_finance_health_status = @yahoo_finance_provider&.health_status || :unknownend++ # Property valuation (AVM) providers — usage is shown against their tight+ # monthly request caps when a key is configured+ @rentcast_usage = Provider::Registry.get_provider(:rentcast)&.usage+ @realie_usage = Provider::Registry.get_provider(:realie)&.usageenddef update@@ -116,6 +121,8 @@ 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(:rentcast_api_key)+ update_encrypted_setting(:realie_api_key)if hosting_params.key?(:syncs_include_pending)Setting.syncs_include_pending = hosting_params[:syncs_include_pending] == "1"@@ -280,7 +287,7 @@ class Settings::HostingsController < ApplicationControllerprivatedef 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, :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, :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, :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, :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/jobs/sync_property_valuations_job.rb b/app/jobs/sync_property_valuations_job.rbnew file mode 100644index 0000000000..b41279e7ef--- /dev/null+++ b/app/jobs/sync_property_valuations_job.rb@@ -0,0 +1,102 @@+# Refreshes the valuation of properties linked to an AVM provider.+#+# Runs once per day (see config/schedule.yml) — never hourly — because the+# provider budgets are tight monthly caps (RentCast 50/month, Realie+# 25/month). Each provider additionally enforces its cap via a durable+# monthly request counter, so refreshes stop once the month's budget is spent.+class SyncPropertyValuationsJob < ApplicationJob+ queue_as :scheduled+ sidekiq_options lock: :until_executed, on_conflict: :log++ def perform+ registry = Provider::Registry.for_concept(:property_valuations)++ # Stalest valuations first (never-synced before oldest-refreshed) so a+ # tight monthly budget is spent where it matters most, not in+ # primary-key order.+ properties = Property.where.not(avm_provider: nil)+ .includes(:address, :account)+ .order(Arel.sql("avm_last_synced_on ASC NULLS FIRST"))++ # One provider instance per key for the whole run — the request throttle+ # tracks its last request time on the instance, so a fresh instance per+ # property would bypass the inter-request delay.+ providers = {}++ properties.each do |property|+ account = property.account+ next unless account&.active?+ next if property.avm_last_synced_on == Date.current++ # Skip before spending a monthly-budget request: mirrors the+ # import-time completeness check. A blank city/ZIP would also disable+ # the wrong-city guard in the Realie lookup, letting a refresh accept+ # another property's valuation — and the providers only cover the US.+ address = property.address+ if address.nil? ||+ %i[line1 locality region postal_code].any? { |field| address[field].blank? } ||+ (address.country.present? && !address.country.to_s.strip.match?(/\A(US|USA)\z/i))+ capture_failure(property, account, "Skipping refresh: property address is incomplete or not a US address", level: "warn")+ next+ end++ unless providers.key?(property.avm_provider)+ providers[property.avm_provider] = begin+ registry.get_provider(property.avm_provider)+ rescue Provider::Registry::Error+ nil+ end+ end++ provider = providers[property.avm_provider]+ next unless provider # API key was removed after the property was linked+ next unless provider.requests_remaining?++ # The account was created in the provider's currency, but the user can+ # change it later. Writing a USD valuation as another currency would+ # corrupt the balance, so skip mismatches — before spending a request.+ unless account.currency == provider.valuation_currency+ capture_failure(property, account, "Skipping refresh: account currency #{account.currency} does not match provider valuation currency #{provider.valuation_currency}", level: "warn")+ next+ end++ response = provider.fetch_property_valuation(+ line1: address.line1,+ locality: address.locality,+ region: address.region,+ postal_code: address.postal_code+ )++ if response.success?+ result = nil+ Property.transaction do+ result = account.set_current_balance(response.data.valuation)+ raise ActiveRecord::Rollback unless result.success?+ property.update!(avm_last_synced_on: Date.current)+ end++ unless result&.success?+ capture_failure(property, account, "Failed to update valuation balance: #{result&.error}")+ end+ else+ capture_failure(property, account, "Valuation refresh failed: #{response.error.message}")+ end+ rescue => e+ capture_failure(property, property.account, "Error refreshing valuation: #{e.class} - #{e.message}")+ end+ end++ private++ def capture_failure(property, account, message, level: "error")+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: level,+ message: message,+ source: self.class.name,+ provider_key: property.avm_provider,+ account: account,+ metadata: { property_id: property.id }+ )+ end+enddiff --git a/app/models/property/avm_import.rb b/app/models/property/avm_import.rbnew file mode 100644index 0000000000..3ac7982777--- /dev/null+++ b/app/models/property/avm_import.rb@@ -0,0 +1,86 @@+# Creates a property account from an AVM provider lookup in two steps:+# `lookup` spends one provider request to fetch the property's attributes+# (type, year built, area) and estimated value, which the user reviews on a+# preview screen; `create_account` then seeds the account from the confirmed+# data without a second request.+class Property::AvmImport+ Error = Class.new(StandardError)++ def initialize(family:, owner:, provider_key:, name:, address_attributes:)+ @family = family+ @owner = owner+ @provider_key = provider_key.to_s+ @name = name+ @address_attributes = address_attributes+ end++ # Step 1: validates the inputs, then spends one provider request. Returns+ # the fetched Provider::PropertyValuationConcept::PropertyValuation.+ def lookup+ validate_inputs!++ provider = Provider::Registry.for_concept(:property_valuations).get_provider(provider_key)+ raise Error.new(I18n.t("providers.property_valuation.not_configured")) if provider.nil?++ response = provider.fetch_property_valuation(+ line1: address_attributes[:line1],+ locality: address_attributes[:locality],+ region: address_attributes[:region],+ postal_code: address_attributes[:postal_code]+ )+ raise Error.new(response.error.message) unless response.success?++ response.data+ end++ # Step 2: creates the active property account from the user-confirmed+ # valuation data. No provider request is made here.+ def create_account(data)+ validate_inputs!++ account = nil+ Account.transaction do+ account = family.accounts.create!(+ name: name,+ balance: 0,+ currency: data.currency,+ status: "draft",+ owner: owner,+ accountable: Property.new(+ subtype: data.property_type,+ year_built: data.year_built,+ area_value: data.area_value,+ area_unit: data.area_unit,+ avm_provider: provider_key,+ avm_last_synced_on: Date.current,+ # Providers only cover US addresses, so the country isn't collected+ # in the lookup form. "US" matches the manual form's placeholder.+ address_attributes: address_attributes.merge(country: "US")+ )+ )++ result = account.set_current_balance(data.valuation)+ raise Error.new(result.error) unless result.success?++ account.activate!+ end++ account.auto_share_with_family! if family.share_all_by_default?+ account+ rescue ActiveRecord::RecordInvalid => e+ raise Error.new(e.record.errors.full_messages.to_sentence.presence || e.message)+ end++ private+ attr_reader :family, :owner, :provider_key, :name, :address_attributes++ # The form marks these required, but a forged or JS-less submission can+ # bypass that — validate locally before spending a monthly-budget request+ # on a lookup that can't produce a property.+ def validate_inputs!+ missing = name.blank? ||+ %i[line1 locality region postal_code].any? { |field| address_attributes[field].blank? }++ raise Error.new(I18n.t("providers.property_valuation.missing_fields")) if missing+ end+enddiff --git a/app/models/provider/property_valuation_concept.rb b/app/models/provider/property_valuation_concept.rbnew file mode 100644index 0000000000..4629b3bcf1--- /dev/null+++ b/app/models/provider/property_valuation_concept.rb@@ -0,0 +1,71 @@+# Interface for automated valuation model (AVM) providers that can look up a+# US property record and return both its attributes and an estimated value in+# a single request.+#+# Includers must define:+# - `MAX_REQUESTS_PER_MONTH` (Integer) — the provider's monthly request budget+# - `RateLimitError` (Class) — provider-scoped rate-limit error class+module Provider::PropertyValuationConcept+ extend ActiveSupport::Concern++ PropertyValuation = Data.define(:valuation, :currency, :property_type, :year_built, :area_value, :area_unit)++ def fetch_property_valuation(line1:, locality: nil, region: nil, postal_code: nil)+ raise NotImplementedError, "Subclasses must implement #fetch_property_valuation"+ end++ # Currency of the valuations this provider returns. Both supported+ # providers are US-based and always price in USD; the daily refresh job+ # checks this against the account currency before spending a request.+ def valuation_currency+ "USD"+ end++ # Whether the provider still has monthly request budget left. Checked by+ # SyncPropertyValuationsJob before spending a request on a refresh.+ def requests_remaining?+ monthly_request_count < max_requests_per_month+ end++ def usage+ with_provider_response do+ used = monthly_request_count++ Provider::UsageData.new(+ used: used,+ limit: max_requests_per_month,+ utilization: (used.to_f / max_requests_per_month * 100).round(1),+ plan: "Free"+ )+ end+ end++ private+ # Defaults to the provider's free tier cap; users on paid plans can raise+ # it via ENV (e.g. RENTCAST_MAX_REQUESTS_PER_MONTH), mirroring the+ # AlphaVantage/Tiingo request limit overrides.+ def max_requests_per_month+ ENV.fetch("#{self.class.name.demodulize.underscore.upcase}_MAX_REQUESTS_PER_MONTH", self.class::MAX_REQUESTS_PER_MONTH).to_i+ end++ def monthly_request_count+ ProviderRequestCount.count_for(provider_key)+ end++ # Counts every outbound request (user-initiated lookups and daily+ # refreshes) against the provider's monthly budget. Backed by a durable+ # database counter (not Rails.cache) so the hard cap can't be reset by+ # cache eviction or a restart.+ def record_monthly_request!+ count = ProviderRequestCount.increment!(provider_key)++ if count > max_requests_per_month+ ProviderRequestCount.decrement!(provider_key)+ raise self.class::RateLimitError.new("#{self.class.name.demodulize} monthly request limit reached (#{max_requests_per_month} per month)")+ end+ end++ def provider_key+ self.class.name.demodulize.underscore+ end+enddiff --git a/app/models/provider/realie.rb b/app/models/provider/realie.rbnew file mode 100644index 0000000000..addd676177--- /dev/null+++ b/app/models/provider/realie.rb@@ -0,0 +1,159 @@+class Provider::Realie < Provider+ include PropertyValuationConcept, RateLimitable+ extend SslConfigurable++ # Subclass so errors caught in this provider are raised as Provider::Realie::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 (Realie free tier limit).+ # Override with REALIE_MAX_REQUESTS_PER_MONTH for paid plans.+ MAX_REQUESTS_PER_MONTH = 25++ # Realie's documented numeric use codes to Property::SUBTYPES keys+ # (https://docs.realie.ai/api-reference/feature-key). Codes without a+ # sensible subtype equivalent (e.g. 1006 mobile/manufactured, commercial+ # codes) are left unmapped, matching the RentCast mapping's behavior.+ NUMERIC_USE_CODE_MAP = {+ "1001" => "single_family_home", # Single family residential+ "1008" => "single_family_home", # Rural/agricultural residence+ "1022" => "single_family_home", # SFR with ADU+ "1024" => "single_family_home", # Multiple SFRs on one parcel+ "1002" => "townhouse", # Townhouse (residential)+ "1004" => "condominium", # Condominium unit (residential)+ "1124" => "condominium", # Condominium building (residential)+ "1101" => "multi_family_home", # Duplex+ "1102" => "multi_family_home", # Triplex+ "1103" => "multi_family_home", # Quadruplex+ "1104" => "apartment", # Apartment house (5+ units)+ "1105" => "apartment", # Apartment house (100+ units)+ "7001" => "agri_land", # Farm+ "7002" => "agri_land", # Ranch+ "8001" => "plot", # Residential vacant land+ "8002" => "plot", # Commercial vacant land+ "8008" => "plot" # Rural/agricultural vacant land+ }.freeze++ def initialize(api_key)+ @api_key = api_key # pipelock:ignore+ end++ # A single address lookup returns the full property record, including the+ # Realie model (AVM) value, so no separate valuation request is needed.+ def fetch_property_valuation(line1:, locality: nil, region: nil, postal_code: nil)+ with_provider_response do+ throttle_request+ record_monthly_request!++ # The address lookup endpoint accepts only the street address and+ # 2-letter state code — filtering by city additionally requires a+ # county, which the property address form doesn't collect.+ response = client.get("#{base_url}/api/public/property/address/") do |req|+ req.params["address"] = line1.to_s.strip+ req.params["state"] = region.to_s.strip.upcase+ end++ parsed = JSON.parse(response.body)+ records = parsed["property"]+ records = [ records ] unless records.is_a?(Array)+ records = records.reject(&:blank?)+ raise Error.new(I18n.t("providers.realie.errors.no_property")) if records.empty?++ # A street+state query can return several candidates across different+ # cities; pick the first one consistent with the entered city/ZIP.+ record = records.find { |candidate| location_match?(candidate, locality: locality, postal_code: postal_code) }+ raise Error.new(I18n.t("providers.realie.errors.location_mismatch")) if record.nil?++ # Realie returns modelValue: 0 when it couldn't produce an AVM+ # estimate, so zero counts as absent and falls back to the assessed+ # total market value.+ valuation = [ record["modelValue"], record["totalMarketValue"] ].find { |value| value.present? && value.to_d.positive? }+ raise Error.new(I18n.t("providers.realie.errors.no_valuation")) if valuation.nil?++ PropertyValuation.new(+ valuation: BigDecimal(valuation.to_s),+ currency: "USD",+ property_type: subtype_for_use_code(record["useCode"]),+ year_built: record["yearBuilt"],+ area_value: record["buildingArea"],+ area_unit: "sqft"+ )+ end+ end++ private+ attr_reader :api_key++ # The address lookup matches on street + state only (filtering by city+ # additionally requires a county, which isn't collected), so a common+ # street name can resolve to properties in other cities. A candidate+ # matches unless its returned city/ZIP contradict what the user entered.+ def location_match?(record, locality:, postal_code:)+ returned_city = record["city"].to_s.strip+ returned_zip = record["zipCode"].to_s.strip.first(5)+ entered_city = locality.to_s.strip+ entered_zip = postal_code.to_s.strip.first(5)++ city_mismatch = returned_city.present? && entered_city.present? && !returned_city.casecmp?(entered_city)+ zip_mismatch = returned_zip.present? && entered_zip.present? && returned_zip != entered_zip++ !(city_mismatch || zip_mismatch)+ end++ # Use codes arrive either as Realie's documented numeric codes (mapped+ # exactly above) or as free-form parcel descriptions, matched on+ # keywords. Unmatched codes leave the subtype unset rather than guessing.+ def subtype_for_use_code(use_code)+ value = use_code.to_s.strip.downcase+ return nil if value.blank?++ return NUMERIC_USE_CODE_MAP[value] if value.match?(/\A\d+\z/)++ case value+ when /single family|sfr/ then "single_family_home"+ when /multi.?family|duplex|triplex/ then "multi_family_home"+ when /condo/ then "condominium"+ when /town.?(house|home)/ then "townhouse"+ when /apartment/ then "apartment"+ when /agricultur|farm/ then "agri_land"+ when /commercial|retail|office|industrial/ then "commercial"+ when /vacant|land|lot/ then "plot"+ end+ end++ def default_error_transformer(error)+ case error+ when Faraday::ResourceNotFound+ Error.new(I18n.t("providers.realie.errors.not_found"))+ else+ super+ end+ end++ def base_url+ ENV["REALIE_URL"] || "https://app.realie.ai"+ 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 tight 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["Authorization"] = api_key+ faraday.headers["Accept"] = "application/json"+ end+ end+enddiff --git a/app/models/provider/registry.rb b/app/models/provider/registry.rbindex aaeb5f98ef..b625fc22fd 100644--- a/app/models/provider/registry.rb+++ b/app/models/provider/registry.rb@@ -3,7 +3,7 @@ class Provider::RegistryError = Class.new(StandardError)- CONCEPTS = %i[exchange_rates securities llm]+ CONCEPTS = %i[exchange_rates securities llm property_valuations]validates :concept, inclusion: { in: CONCEPTS }@@ -156,6 +156,22 @@ class Provider::RegistryProvider::TinkoffInvest.new(api_key)end++ def rentcast+ api_key = ENV["RENTCAST_API_KEY"].presence || Setting.rentcast_api_key # pipelock:ignore++ return nil unless api_key.present?++ Provider::Rentcast.new(api_key)+ end++ def realie+ api_key = ENV["REALIE_API_KEY"].presence || Setting.realie_api_key # pipelock:ignore++ return nil unless api_key.present?++ Provider::Realie.new(api_key)+ endenddef initialize(concept)@@ -191,6 +207,8 @@ class Provider::Registry%i[twelve_data yahoo_finance tiingo eodhd alpha_vantage mfapi binance_public moex_public tinkoff_invest]when :llm%i[openai anthropic]+ when :property_valuations+ %i[rentcast realie]else%i[plaid_us plaid_eu github openai anthropic]enddiff --git a/app/models/provider/rentcast.rb b/app/models/provider/rentcast.rbnew file mode 100644index 0000000000..16059d1fa9--- /dev/null+++ b/app/models/provider/rentcast.rb@@ -0,0 +1,96 @@+class Provider::Rentcast < Provider+ include PropertyValuationConcept, RateLimitable+ extend SslConfigurable++ # Subclass so errors caught in this provider are raised as Provider::Rentcast::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 (RentCast free tier limit).+ # Override with RENTCAST_MAX_REQUESTS_PER_MONTH for paid plans.+ MAX_REQUESTS_PER_MONTH = 50++ # RentCast property types to Property::SUBTYPES keys. Unmapped types+ # (e.g. "Manufactured") leave the subtype unset rather than guessing.+ PROPERTY_TYPE_MAP = {+ "Single Family" => "single_family_home",+ "Multi-Family" => "multi_family_home",+ "Condo" => "condominium",+ "Townhouse" => "townhouse",+ "Apartment" => "apartment",+ "Land" => "plot"+ }.freeze++ def initialize(api_key)+ @api_key = api_key # pipelock:ignore+ end++ # Fetches the value estimate and the subject property's attributes in a+ # single request — `lookupSubjectAttributes` enriches the AVM response with+ # the property record, so a separate /v1/properties call isn't needed.+ def fetch_property_valuation(line1:, locality: nil, region: nil, postal_code: nil)+ with_provider_response do+ throttle_request+ record_monthly_request!++ response = client.get("#{base_url}/v1/avm/value") do |req|+ req.params["address"] = [ line1, locality, region, postal_code ].map { |part| part.to_s.strip }.reject(&:empty?).join(", ")+ req.params["lookupSubjectAttributes"] = true+ end++ parsed = JSON.parse(response.body)+ price = parsed["price"]+ raise Error.new(I18n.t("providers.rentcast.errors.no_valuation")) if price.blank?++ subject = parsed["subjectProperty"] || {}++ PropertyValuation.new(+ valuation: BigDecimal(price.to_s),+ currency: "USD",+ property_type: PROPERTY_TYPE_MAP[subject["propertyType"]],+ year_built: subject["yearBuilt"],+ area_value: subject["squareFootage"],+ area_unit: "sqft"+ )+ end+ end++ private+ attr_reader :api_key++ def default_error_transformer(error)+ case error+ when Faraday::ResourceNotFound+ Error.new(I18n.t("providers.rentcast.errors.not_found"))+ else+ super+ end+ end++ def base_url+ ENV["RENTCAST_URL"] || "https://api.rentcast.io"+ 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 tight 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+enddiff --git a/app/models/provider_request_count.rb b/app/models/provider_request_count.rbnew file mode 100644index 0000000000..772cb36fab--- /dev/null+++ b/app/models/provider_request_count.rb@@ -0,0 +1,33 @@+# Durable monthly API request counters for providers with hard request+# budgets (e.g. AVM property valuation providers). Stored in the database+# rather than Rails.cache so budget enforcement survives cache eviction,+# restarts, and Redis flushes.+class ProviderRequestCount < ApplicationRecord+ validates :provider_key, :period, presence: true+ validates :provider_key, uniqueness: { scope: :period }++ class << self+ def current_period+ Date.current.strftime("%Y-%m")+ end++ # Atomically increments the counter and returns the new count.+ def increment!(provider_key, period: current_period)+ result = upsert(+ { provider_key: provider_key, period: period, count: 1 },+ unique_by: %i[provider_key period],+ on_duplicate: Arel.sql("count = provider_request_counts.count + 1, updated_at = CURRENT_TIMESTAMP"),+ returning: %w[count]+ )+ result.rows.first.first.to_i+ end++ def decrement!(provider_key, period: current_period)+ where(provider_key: provider_key, period: period).update_all("count = GREATEST(count - 1, 0)")+ end++ def count_for(provider_key, period: current_period)+ where(provider_key: provider_key, period: period).pick(:count).to_i+ end+ end+enddiff --git a/app/models/setting.rb b/app/models/setting.rbindex 142e603186..dde71b9609 100644--- a/app/models/setting.rb+++ b/app/models/setting.rb@@ -61,6 +61,10 @@ class Setting < RailsSettings::Basefield :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"]+ # Property valuation (AVM) provider API keys+ field :rentcast_api_key, type: :string, default: ENV["RENTCAST_API_KEY"]+ field :realie_api_key, type: :string, default: ENV["REALIE_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# reads (decrypt) and writes (encrypt) while `super` delegates to the@@ -75,6 +79,8 @@ class Setting < RailsSettings::Baseeodhd_api_keyalpha_vantage_api_keytinkoff_invest_api_key+ rentcast_api_key+ realie_api_keyopenai_access_tokenanthropic_access_tokenexternal_assistant_tokendiff --git a/app/views/properties/_avm_form.html.erb b/app/views/properties/_avm_form.html.erbnew file mode 100644index 0000000000..fe81ebbcbb--- /dev/null+++ b/app/views/properties/_avm_form.html.erb@@ -0,0 +1,57 @@+<%# locals: (account:, provider_key:) %>++<% provider_name = t("properties.avm_providers.#{provider_key}") %>++<%= render DS::Dialog.new do |dialog| %>+ <% dialog.with_header(title: t("properties.new.avm_title", provider: provider_name)) %>+ <% dialog.with_body do %>+ <%= styled_form_with model: account, url: properties_path do |form| %>+ <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>++ <%= hidden_field_tag :avm_provider, provider_key %>+ <%= form.hidden_field :accountable_type, value: "Property" %>++ <%= form.text_field :name,+ label: t("properties.overview_fields.name_label"),+ placeholder: t("properties.overview_fields.name_placeholder"),+ required: true %>++ <%= form.fields_for :address, (@avm_address || Address.new) do |address_form| %>+ <%= address_form.text_field :line1,+ label: t("properties.form.address_line1"),+ placeholder: t("properties.form.address_line1_placeholder"),+ required: true %>+ <div class="flex items-center gap-2">+ <%= address_form.text_field :locality,+ label: t("properties.form.locality"),+ placeholder: t("properties.form.locality_placeholder"),+ required: true %>+ <%= address_form.text_field :region,+ label: t("properties.form.region"),+ placeholder: t("properties.form.region_placeholder"),+ required: true %>+ </div>+ <div class="flex items-center gap-2">+ <%= address_form.text_field :postal_code,+ label: t("properties.form.postal_code"),+ placeholder: t("properties.form.postal_code_placeholder"),+ required: true %>+ </div>+ <% end %>++ <p class="text-sm text-secondary"><%= t("properties.new.avm_us_only", provider: provider_name) %></p>+ </div>++ <div class="flex justify-end mt-4">+ <%= render DS::Button.new(+ text: t("properties.new.avm_submit"),+ variant: "primary",+ type: :submit,+ ) %>+ </div>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/properties/_avm_method_option.html.erb b/app/views/properties/_avm_method_option.html.erbnew file mode 100644index 0000000000..8cf763b7dc--- /dev/null+++ b/app/views/properties/_avm_method_option.html.erb@@ -0,0 +1,9 @@+<%# locals: (path:, icon_name:, label:) %>++<%= link_to path, class: "group flex items-center gap-4 w-full text-center text-primary focus:outline-hidden focus:bg-surface-hover border border-transparent focus:border focus:border-secondary px-2 hover:bg-surface-hover rounded-lg p-2" do %>+ <span class="flex w-8 h-8 shrink-0 grow-0 items-center justify-center rounded-lg bg-alpha-black-50 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.02)]">+ <%= icon(icon_name) %>+ </span>+ <%= label %>+ <%= icon("chevron-right", size: "sm", class: "ml-auto shrink-0 text-subdued transition-colors group-hover:text-secondary") %>+<% end %>diff --git a/app/views/properties/_avm_method_selector.html.erb b/app/views/properties/_avm_method_selector.html.erbnew file mode 100644index 0000000000..ff49f1e938--- /dev/null+++ b/app/views/properties/_avm_method_selector.html.erb@@ -0,0 +1,17 @@+<%# locals: (avm_providers:) %>++<%= render layout: "accounts/new/container", locals: { title: t("accounts.new.method_selector.title"), back_path: new_account_path } do %>+ <div class="text-sm">+ <%= render "properties/avm_method_option",+ path: new_property_path(return_to: params[:return_to]),+ icon_name: "keyboard",+ label: t("accounts.new.method_selector.manual_entry") %>++ <% avm_providers.each do |provider_key| %>+ <%= render "properties/avm_method_option",+ path: new_property_path(method: provider_key, return_to: params[:return_to]),+ icon_name: "map-pin",+ label: t("properties.new.avm_option", provider: t("properties.avm_providers.#{provider_key}")) %>+ <% end %>+ </div>+<% end %>diff --git a/app/views/properties/_avm_preview.html.erb b/app/views/properties/_avm_preview.html.erbnew file mode 100644index 0000000000..b8b1173c37--- /dev/null+++ b/app/views/properties/_avm_preview.html.erb@@ -0,0 +1,66 @@+<%# locals: (account:, provider_key:, preview:, address:) %>++<% provider_name = t("properties.avm_providers.#{provider_key}") %>+<% unknown = t("properties.overview.unknown") %>+<% no_property_record = preview.property_type.nil? && preview.year_built.nil? && preview.area_value.nil? %>++<%= render DS::Dialog.new do |dialog| %>+ <% dialog.with_header(title: t("properties.new.avm_preview_title", provider: provider_name)) %>+ <% dialog.with_body do %>+ <div class="flex flex-col gap-4 min-h-80">+ <p class="text-sm text-secondary"><%= t("properties.new.avm_preview_description", provider: provider_name) %></p>++ <div class="flex flex-col gap-2 text-sm">+ <div class="flex justify-between gap-2">+ <span class="text-secondary"><%= t("properties.overview_fields.name_label") %></span>+ <span class="text-primary font-medium"><%= account.name %></span>+ </div>+ <div class="flex justify-between gap-2">+ <span class="text-secondary"><%= t("properties.form.address_line1") %></span>+ <span class="text-primary font-medium text-right"><%= [ address.line1, address.locality, address.region, address.postal_code ].map(&:presence).compact.join(", ") %></span>+ </div>+ <%= render "shared/ruler", classes: "my-1" %>+ <div class="flex justify-between gap-2">+ <span class="text-secondary"><%= t("properties.overview_fields.property_type_label") %></span>+ <span class="text-primary font-medium"><%= preview.property_type ? Property::SUBTYPES.dig(preview.property_type, :long) : unknown %></span>+ </div>+ <div class="flex justify-between gap-2">+ <span class="text-secondary"><%= t("properties.overview.year_built") %></span>+ <span class="text-primary font-medium"><%= preview.year_built || unknown %></span>+ </div>+ <div class="flex justify-between gap-2">+ <span class="text-secondary"><%= t("properties.overview.living_area") %></span>+ <span class="text-primary font-medium"><%= preview.area_value ? "#{preview.area_value} #{preview.area_unit}" : unknown %></span>+ </div>+ <div class="flex justify-between gap-2">+ <span class="text-secondary"><%= t("properties.overview.market_value") %></span>+ <span class="text-primary font-medium privacy-sensitive"><%= format_money(Money.new(preview.valuation, preview.currency)) %></span>+ </div>+ </div>++ <% if no_property_record %>+ <p class="text-sm text-secondary"><%= t("properties.new.avm_preview_no_record", provider: provider_name) %></p>+ <% end %>+ </div>++ <%# The confirm step rebuilds everything from the signed token, proving+ the lookup ran; only routing params travel as plain fields. %>+ <%= styled_form_with model: account, url: properties_path do |form| %>+ <%= hidden_field_tag :avm_provider, provider_key %>+ <%= hidden_field_tag :avm_step, "confirm" %>+ <%= hidden_field_tag :avm_preview_token, @avm_preview_token %>+ <%= form.hidden_field :accountable_type, value: "Property" %>++ <div class="flex justify-between items-center mt-4">+ <%= link_to t("properties.new.avm_preview_back"),+ new_property_path(method: provider_key, return_to: params[:return_to]),+ class: "text-sm text-secondary hover:text-primary underline" %>+ <%= render DS::Button.new(+ text: t("properties.new.avm_preview_confirm"),+ variant: "primary",+ type: :submit,+ ) %>+ </div>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/properties/new.html.erb b/app/views/properties/new.html.erbindex 5e790cce0a..a62e2eda80 100644--- a/app/views/properties/new.html.erb+++ b/app/views/properties/new.html.erb@@ -1,28 +1,38 @@-<%= render DS::Dialog.new do |dialog| %>- <% dialog.with_header(title: t(".title")) %>- <% dialog.with_body do %>- <div class="flex gap-4">- <!-- Left sidebar with tabs -->- <%= render "properties/form_tabs", account: @account, active_tab: "overview" %>+<% avm_provider_key = @avm_provider_key || params[:method] %>- <!-- Right content area with form -->- <div class="flex-1">- <%= styled_form_with model: @account, url: properties_path do |form| %>- <div class="flex flex-col gap-2 min-h-[320px]">- <%= render "properties/form_alert", notice: @success_message, error: @error_message %>- <%= render "properties/overview_fields", form: form %>- </div>+<% if @avm_preview.present? %>+ <%= render "properties/avm_preview", account: @account, provider_key: @avm_provider_key, preview: @avm_preview, address: @avm_address %>+<% elsif params[:step] == "method_select" && @avm_providers.present? %>+ <%= render "properties/avm_method_selector", avm_providers: @avm_providers %>+<% elsif avm_provider_key.present? && @avm_providers&.map(&:to_s)&.include?(avm_provider_key.to_s) %>+ <%= render "properties/avm_form", account: @account, provider_key: avm_provider_key %>+<% else %>+ <%= render DS::Dialog.new do |dialog| %>+ <% dialog.with_header(title: t(".title")) %>+ <% dialog.with_body do %>+ <div class="flex gap-4">+ <!-- Left sidebar with tabs -->+ <%= render "properties/form_tabs", account: @account, active_tab: "overview" %>- <!-- Create button -->- <div class="flex justify-end mt-4">- <%= render DS::Button.new(- text: t(".next"),- variant: "primary",- type: :submit,- ) %>- </div>- <% end %>+ <!-- Right content area with form -->+ <div class="flex-1">+ <%= styled_form_with model: @account, url: properties_path do |form| %>+ <div class="flex flex-col gap-2 min-h-[320px]">+ <%= render "properties/form_alert", notice: @success_message, error: @error_message %>+ <%= render "properties/overview_fields", form: form %>+ </div>++ <!-- Create button -->+ <div class="flex justify-end mt-4">+ <%= render DS::Button.new(+ text: t(".next"),+ variant: "primary",+ type: :submit,+ ) %>+ </div>+ <% end %>+ </div></div>- </div>+ <% end %><% end %><% end %>diff --git a/app/views/settings/hostings/_realie_settings.html.erb b/app/views/settings/hostings/_realie_settings.html.erbnew file mode 100644index 0000000000..ae5b3ff74b--- /dev/null+++ b/app/views/settings/hostings/_realie_settings.html.erb@@ -0,0 +1,30 @@+<div class="space-y-4">+ <div>+ <h2 class="font-medium mb-1"><%= t(".title") %></h2>+ <% if ENV["REALIE_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 @realie_usage&.success? %>+ <p class="text-sm text-secondary"><%= t(".usage", used: @realie_usage.data.used, limit: @realie_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["REALIE_API_KEY"].present? || Setting.realie_api_key.present? %>+ <%= form.text_field :realie_api_key,+ label: t(".label"),+ type: "password",+ placeholder: t(".placeholder"),+ value: has_key ? "********" : "",+ disabled: ENV["REALIE_API_KEY"].present?,+ data: { "auto-submit-form-target": "auto" } %>+ <% end %>+</div>diff --git a/app/views/settings/hostings/_rentcast_settings.html.erb b/app/views/settings/hostings/_rentcast_settings.html.erbnew file mode 100644index 0000000000..c88c30680d--- /dev/null+++ b/app/views/settings/hostings/_rentcast_settings.html.erb@@ -0,0 +1,30 @@+<div class="space-y-4">+ <div>+ <h2 class="font-medium mb-1"><%= t(".title") %></h2>+ <% if ENV["RENTCAST_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 @rentcast_usage&.success? %>+ <p class="text-sm text-secondary"><%= t(".usage", used: @rentcast_usage.data.used, limit: @rentcast_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["RENTCAST_API_KEY"].present? || Setting.rentcast_api_key.present? %>+ <%= form.text_field :rentcast_api_key,+ label: t(".label"),+ type: "password",+ placeholder: t(".placeholder"),+ value: has_key ? "********" : "",+ disabled: ENV["RENTCAST_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.erbindex a5cf082f63..44970a9afa 100644--- a/app/views/settings/hostings/show.html.erb+++ b/app/views/settings/hostings/show.html.erb@@ -41,6 +41,12 @@<% end %></div><% end %>+<%= settings_section title: t(".property_valuation_providers") do %>+ <div class="space-y-6">+ <%= render "settings/hostings/rentcast_settings" %>+ <%= render "settings/hostings/realie_settings" %>+ </div>+<% end %><%= settings_section title: t(".sync_settings") do %><%= render "settings/hostings/sync_settings" %><% end %>diff --git a/config/locales/models/provider/en.yml b/config/locales/models/provider/en.ymlnew file mode 100644index 0000000000..4e0a08dac8--- /dev/null+++ b/config/locales/models/provider/en.yml@@ -0,0 +1,17 @@+---+en:+ providers:+ property_valuation:+ not_configured: This property data provider is not configured.+ missing_fields: Please provide a name and a complete US address (street, city, state, and ZIP code).+ preview_expired: This property preview has expired — please look up the address again.+ rentcast:+ errors:+ no_valuation: RentCast did not return a value estimate for this address.+ not_found: RentCast could not find a property matching this address.+ realie:+ errors:+ no_property: Realie did not return a property for this address.+ no_valuation: Realie did not return a valuation for this property.+ not_found: Realie could not find a property matching this address.+ location_mismatch: Realie matched a property in a different city or ZIP code. Please double-check the address.diff --git a/config/locales/views/properties/en.yml b/config/locales/views/properties/en.ymlindex fabe4d28af..d0dc0fe4cf 100644--- a/config/locales/views/properties/en.yml+++ b/config/locales/views/properties/en.yml@@ -21,9 +21,22 @@ en:subtype_prompt: Select property typeyear_built: Year builtyear_built_placeholder: '2000'+ avm_providers:+ rentcast: RentCast+ realie: Realienew:title: Enter property manuallynext: "Next"+ avm_option: "Add via %{provider}"+ avm_title: "Add property via %{provider}"+ avm_description: "Enter a name for the property and its address. %{provider} will look up the property details and estimated market value for you."+ avm_us_only: "%{provider} only supports properties located in the United States."+ 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_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_confirm: "Add property"address:title: "Enter property manually"address_line1_label: "Address Line 1"diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.ymlindex 4ca4155aa5..9c6539ad9e 100644--- a/config/locales/views/settings/hostings/en.yml+++ b/config/locales/views/settings/hostings/en.yml@@ -21,6 +21,7 @@ en:general: General Settingsai_assistant: AI Assistantfinancial_data_providers: Financial Data Providers+ property_valuation_providers: Property Valuation Providerssync_settings: Sync Settingsinvites: Invite Codestitle: Self-Hosting@@ -152,6 +153,20 @@ en:unavailable_title: Could not verify Yahoo Finance.unavailable_message: Yahoo Finance could not be reached or returned an unexpected response. Check your internet connection and try again later.status_unknown: Yahoo Finance status is being checked.+ rentcast_settings:+ title: RentCast+ description: Enter your RentCast API key to look up US property details and value estimates when adding a property. The free tier is limited to 50 API requests per month, shared between property lookups and daily valuation refreshes. On a paid plan, raise the cap with the RENTCAST_MAX_REQUESTS_PER_MONTH environment variable.+ env_configured_message: Successfully configured through the RENTCAST_API_KEY environment variable.+ label: API Key+ placeholder: Enter your RentCast API key here+ usage: "%{used} of %{limit} monthly requests used"+ realie_settings:+ title: Realie+ description: Enter your Realie API key to look up US property details and value estimates when adding a property. The free tier is limited to 25 API requests per month, shared between property lookups and daily valuation refreshes. On a paid plan, raise the cap with the REALIE_MAX_REQUESTS_PER_MONTH environment variable.+ env_configured_message: Successfully configured through the REALIE_API_KEY environment variable.+ label: API Key+ placeholder: Enter your Realie API key here+ usage: "%{used} of %{limit} monthly requests used"tiingo_settings:title: Tiingodescription: Enter the API token provided by Tiingo. Free tier supports 50 unique symbols per hour with 30+ years of historical data.diff --git a/config/schedule.yml b/config/schedule.ymlindex a504b56986..720966f040 100644--- a/config/schedule.yml+++ b/config/schedule.yml@@ -25,6 +25,12 @@ sync_hourly:queue: "scheduled"description: "Syncs provider items that opt-in to hourly syncing"+sync_property_valuations:+ cron: "30 1 1 * *" # monthly on the 1st at 1:30 AM+ class: "SyncPropertyValuationsJob"+ queue: "scheduled"+ description: "Refreshes AVM property valuations once a month (providers enforce tight monthly request caps)"+clean_data:cron: "0 3 * * *" # daily at 3:00 AMclass: "DataCleanerJob"diff --git a/db/migrate/20260718000000_add_avm_provider_to_properties.rb b/db/migrate/20260718000000_add_avm_provider_to_properties.rbnew file mode 100644index 0000000000..c85de8458a--- /dev/null+++ b/db/migrate/20260718000000_add_avm_provider_to_properties.rb@@ -0,0 +1,6 @@+class AddAvmProviderToProperties < ActiveRecord::Migration[7.2]+ def change+ add_column :properties, :avm_provider, :string+ add_column :properties, :avm_last_synced_on, :date+ end+enddiff --git a/db/migrate/20260719000000_create_provider_request_counts.rb b/db/migrate/20260719000000_create_provider_request_counts.rbnew file mode 100644index 0000000000..04d27f4392--- /dev/null+++ b/db/migrate/20260719000000_create_provider_request_counts.rb@@ -0,0 +1,13 @@+class CreateProviderRequestCounts < ActiveRecord::Migration[7.2]+ def change+ create_table :provider_request_counts, id: :uuid do |t|+ t.string :provider_key, null: false+ t.string :period, null: false+ t.integer :count, null: false, default: 0++ t.timestamps+ end++ add_index :provider_request_counts, [ :provider_key, :period ], unique: true+ end+enddiff --git a/db/migrate/20260719000001_add_avm_provider_check_to_properties.rb b/db/migrate/20260719000001_add_avm_provider_check_to_properties.rbnew file mode 100644index 0000000000..c667aa6882--- /dev/null+++ b/db/migrate/20260719000001_add_avm_provider_check_to_properties.rb@@ -0,0 +1,7 @@+class AddAvmProviderCheckToProperties < ActiveRecord::Migration[7.2]+ def change+ add_check_constraint :properties,+ "avm_provider IS NULL OR avm_provider IN ('rentcast', 'realie')",+ name: "properties_avm_provider_check"+ end+enddiff --git a/db/migrate/20260719000002_add_avm_sync_index_to_properties.rb b/db/migrate/20260719000002_add_avm_sync_index_to_properties.rbnew file mode 100644index 0000000000..7f8d3bc3a1--- /dev/null+++ b/db/migrate/20260719000002_add_avm_sync_index_to_properties.rb@@ -0,0 +1,11 @@+class AddAvmSyncIndexToProperties < ActiveRecord::Migration[7.2]+ def change+ # Keyed on avm_last_synced_on (matching the daily job's+ # ORDER BY avm_last_synced_on ASC NULLS FIRST) so the index also+ # serves the sort, not just the avm_provider IS NOT NULL filter.+ add_index :properties, :avm_last_synced_on,+ order: { avm_last_synced_on: "ASC NULLS FIRST" },+ where: "avm_provider IS NOT NULL",+ name: "index_properties_on_avm_provider_sync"+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 7d858b70bd..d743bd3448 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[7.2].define(version: 2026_07_14_120000) do+ActiveRecord::Schema[7.2].define(version: 2026_07_19_000002) do# These are extensions that must be enabled in order to support this databaseenable_extension "pgcrypto"enable_extension "plpgsql"@@ -1542,6 +1542,19 @@ ActiveRecord::Schema[7.2].define(version: 2026_07_14_120000) dot.string "area_unit"t.jsonb "locked_attributes", default: {}t.string "subtype"+ t.string "avm_provider"+ t.date "avm_last_synced_on"+ 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]::text[]))", name: "properties_avm_provider_check"+ end++ create_table "provider_request_counts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.integer "count", default: 0, null: false+ t.datetime "created_at", null: false+ t.string "period", null: false+ t.string "provider_key", null: false+ t.datetime "updated_at", null: false+ t.index ["provider_key", "period"], name: "index_provider_request_counts_on_provider_key_and_period", unique: trueendcreate_table "questrade_accounts", 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.rbindex 81ecd88f8c..fa4d7f19dd 100644--- a/test/controllers/properties_controller_test.rb+++ b/test/controllers/properties_controller_test.rb@@ -273,4 +273,268 @@ class PropertiesControllerTest < ActionDispatch::IntegrationTestassert draft_account.active?assert_redirected_to account_path(draft_account)end++ # AVM provider lookup tests+ def stub_avm_provider(response)+ provider = mock+ provider.stubs(:fetch_property_valuation).returns(response)+ Provider::Registry.stubs(:rentcast).returns(provider)+ provider+ end++ def successful_avm_response+ Provider::Response.new(+ success?: true,+ data: Provider::PropertyValuationConcept::PropertyValuation.new(+ valuation: 356_000,+ currency: "USD",+ property_type: "single_family_home",+ year_built: 1973,+ area_value: 1878,+ area_unit: "sqft"+ ),+ error: nil+ )+ end++ test "new shows method selector when an AVM provider is configured" do+ stub_avm_provider(successful_avm_response)++ get new_property_path(step: "method_select")++ assert_response :success+ assert_match "Add via RentCast", response.body+ end++ test "new skips method selector when no AVM provider is configured" do+ Provider::Registry.stubs(:rentcast).returns(nil)+ Provider::Registry.stubs(:realie).returns(nil)++ get new_property_path(step: "method_select")++ assert_response :success+ assert_match "Enter property manually", response.body+ end++ test "new renders AVM lookup form for a configured provider" do+ stub_avm_provider(successful_avm_response)++ get new_property_path(method: "rentcast")++ assert_response :success+ assert_match "Add property via RentCast", response.body+ end++ test "AVM lookup renders a preview without creating an account" do+ provider = mock+ provider.expects(:fetch_property_valuation).with(+ line1: "5500 Grand Lake Dr",+ locality: "San Antonio",+ region: "TX",+ postal_code: "78244"+ ).returns(successful_avm_response)+ Provider::Registry.stubs(:rentcast).returns(provider)++ assert_no_difference "Account.count" do+ post properties_path, params: {+ avm_provider: "rentcast",+ account: {+ name: "AVM Home",+ accountable_type: "Property",+ address: {+ line1: "5500 Grand Lake Dr",+ locality: "San Antonio",+ region: "TX",+ postal_code: "78244"+ }+ }+ }+ end++ assert_response :success+ assert_match "Confirm property details", response.body+ assert_match "1973", response.body+ assert_match "1878", response.body+ end++ test "AVM preview warns when no property record was found" do+ no_record = Provider::Response.new(+ success?: true,+ data: Provider::PropertyValuationConcept::PropertyValuation.new(+ valuation: 450_000, currency: "USD", property_type: nil, year_built: nil, area_value: nil, area_unit: "sqft"+ ),+ error: nil+ )+ stub_avm_provider(no_record)++ post properties_path, params: {+ avm_provider: "rentcast",+ account: {+ name: "AVM Home",+ accountable_type: "Property",+ address: { line1: "1 Ghost St", locality: "San Antonio", region: "TX", postal_code: "78244" }+ }+ }++ assert_response :success+ assert_match "couldn't find a property record", response.body+ assert_match "Unknown", response.body+ end++ def signed_preview_token(family: @user.family)+ Rails.application.message_verifier(:avm_preview).generate(+ {+ "provider_key" => "rentcast",+ "name" => "AVM Home",+ "address" => {+ "line1" => "5500 Grand Lake Dr",+ "locality" => "San Antonio",+ "region" => "TX",+ "postal_code" => "78244"+ },+ "data" => {+ "valuation" => "356000.0",+ "currency" => "USD",+ "property_type" => "single_family_home",+ "year_built" => "1973",+ "area_value" => "1878",+ "area_unit" => "sqft"+ }+ },+ expires_in: 1.hour,+ purpose: "avm_preview/family/#{family.id}"+ )+ end++ test "AVM confirm creates the account from the signed preview token without a provider call" do+ provider = mock+ provider.expects(:fetch_property_valuation).never+ Provider::Registry.stubs(:rentcast).returns(provider)++ assert_difference -> { Account.count } => 1 do+ post properties_path, params: {+ avm_provider: "rentcast",+ avm_step: "confirm",+ avm_preview_token: signed_preview_token,+ account: { accountable_type: "Property" }+ }+ end++ created_account = Account.order(:created_at).last+ assert_redirected_to account_path(created_account)+ assert created_account.active?+ assert_equal "AVM Home", created_account.name+ assert_equal 356_000, created_account.balance+ assert_equal "USD", created_account.currency++ property = created_account.accountable+ assert_equal "rentcast", property.avm_provider+ assert_equal Date.current, property.avm_last_synced_on+ assert_equal "single_family_home", property.subtype+ assert_equal 1973, property.year_built+ assert_equal 1878, property.area_value+ assert_equal "sqft", property.area_unit++ address = property.address+ assert_equal "5500 Grand Lake Dr", address.line1+ assert_equal "San Antonio", address.locality+ assert_equal "TX", address.region+ assert_equal "78244", address.postal_code+ assert_equal "US", address.country+ end++ test "re-renders lookup form when the AVM provider returns an error" do+ stub_avm_provider(+ Provider::Response.new(+ success?: false,+ data: nil,+ error: Provider::Rentcast::Error.new("RentCast could not find a property matching this address")+ )+ )++ assert_no_difference "Account.count" do+ post properties_path, params: {+ avm_provider: "rentcast",+ account: {+ name: "AVM Home",+ accountable_type: "Property",+ address: { line1: "1 Nowhere Ln", locality: "Nowhere", region: "TX", postal_code: "00000" }+ }+ }+ end++ assert_response :unprocessable_entity+ assert_match "could not find a property", response.body+ end++ test "rejects AVM confirm without a valid signed preview token" do+ provider = mock+ provider.expects(:fetch_property_valuation).never+ Provider::Registry.stubs(:rentcast).returns(provider)++ assert_no_difference "Account.count" do+ post properties_path, params: {+ avm_provider: "rentcast",+ avm_step: "confirm",+ avm_preview_token: "forged-token",+ account: { accountable_type: "Property" }+ }+ end++ assert_response :unprocessable_entity+ assert_match "preview has expired", response.body+ end++ test "rejects an AVM preview token minted for another family" do+ provider = mock+ provider.expects(:fetch_property_valuation).never+ Provider::Registry.stubs(:rentcast).returns(provider)++ assert_no_difference "Account.count" do+ post properties_path, params: {+ avm_provider: "rentcast",+ avm_step: "confirm",+ avm_preview_token: signed_preview_token(family: families(:empty)),+ account: { accountable_type: "Property" }+ }+ end++ assert_response :unprocessable_entity+ assert_match "preview has expired", response.body+ end++ test "rejects incomplete AVM submissions before calling the provider" do+ provider = mock+ provider.expects(:fetch_property_valuation).never+ Provider::Registry.stubs(:rentcast).returns(provider)++ assert_no_difference "Account.count" do+ post properties_path, params: {+ avm_provider: "rentcast",+ account: {+ name: "",+ accountable_type: "Property",+ address: { line1: "5500 Grand Lake Dr", locality: "", region: "TX", postal_code: "78244" }+ }+ }+ end++ assert_response :unprocessable_entity+ assert_match "complete US address", response.body+ end++ test "rejects AVM creation for unconfigured providers" do+ assert_no_difference "Account.count" do+ post properties_path, params: {+ avm_provider: "realie",+ account: {+ name: "AVM Home",+ accountable_type: "Property",+ address: { line1: "123 Main Street", locality: "LA", region: "CA", postal_code: "90001" }+ }+ }+ end++ assert_redirected_to new_property_path+ endenddiff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rbindex 08191008c0..085139df98 100644--- a/test/controllers/settings/hostings_controller_test.rb+++ b/test/controllers/settings/hostings_controller_test.rb@@ -12,6 +12,8 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest@provider.stubs(:health_status).returns(:healthy)Provider::Registry.stubs(:get_provider).with(:yahoo_finance).returns(@provider)+ Provider::Registry.stubs(:get_provider).with(:rentcast).returns(nil)+ Provider::Registry.stubs(:get_provider).with(:realie).returns(nil)@provider.stubs(:usage).returns(provider_success_response(OpenStruct.new(used: 10,@@ -25,7 +27,7 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTestteardown 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 llm_provider].each do |key|+ %i[anthropic_access_token anthropic_base_url anthropic_model llm_provider rentcast_api_key realie_api_key].each do |key|Setting.public_send("#{key}=", nil)endend@@ -50,6 +52,22 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTestendend+ test "can update rentcast api key when self hosting is enabled" do+ with_self_hosting do+ patch settings_hosting_url, params: { setting: { rentcast_api_key: "rentcast-token" } }++ assert_equal "rentcast-token", Setting.rentcast_api_key+ end+ end++ test "can update realie api key when self hosting is enabled" do+ with_self_hosting do+ patch settings_hosting_url, params: { setting: { realie_api_key: "realie-token" } }++ assert_equal "realie-token", Setting.realie_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/jobs/sync_property_valuations_job_test.rb b/test/jobs/sync_property_valuations_job_test.rbnew file mode 100644index 0000000000..5ae6ef95dd--- /dev/null+++ b/test/jobs/sync_property_valuations_job_test.rb@@ -0,0 +1,169 @@+require "test_helper"++class SyncPropertyValuationsJobTest < ActiveSupport::TestCase+ setup do+ @account = accounts(:property)+ @property = @account.property+ @property.update!(avm_provider: "rentcast")+ end++ def valuation_data(valuation: 600_000)+ Provider::PropertyValuationConcept::PropertyValuation.new(+ valuation: valuation,+ currency: "USD",+ property_type: "single_family_home",+ year_built: 1973,+ area_value: 1878,+ area_unit: "sqft"+ )+ end++ test "refreshes the valuation of linked properties via their provider" do+ provider = mock+ provider.stubs(:requests_remaining?).returns(true)+ provider.stubs(:valuation_currency).returns("USD")+ provider.expects(:fetch_property_valuation).with(+ line1: "123 Main Street",+ locality: "Los Angeles",+ region: "CA",+ postal_code: "90001"+ ).returns(Provider::Response.new(success?: true, data: valuation_data, error: nil))+ Provider::Registry.stubs(:rentcast).returns(provider)++ SyncPropertyValuationsJob.new.perform++ assert_equal Date.current, @property.reload.avm_last_synced_on+ assert_equal 600_000, @account.reload.balance+ end++ test "resolves each provider once per run across multiple properties" do+ second_account = @account.family.accounts.create!(+ name: "Second AVM Property",+ balance: 0,+ currency: "USD",+ owner: @account.owner,+ accountable: Property.new(+ avm_provider: "rentcast",+ address_attributes: { line1: "456 Oak Ave", locality: "Los Angeles", region: "CA", country: "US", postal_code: "90002" }+ )+ )++ provider = mock+ provider.stubs(:requests_remaining?).returns(true)+ provider.stubs(:valuation_currency).returns("USD")+ provider.stubs(:fetch_property_valuation).twice.returns(Provider::Response.new(success?: true, data: valuation_data, error: nil))+ Provider::Registry.expects(:rentcast).once.returns(provider)++ SyncPropertyValuationsJob.new.perform++ assert_equal Date.current, @property.reload.avm_last_synced_on+ assert_equal Date.current, second_account.property.reload.avm_last_synced_on+ end++ test "skips refresh when the account currency no longer matches the provider currency" do+ @account.update!(currency: "EUR")++ provider = mock+ provider.stubs(:requests_remaining?).returns(true)+ provider.stubs(:valuation_currency).returns("USD")+ provider.expects(:fetch_property_valuation).never+ Provider::Registry.stubs(:rentcast).returns(provider)++ assert_difference "DebugLogEntry.count" => 1 do+ SyncPropertyValuationsJob.new.perform+ end++ assert_nil @property.reload.avm_last_synced_on+ end++ test "skips properties with incomplete addresses without spending a request" do+ @property.address.update!(region: "")++ Provider::Registry.expects(:rentcast).never++ assert_difference "DebugLogEntry.count" => 1 do+ SyncPropertyValuationsJob.new.perform+ end++ assert_nil @property.reload.avm_last_synced_on+ end++ test "skips properties whose address city or ZIP was blanked" do+ @property.address.update!(locality: "")++ Provider::Registry.expects(:rentcast).never++ assert_difference "DebugLogEntry.count" => 1 do+ SyncPropertyValuationsJob.new.perform+ end++ assert_nil @property.reload.avm_last_synced_on+ end++ test "skips properties whose address is no longer in the US" do+ @property.address.update!(country: "CA")++ Provider::Registry.expects(:rentcast).never++ assert_difference "DebugLogEntry.count" => 1 do+ SyncPropertyValuationsJob.new.perform+ end++ assert_nil @property.reload.avm_last_synced_on+ end++ test "does not mark a property synced when the balance update fails" do+ provider = mock+ provider.stubs(:requests_remaining?).returns(true)+ provider.stubs(:valuation_currency).returns("USD")+ provider.stubs(:fetch_property_valuation).returns(Provider::Response.new(success?: true, data: valuation_data, error: nil))+ Provider::Registry.stubs(:rentcast).returns(provider)++ Account.any_instance.stubs(:set_current_balance).returns(+ Account::CurrentBalanceManager::Result.new(success?: false, changes_made?: false, error: "boom")+ )++ assert_difference "DebugLogEntry.count" => 1 do+ SyncPropertyValuationsJob.new.perform+ end++ assert_nil @property.reload.avm_last_synced_on+ end++ test "skips properties already refreshed today" do+ @property.update!(avm_last_synced_on: Date.current)++ provider = mock+ provider.expects(:fetch_property_valuation).never+ Provider::Registry.stubs(:rentcast).returns(provider)++ SyncPropertyValuationsJob.new.perform+ end++ test "skips refresh when the provider's monthly budget is spent" do+ provider = mock+ provider.stubs(:requests_remaining?).returns(false)+ provider.expects(:fetch_property_valuation).never+ Provider::Registry.stubs(:rentcast).returns(provider)++ SyncPropertyValuationsJob.new.perform++ assert_nil @property.reload.avm_last_synced_on+ end++ test "skips properties whose provider is no longer configured" do+ Provider::Registry.stubs(:rentcast).returns(nil)++ SyncPropertyValuationsJob.new.perform++ assert_nil @property.reload.avm_last_synced_on+ end++ test "does not touch properties without an AVM provider" do+ @property.update!(avm_provider: nil)++ Provider::Registry.expects(:rentcast).never++ SyncPropertyValuationsJob.new.perform+ end+enddiff --git a/test/models/provider/realie_test.rb b/test/models/provider/realie_test.rbnew file mode 100644index 0000000000..7818e30f1c--- /dev/null+++ b/test/models/provider/realie_test.rb@@ -0,0 +1,185 @@+require "test_helper"++class Provider::RealieTest < ActiveSupport::TestCase+ setup do+ @provider = Provider::Realie.new("test_api_key")+ @provider.stubs(:throttle_request)+ end++ def address_lookup_body(overrides = {})+ {+ "property" => {+ "useCode" => "Single Family Residential",+ "yearBuilt" => 1985,+ "buildingArea" => 1500.0,+ "modelValue" => 420_000.0,+ "modelValueMin" => 390_000.0,+ "modelValueMax" => 450_000.0,+ "totalMarketValue" => 400_000,+ "city" => "LOS ANGELES",+ "state" => "CA",+ "zipCode" => "90001"+ }.merge(overrides)+ }.to_json+ end++ test "fetches valuation and property attributes in a single request" do+ stub = stub_request(:get, "https://app.realie.ai/api/public/property/address/")+ .with(+ query: { "address" => "123 Main Street", "state" => "CA" },+ headers: { "Authorization" => "test_api_key" }+ )+ .to_return(status: 200, body: address_lookup_body)++ response = @provider.fetch_property_valuation(+ line1: "123 Main Street",+ locality: "Los Angeles",+ region: "CA",+ postal_code: "90001"+ )++ assert response.success?+ data = response.data+ assert_equal 420_000, data.valuation+ assert_equal "USD", data.currency+ assert_equal "single_family_home", data.property_type+ assert_equal 1985, data.year_built+ assert_equal 1500, data.area_value+ assert_equal "sqft", data.area_unit+ assert_requested stub+ end++ test "falls back to the assessed market value when no model value is present" do+ stub_request(:get, "https://app.realie.ai/api/public/property/address/")+ .with(query: hash_including("address" => "123 Main Street"))+ .to_return(status: 200, body: address_lookup_body("modelValue" => nil))++ response = @provider.fetch_property_valuation(line1: "123 Main Street", region: "CA")++ assert response.success?+ assert_equal 400_000, response.data.valuation+ end++ test "treats a zero model value as absent and falls back to the market value" do+ stub_request(:get, "https://app.realie.ai/api/public/property/address/")+ .with(query: hash_including("address" => "123 Main Street"))+ .to_return(status: 200, body: address_lookup_body("modelValue" => 0))++ response = @provider.fetch_property_valuation(line1: "123 Main Street", region: "CA")++ assert response.success?+ assert_equal 400_000, response.data.valuation+ end++ test "returns an error when both model and market values are zero" do+ stub_request(:get, "https://app.realie.ai/api/public/property/address/")+ .with(query: hash_including("address" => "123 Main Street"))+ .to_return(status: 200, body: address_lookup_body("modelValue" => 0, "totalMarketValue" => 0))++ response = @provider.fetch_property_valuation(line1: "123 Main Street", region: "CA")++ assert_not response.success?+ assert_match(/valuation/i, response.error.message)+ end++ test "picks the candidate matching the entered city and ZIP from multiple results" do+ wrong_city = { "useCode" => "Commercial", "yearBuilt" => 1970, "buildingArea" => 9_000.0, "modelValue" => 2_000_000.0, "city" => "SACRAMENTO", "state" => "CA", "zipCode" => "95814" }+ right_city = { "useCode" => "Single Family Residential", "yearBuilt" => 1985, "buildingArea" => 1500.0, "modelValue" => 420_000.0, "city" => "LOS ANGELES", "state" => "CA", "zipCode" => "90001" }++ stub_request(:get, "https://app.realie.ai/api/public/property/address/")+ .with(query: hash_including("address" => "123 Main Street"))+ .to_return(status: 200, body: { "property" => [ wrong_city, right_city ] }.to_json)++ response = @provider.fetch_property_valuation(+ line1: "123 Main Street",+ locality: "Los Angeles",+ region: "CA",+ postal_code: "90001"+ )++ assert response.success?+ assert_equal 420_000, response.data.valuation+ assert_equal "single_family_home", response.data.property_type+ assert_equal 1985, response.data.year_built+ end++ test "rejects a property matched in a different city or ZIP" do+ stub_request(:get, "https://app.realie.ai/api/public/property/address/")+ .with(query: hash_including("address" => "123 Main Street"))+ .to_return(status: 200, body: address_lookup_body("city" => "SACRAMENTO", "zipCode" => "95814"))++ response = @provider.fetch_property_valuation(+ line1: "123 Main Street",+ locality: "Los Angeles",+ region: "CA",+ postal_code: "90001"+ )++ assert_not response.success?+ assert_match(/different city or zip/i, response.error.message)+ end++ test "returns a friendly error when no property matches the address" do+ stub_request(:get, "https://app.realie.ai/api/public/property/address/")+ .with(query: hash_including("address" => "1 Nowhere Ln"))+ .to_return(status: 404, body: { "detail" => "Not found" }.to_json)++ response = @provider.fetch_property_valuation(line1: "1 Nowhere Ln", region: "CA")++ assert_not response.success?+ assert_match(/could not find a property/i, response.error.message)+ end++ test "maps documented numeric use codes to property subtypes" do+ {+ "1001" => "single_family_home",+ "1002" => "townhouse",+ "1004" => "condominium",+ "1101" => "multi_family_home",+ "1104" => "apartment",+ "7001" => "agri_land",+ "8001" => "plot",+ "1006" => nil, # mobile/manufactured — no subtype equivalent+ "9999" => nil # unknown numeric code+ }.each do |use_code, expected|+ actual = @provider.send(:subtype_for_use_code, use_code)+ if expected.nil?+ assert_nil actual, "expected #{use_code.inspect} to map to nil"+ else+ assert_equal expected, actual, "expected #{use_code.inspect} to map to #{expected.inspect}"+ end+ end+ end++ test "maps use codes to property subtypes by keyword" do+ {+ "Single Family Residential" => "single_family_home",+ "Duplex (2 units)" => "multi_family_home",+ "Residential Condominium" => "condominium",+ "Townhouse" => "townhouse",+ "Vacant Land" => "plot",+ "Commercial Office" => "commercial",+ "Agricultural" => "agri_land",+ "Something Unrecognized" => nil+ }.each do |use_code, expected|+ actual = @provider.send(:subtype_for_use_code, use_code)+ if expected.nil?+ assert_nil actual, "expected #{use_code.inspect} to map to nil"+ else+ assert_equal expected, actual, "expected #{use_code.inspect} to map to #{expected.inspect}"+ end+ end+ end++ test "stops issuing requests once the monthly limit is reached" do+ ProviderRequestCount.create!(provider_key: "realie", period: ProviderRequestCount.current_period, count: Provider::Realie::MAX_REQUESTS_PER_MONTH)++ assert_not @provider.requests_remaining?++ response = @provider.fetch_property_valuation(line1: "123 Main Street", region: "CA")++ assert_not response.success?+ assert_instance_of Provider::Realie::RateLimitError, response.error+ assert_not_requested :get, %r{app\.realie\.ai}+ end+enddiff --git a/test/models/provider/rentcast_test.rb b/test/models/provider/rentcast_test.rbnew file mode 100644index 0000000000..e0e1fde054--- /dev/null+++ b/test/models/provider/rentcast_test.rb@@ -0,0 +1,96 @@+require "test_helper"++class Provider::RentcastTest < ActiveSupport::TestCase+ setup do+ @provider = Provider::Rentcast.new("test_api_key")+ @provider.stubs(:throttle_request)+ end++ def avm_response_body+ {+ "price" => 356_000,+ "priceRangeLow" => 330_000,+ "priceRangeHigh" => 382_000,+ "subjectProperty" => {+ "formattedAddress" => "5500 Grand Lake Dr, San Antonio, TX 78244",+ "propertyType" => "Single Family",+ "yearBuilt" => 1973,+ "squareFootage" => 1878+ }+ }.to_json+ end++ test "fetches valuation and property attributes in a single request" do+ stub = stub_request(:get, "https://api.rentcast.io/v1/avm/value")+ .with(+ query: {+ "address" => "5500 Grand Lake Dr, San Antonio, TX, 78244",+ "lookupSubjectAttributes" => "true"+ },+ headers: { "X-Api-Key" => "test_api_key" }+ )+ .to_return(status: 200, body: avm_response_body)++ response = @provider.fetch_property_valuation(+ line1: "5500 Grand Lake Dr",+ locality: "San Antonio",+ region: "TX",+ postal_code: "78244"+ )++ assert response.success?+ data = response.data+ assert_equal 356_000, data.valuation+ assert_equal "USD", data.currency+ assert_equal "single_family_home", data.property_type+ assert_equal 1973, data.year_built+ assert_equal 1878, data.area_value+ assert_equal "sqft", data.area_unit+ assert_requested stub+ end++ test "returns a friendly error when no property matches the address" do+ stub_request(:get, "https://api.rentcast.io/v1/avm/value")+ .with(query: hash_including("address" => "1 Nowhere Ln"))+ .to_return(status: 404, body: { "error" => "Not found" }.to_json)++ 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 "counts requests against the monthly budget" do+ stub_request(:get, "https://api.rentcast.io/v1/avm/value")+ .with(query: hash_including("lookupSubjectAttributes" => "true"))+ .to_return(status: 200, body: avm_response_body)++ assert @provider.requests_remaining?++ @provider.fetch_property_valuation(line1: "5500 Grand Lake Dr")++ assert_equal 1, ProviderRequestCount.count_for("rentcast")+ end++ test "monthly limit can be raised via ENV override" do+ ProviderRequestCount.create!(provider_key: "rentcast", period: ProviderRequestCount.current_period, count: Provider::Rentcast::MAX_REQUESTS_PER_MONTH)++ ENV["RENTCAST_MAX_REQUESTS_PER_MONTH"] = "100"+ assert @provider.requests_remaining?+ ensure+ ENV.delete("RENTCAST_MAX_REQUESTS_PER_MONTH")+ end++ test "stops issuing requests once the monthly limit is reached" do+ ProviderRequestCount.create!(provider_key: "rentcast", period: ProviderRequestCount.current_period, count: Provider::Rentcast::MAX_REQUESTS_PER_MONTH)++ assert_not @provider.requests_remaining?++ response = @provider.fetch_property_valuation(line1: "5500 Grand Lake Dr")++ assert_not response.success?+ assert_instance_of Provider::Rentcast::RateLimitError, response.error+ assert_equal Provider::Rentcast::MAX_REQUESTS_PER_MONTH, ProviderRequestCount.count_for("rentcast")+ assert_not_requested :get, %r{api\.rentcast\.io}+ end+enddiff --git a/test/models/provider_request_count_test.rb b/test/models/provider_request_count_test.rbnew file mode 100644index 0000000000..d3833099b3--- /dev/null+++ b/test/models/provider_request_count_test.rb@@ -0,0 +1,31 @@+require "test_helper"++class ProviderRequestCountTest < ActiveSupport::TestCase+ test "increment! creates the counter and returns the new count" do+ assert_equal 1, ProviderRequestCount.increment!("rentcast")+ assert_equal 2, ProviderRequestCount.increment!("rentcast")+ assert_equal 2, ProviderRequestCount.count_for("rentcast")+ end++ test "counts are scoped per provider and period" do+ ProviderRequestCount.increment!("rentcast")+ ProviderRequestCount.increment!("realie")+ ProviderRequestCount.increment!("rentcast", period: "2020-01")++ assert_equal 1, ProviderRequestCount.count_for("rentcast")+ assert_equal 1, ProviderRequestCount.count_for("realie")+ assert_equal 1, ProviderRequestCount.count_for("rentcast", period: "2020-01")+ end++ test "decrement! floors at zero" do+ ProviderRequestCount.increment!("rentcast")+ ProviderRequestCount.decrement!("rentcast")+ ProviderRequestCount.decrement!("rentcast")++ assert_equal 0, ProviderRequestCount.count_for("rentcast")+ end++ test "count_for returns zero when no counter exists" do+ assert_equal 0, ProviderRequestCount.count_for("rentcast")+ end+enddiff --git a/test/system/settings_test.rb b/test/system/settings_test.rbindex 954c152668..c02c14d00e 100644--- a/test/system/settings_test.rb+++ b/test/system/settings_test.rb@@ -54,6 +54,8 @@ class SettingsTest < ApplicationSystemTestCaseRails.application.config.app_mode.stubs(:self_hosted?).returns(true)Provider::Registry.stubs(:get_provider).with(:twelve_data).returns(nil)Provider::Registry.stubs(:get_provider).with(:yahoo_finance).returns(nil)+ Provider::Registry.stubs(:get_provider).with(:rentcast).returns(nil)+ Provider::Registry.stubs(:get_provider).with(:realie).returns(nil)Provider::Registry.stubs(:get_provider).with(:github).returns(stub(fetch_latest_release_notes: nil))open_settings_from_sidebarassert_selector "li", text: "Self-Hosting"