Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add Chimnie provider for UK property valuations (#4135)

ljefferies98a8fac993910f
diff --git a/.env.example b/.env.example
index f6558c1812..fd7f7fe6f4 100644
--- a/.env.example
+++ b/.env.example
@@ -136,6 +136,12 @@ SECURITIES_PROVIDER=yahoo_finance
# Brandfetch to grab logos for banks and merchants
BRAND_FETCH_CLIENT_ID=
+# Optional: Chimnie API key for automatic UK property valuations by UPRN
+# (you can also set this in your self-hosted settings page)
+# Get a free key here: https://dashboard.chimnie.com (requires a business or custom-domain email)
+CHIMNIE_API_KEY=
+# CHIMNIE_MAX_REQUESTS_PER_MONTH=1000
+
# Custom port config
# For users who have other applications listening at 3000, this allows them to set a value puma will listen to.
PORT=3000
diff --git a/app/controllers/properties_controller.rb b/app/controllers/properties_controller.rb
index 3e069d853e..622c65b800 100644
--- a/app/controllers/properties_controller.rb
+++ b/app/controllers/properties_controller.rb
@@ -1,8 +1,10 @@
class PropertiesController < ApplicationController
include AccountableResource, StreamExtensions
- before_action :set_property, only: [ :balances, :address, :update_balances, :update_address ]
- before_action :require_property_write_permission!, only: [ :update_balances, :update_address ]
+ before_action :set_property, only: [ :balances, :address, :update_balances, :update_address, :refresh_valuation ]
+ before_action :require_property_write_permission!, only: [ :update_balances, :update_address, :refresh_valuation ]
+
+ helper_method :avm_provider_class
def new
@account = Current.family.accounts.build(accountable: Property.new)
@@ -68,6 +70,22 @@ class PropertiesController < ApplicationController
end
end
+ # Manual refresh bypasses the provider's automatic refresh interval (e.g.
+ # Chimnie's monthly cadence) but still counts against its request budget.
+ def refresh_valuation
+ unless @property.avm_provider.present?
+ redirect_back_or_to account_path(@account), alert: t(".not_linked") and return
+ end
+
+ unless configured_avm_providers.map(&:to_s).include?(@property.avm_provider)
+ redirect_back_or_to account_path(@account),
+ alert: t(".not_configured", provider: t("properties.avm_providers.#{@property.avm_provider}")) and return
+ end
+
+ SyncPropertyValuationsJob.perform_later(property_id: @property.id, force: true)
+ redirect_back_or_to account_path(@account), notice: t(".queued")
+ end
+
def address
@property = @account.property
@property.address ||= Address.new
@@ -123,7 +141,8 @@ class PropertiesController < ApplicationController
owner: Current.user,
provider_key: payload["provider_key"],
name: payload["name"],
- address_attributes: payload["address"].symbolize_keys
+ address_attributes: payload["address"].symbolize_keys,
+ external_id: payload["external_id"]
)
@account = importer.create_account(avm_data_from_payload(payload))
@@ -145,7 +164,8 @@ class PropertiesController < ApplicationController
owner: Current.user,
provider_key: provider_key,
name: params.dig(:account, :name),
- address_attributes: avm_address_params.to_h.symbolize_keys
+ address_attributes: avm_address_params.to_h.symbolize_keys,
+ external_id: avm_external_id_param
)
@avm_preview = importer.lookup
@@ -154,6 +174,7 @@ class PropertiesController < ApplicationController
"provider_key" => provider_key,
"name" => params.dig(:account, :name),
"address" => avm_address_params.to_h,
+ "external_id" => avm_external_id_param,
"data" => @avm_preview.to_h.transform_values(&:to_s)
},
expires_in: 1.hour,
@@ -171,6 +192,7 @@ class PropertiesController < ApplicationController
# 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 || {})
+ @avm_external_id = avm_external_id_param
render :new, status: :unprocessable_entity
end
@@ -178,6 +200,12 @@ class PropertiesController < ApplicationController
params.require(:account).require(:address).permit(:line1, :locality, :region, :postal_code)
end
+ # Provider-side property identifier (e.g. a UK UPRN), for providers that
+ # look properties up by ID rather than address.
+ def avm_external_id_param
+ params.dig(:account, :property, :avm_external_id).to_s.strip.presence
+ end
+
def avm_preview_verifier
Rails.application.message_verifier(:avm_preview)
end
@@ -206,10 +234,20 @@ class PropertiesController < ApplicationController
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"
+ area_unit: raw["area_unit"].presence || "sqft",
+ external_id: raw["external_id"].presence,
+ valuation_low: raw["valuation_low"].presence&.to_d,
+ valuation_high: raw["valuation_high"].presence&.to_d,
+ confidence: raw["confidence"].presence
)
end
+ # Lets the lookup form adapt to what the provider needs (e.g. a UPRN
+ # instead of a full US address).
+ def avm_provider_class(key)
+ Provider::PropertyValuationConcept.provider_class(key)
+ end
+
def configured_avm_providers
registry = Provider::Registry.for_concept(:property_valuations)
registry.provider_keys.select { |key| registry.get_provider(key).present? }
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb
index fc44b57f98..8ade7145dc 100644
--- a/app/controllers/settings/hostings_controller.rb
+++ b/app/controllers/settings/hostings_controller.rb
@@ -56,6 +56,7 @@ class Settings::HostingsController < ApplicationController
# monthly request caps when a key is configured
@rentcast_usage = Provider::Registry.get_provider(:rentcast)&.usage
@realie_usage = Provider::Registry.get_provider(:realie)&.usage
+ @chimnie_usage = Provider::Registry.get_provider(:chimnie)&.usage
load_external_assistant_models
end
@@ -150,6 +151,7 @@ class Settings::HostingsController < ApplicationController
update_encrypted_setting(:mansa_api_key)
update_encrypted_setting(:rentcast_api_key)
update_encrypted_setting(:realie_api_key)
+ update_encrypted_setting(:chimnie_api_key)
if hosting_params.key?(:syncs_include_pending)
Setting.syncs_include_pending = hosting_params[:syncs_include_pending] == "1"
@@ -324,7 +326,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, :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, :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, :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, :external_assistant_url, :external_assistant_token, :external_assistant_model, securities_providers: [])
end
def load_external_assistant_models
diff --git a/app/jobs/sync_property_valuations_job.rb b/app/jobs/sync_property_valuations_job.rb
index b41279e7ef..6aed73c106 100644
--- a/app/jobs/sync_property_valuations_job.rb
+++ b/app/jobs/sync_property_valuations_job.rb
@@ -1,14 +1,18 @@
# 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.
+# Scheduled monthly (see config/schedule.yml) 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, and sets a minimum
+# interval between refreshes of the same property (`refresh_interval`).
+#
+# Pass `property_id:` with `force: true` for a user-requested refresh of a
+# single property, which skips the refresh interval.
class SyncPropertyValuationsJob < ApplicationJob
queue_as :scheduled
sidekiq_options lock: :until_executed, on_conflict: :log
- def perform
+ def perform(property_id: nil, force: false)
registry = Provider::Registry.for_concept(:property_valuations)
# Stalest valuations first (never-synced before oldest-refreshed) so a
@@ -17,26 +21,33 @@ class SyncPropertyValuationsJob < ApplicationJob
properties = Property.where.not(avm_provider: nil)
.includes(:address, :account)
.order(Arel.sql("avm_last_synced_on ASC NULLS FIRST"))
+ properties = properties.where(id: property_id) if property_id.present?
# 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 = {}
+ # Providers that hit their rate limit during this run; no further
+ # requests are sent to them until the next run.
+ rate_limited = Set.new
+
properties.each do |property|
account = property.account
next unless account&.active?
- next if property.avm_last_synced_on == Date.current
+ next if rate_limited.include?(property.avm_provider)
+
+ provider_class = Provider::PropertyValuationConcept.provider_class(property.avm_provider)
+ next unless provider_class
+ next if !force && recently_synced?(property, provider_class)
# 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")
+ # another property's valuation; ID-based providers (Chimnie) need the
+ # property's UPRN. Each provider covers a single country.
+ unless provider_class.lookup_ready?(property.address, property.avm_external_id)
+ capture_failure(property, account, "Skipping refresh: property address or identifier is incomplete, or the property is outside #{provider_class.supported_country}", level: "warn")
next
end
@@ -49,7 +60,10 @@ class SyncPropertyValuationsJob < ApplicationJob
end
provider = providers[property.avm_provider]
- next unless provider # API key was removed after the property was linked
+ unless provider # API key was removed after the property was linked
+ capture_failure(property, account, "Skipping refresh: #{property.avm_provider} is not configured", level: "warn")
+ next
+ end
next unless provider.requests_remaining?
# The account was created in the provider's currency, but the user can
@@ -60,18 +74,23 @@ class SyncPropertyValuationsJob < ApplicationJob
next
end
- response = provider.fetch_property_valuation(
+ address = property.address
+ lookup_params = {
line1: address.line1,
locality: address.locality,
region: address.region,
postal_code: address.postal_code
- )
+ }
+ lookup_params[:external_id] = property.avm_external_id if provider_class.requires_external_id?
+
+ response = provider.fetch_property_valuation(**lookup_params)
if response.success?
result = nil
Property.transaction do
result = account.set_current_balance(response.data.valuation)
raise ActiveRecord::Rollback unless result.success?
+ property.name_avm_valuation!
property.update!(avm_last_synced_on: Date.current)
end
@@ -79,6 +98,7 @@ class SyncPropertyValuationsJob < ApplicationJob
capture_failure(property, account, "Failed to update valuation balance: #{result&.error}")
end
else
+ rate_limited << property.avm_provider if response.error.is_a?(provider_class::RateLimitError)
capture_failure(property, account, "Valuation refresh failed: #{response.error.message}")
end
rescue => e
@@ -88,6 +108,12 @@ class SyncPropertyValuationsJob < ApplicationJob
private
+ # RentCast and Realie refresh at most daily; Chimnie at most monthly.
+ def recently_synced?(property, provider_class)
+ property.avm_last_synced_on.present? &&
+ property.avm_last_synced_on > Date.current - provider_class.refresh_interval
+ end
+
def capture_failure(property, account, message, level: "error")
DebugLogEntry.capture(
category: "provider_sync_error",
diff --git a/app/models/account/reconciliation_manager.rb b/app/models/account/reconciliation_manager.rb
index dd6915f34c..242ab2d0df 100644
--- a/app/models/account/reconciliation_manager.rb
+++ b/app/models/account/reconciliation_manager.rb
@@ -94,6 +94,13 @@ class Account::ReconciliationManager
currency: account.currency
)
+ # A provider may have labelled this day's reconciliation (see
+ # Property#name_avm_valuation!); a later write — e.g. a manual edit —
+ # goes back to the default name, and providers relabel after their own.
+ if valuation_record.entryable.is_a?(Valuation) && valuation_record.entryable.reconciliation?
+ valuation_record.name = Valuation.build_reconciliation_name(account.accountable_type)
+ end
+
valuation_record
end
diff --git a/app/models/property.rb b/app/models/property.rb
index c04b68cdc5..e49a43bdd7 100644
--- a/app/models/property.rb
+++ b/app/models/property.rb
@@ -54,6 +54,20 @@ class Property < ApplicationRecord
"original purchase price"
end
+ # Balance updates are recorded as "Manual value update" reconciliations;
+ # rename the one an AVM provider just wrote so the activity feed shows
+ # where the value came from. Account::ReconciliationManager resets the name
+ # on any later write to that day's entry.
+ def name_avm_valuation!(date = Date.current)
+ return if avm_provider.blank?
+
+ entry = account.entries.valuations.find_by(date: date)
+ return unless entry&.entryable&.reconciliation?
+
+ provider_name = I18n.t("properties.avm_providers.#{avm_provider}", default: avm_provider.titleize)
+ entry.update!(name: I18n.t("providers.property_valuation.entry_name", provider: provider_name))
+ end
+
private
def first_valuation_amount
account.entries.valuations.order(:date).first&.amount_money || account.balance_money
diff --git a/app/models/property/avm_import.rb b/app/models/property/avm_import.rb
index 3ac7982777..b290fc33f2 100644
--- a/app/models/property/avm_import.rb
+++ b/app/models/property/avm_import.rb
@@ -6,12 +6,13 @@
class Property::AvmImport
Error = Class.new(StandardError)
- def initialize(family:, owner:, provider_key:, name:, address_attributes:)
+ def initialize(family:, owner:, provider_key:, name:, address_attributes:, external_id: nil)
@family = family
@owner = owner
@provider_key = provider_key.to_s
@name = name
@address_attributes = address_attributes
+ @external_id = external_id.to_s.strip.presence
end
# Step 1: validates the inputs, then spends one provider request. Returns
@@ -22,12 +23,15 @@ class Property::AvmImport
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(
+ lookup_params = {
line1: address_attributes[:line1],
locality: address_attributes[:locality],
region: address_attributes[:region],
postal_code: address_attributes[:postal_code]
- )
+ }
+ lookup_params[:external_id] = external_id if provider_class.requires_external_id?
+
+ response = provider.fetch_property_valuation(**lookup_params)
raise Error.new(response.error.message) unless response.success?
response.data
@@ -52,15 +56,17 @@ class Property::AvmImport
area_value: data.area_value,
area_unit: data.area_unit,
avm_provider: provider_key,
+ avm_external_id: data.external_id.presence || external_id,
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")
+ # Each provider covers a single country, so the country isn't
+ # collected in the lookup form.
+ address_attributes: address_attributes.merge(country: provider_class.supported_country)
)
)
result = account.set_current_balance(data.valuation)
raise Error.new(result.error) unless result.success?
+ account.property.name_avm_valuation!
account.activate!
end
@@ -72,15 +78,20 @@ class Property::AvmImport
end
private
- attr_reader :family, :owner, :provider_key, :name, :address_attributes
+ attr_reader :family, :owner, :provider_key, :name, :address_attributes, :external_id
+
+ def provider_class
+ @provider_class ||= Provider::PropertyValuationConcept.provider_class(provider_key) ||
+ raise(Error.new(I18n.t("providers.property_valuation.not_configured")))
+ end
# 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? }
+ return unless name.blank? || !provider_class.lookup_ready?(address_attributes, external_id)
- raise Error.new(I18n.t("providers.property_valuation.missing_fields")) if missing
+ message_key = provider_class.supported_country == "GB" ? "missing_fields_gb" : "missing_fields"
+ raise Error.new(I18n.t("providers.property_valuation.#{message_key}"))
end
end
diff --git a/app/models/provider/chimnie.rb b/app/models/provider/chimnie.rb
new file mode 100644
index 0000000000..c3fdea626a
--- /dev/null
+++ b/app/models/provider/chimnie.rb
@@ -0,0 +1,160 @@
+class Provider::Chimnie < Provider
+ include PropertyValuationConcept, RateLimitable
+ extend SslConfigurable
+
+ # Subclass so errors caught in this provider are raised as Provider::Chimnie::Error
+ Error = Class.new(Provider::Error)
+ RateLimitError = Class.new(Error)
+
+ # Chimnie's free UPRN valuations are limited to 1 request per second.
+ MIN_REQUEST_INTERVAL = 1.1
+
+ # UPRN valuations are free, so this is a safety cap rather than a plan
+ # limit. Override with CHIMNIE_MAX_REQUESTS_PER_MONTH.
+ MAX_REQUESTS_PER_MONTH = 1000
+
+ # Only these fields are free when requested by UPRN — asking for anything
+ # else (property type, floor area, ...) makes the request billable.
+ FREE_VALUATION_FIELDS = %w[
+ property.value.sale.property_value
+ property.value.sale.property_value_range
+ property.value.sale.property_value_confidence
+ ].freeze
+
+ UPRN_FORMAT = /\A\d{1,12}\z/
+
+ # Runs a hook immediately before every HTTP attempt, including retries, so
+ # each one is throttled and counted against the monthly budget.
+ class BeforeEachAttempt < Faraday::Middleware
+ def initialize(app, hook)
+ super(app)
+ @hook = hook
+ end
+
+ def on_request(_env)
+ @hook.call
+ end
+ end
+
+ def initialize(api_key)
+ @api_key = api_key # pipelock:ignore
+ end
+
+ # Looks up a UK residential property by its UPRN (Unique Property
+ # Reference Number). The address isn't sent — UPRN lookups are free,
+ # address lookups are charged.
+ def fetch_property_valuation(line1: nil, locality: nil, region: nil, postal_code: nil, external_id: nil)
+ with_provider_response do
+ uprn = self.class.normalize_uprn(external_id)
+ raise Error.new(I18n.t("providers.chimnie.errors.invalid_uprn")) if uprn.nil?
+
+ response = client.get("#{base_url}/residential/uprn/#{uprn}") do |req|
+ req.params["fields"] = FREE_VALUATION_FIELDS.join(",")
+ end
+
+ parsed = JSON.parse(response.body)
+ sale = parsed.dig("property", "value", "sale") || {}
+ value = sale["property_value"]
+ raise Error.new(I18n.t("providers.chimnie.errors.no_estimate")) if value.blank? || value.to_d <= 0
+
+ low, high = Array(sale["property_value_range"])
+
+ PropertyValuation.new(
+ valuation: BigDecimal(value.to_s),
+ currency: valuation_currency,
+ property_type: nil,
+ year_built: nil,
+ area_value: nil,
+ area_unit: "sqft",
+ external_id: parsed["id"].presence&.to_s || uprn,
+ valuation_low: low.present? ? BigDecimal(low.to_s) : nil,
+ valuation_high: high.present? ? BigDecimal(high.to_s) : nil,
+ confidence: sale["property_value_confidence"].presence&.downcase
+ )
+ end
+ end
+
+ # Strips the spaces people copy from council tax bills; returns nil when
+ # the result isn't a valid UPRN.
+ def self.normalize_uprn(value)
+ uprn = value.to_s.gsub(/\s+/, "")
+ uprn.match?(UPRN_FORMAT) ? uprn : nil
+ end
+
+ def self.valuation_currency
+ "GBP"
+ end
+
+ def self.supported_country
+ "GB"
+ end
+
+ def self.requires_external_id?
+ true
+ end
+
+ # The address is kept for display only; lookups go by UPRN. UK addresses
+ # often have no county, so region isn't required.
+ def self.required_address_fields
+ %i[line1 postal_code]
+ end
+
+ # AVM estimates don't move day to day; refreshing monthly keeps well
+ # inside the free tier's rate limit.
+ def self.refresh_interval
+ 1.month
+ end
+
+ private
+ attr_reader :api_key
+
+ def default_error_transformer(error)
+ case error
+ when Faraday::UnauthorizedError
+ Error.new(I18n.t("providers.chimnie.errors.unauthorized"))
+ when Faraday::ResourceNotFound
+ Error.new(I18n.t("providers.chimnie.errors.not_found"))
+ when Faraday::ConflictError
+ Error.new(I18n.t("providers.chimnie.errors.unsupported_property"))
+ when Faraday::ClientError
+ if error.response&.dig(:status) == 402
+ Error.new(I18n.t("providers.chimnie.errors.insufficient_balance"))
+ else
+ super
+ end
+ else
+ super
+ end
+ end
+
+ def base_url
+ ENV["CHIMNIE_URL"] || "https://api.chimnie.com"
+ end
+
+ def client
+ @client ||= Faraday.new(url: base_url, ssl: self.class.faraday_ssl_options) do |faraday|
+ # 429s are retried too: the 1 request/second limit is per API key, so
+ # concurrent lookups or refresh jobs in other processes can trip it
+ # despite the per-instance throttle. Chimnie sends no Retry-After, so
+ # back off from 1s.
+ faraday.request(:retry, {
+ max: 3,
+ interval: 1.0,
+ interval_randomness: 0.5,
+ backoff_factor: 2,
+ exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [ Faraday::ConnectionFailed, Faraday::TooManyRequestsError ]
+ })
+ # After the retry middleware, so it runs for each attempt.
+ faraday.use BeforeEachAttempt, -> {
+ throttle_request
+ record_monthly_request!
+ }
+ faraday.request :json
+ faraday.response :raise_error
+ faraday.options.timeout = 10
+ faraday.options.open_timeout = 5
+ faraday.headers["Authorization"] = "Bearer #{api_key}"
+ faraday.headers["Accept"] = "application/json"
+ end
+ end
+end
diff --git a/app/models/provider/metadata.rb b/app/models/provider/metadata.rb
index 1f8bed821b..f696ce35cc 100644
--- a/app/models/provider/metadata.rb
+++ b/app/models/provider/metadata.rb
@@ -27,7 +27,11 @@ class Provider
plaid_eu: { region: "EU", kinds: %w[Bank], maturity: :stable, logo_text: "PL", logo_color: "#4f46e5", domain: "plaid.com", tier: "Paid", name: "Plaid EU" },
questrade: { region: "CA", kinds: %w[Investment], maturity: :beta, logo_text: "QT", logo_color: "#0d9488", domain: "questrade.com" },
redbark: { region: "AU", kinds: %w[Bank], maturity: :beta, logo_text: "RB", logo_color: "#b91c1c", domain: "redbark.com" },
- onchain_wallet: { region: "Global", kinds: %w[Crypto], maturity: :alpha, logo_text: "OC", logo_color: "#d97706", domain: nil, logo_icon: "wallet", name: "On-chain wallets" }
+ onchain_wallet: { region: "Global", kinds: %w[Crypto], maturity: :alpha, logo_text: "OC", logo_color: "#d97706", domain: nil, logo_icon: "wallet", name: "On-chain wallets" },
+ # Property valuation (AVM) providers
+ rentcast: { region: "US", kinds: %w[Property], maturity: :beta, logo_text: "RC", logo_color: "#2563eb", domain: "rentcast.io", name: "RentCast" },
+ realie: { region: "US", kinds: %w[Property], maturity: :beta, logo_text: "RE", logo_color: "#0d9488", domain: "realie.ai" },
+ chimnie: { region: "UK", kinds: %w[Property], maturity: :beta, logo_text: "CH", logo_color: "#db2777", domain: "chimnie.com" }
}.freeze
def self.for(provider_key)
diff --git a/app/models/provider/property_valuation_concept.rb b/app/models/provider/property_valuation_concept.rb
index 4629b3bcf1..ac257adbf0 100644
--- a/app/models/provider/property_valuation_concept.rb
+++ b/app/models/provider/property_valuation_concept.rb
@@ -1,6 +1,6 @@
# 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.
+# 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
@@ -8,17 +8,83 @@
module Provider::PropertyValuationConcept
extend ActiveSupport::Concern
- PropertyValuation = Data.define(:valuation, :currency, :property_type, :year_built, :area_value, :area_unit)
+ COUNTRY_ALIASES = {
+ "US" => %w[US USA],
+ "GB" => %w[GB UK GBR]
+ }.freeze
- def fetch_property_valuation(line1:, locality: nil, region: nil, postal_code: nil)
+ # `external_id` is the provider's own identifier for the property (e.g. a
+ # UK UPRN). The range and confidence are optional; not every provider
+ # returns them.
+ PropertyValuation = Data.define(
+ :valuation, :currency, :property_type, :year_built, :area_value, :area_unit,
+ :external_id, :valuation_low, :valuation_high, :confidence
+ ) do
+ def initialize(external_id: nil, valuation_low: nil, valuation_high: nil, confidence: nil, **rest)
+ super
+ end
+ end
+
+ # The provider class for a registered property valuation provider key, for
+ # checking its capabilities (country, required fields, refresh interval)
+ # without building an instance or needing an API key.
+ def self.provider_class(key)
+ return nil unless Provider::Registry.for_concept(:property_valuations).provider_keys.map(&:to_s).include?(key.to_s)
+
+ "Provider::#{key.to_s.camelize}".safe_constantize
+ end
+
+ # Capabilities are class-level so eligibility can be checked before a
+ # provider instance (and its API key) is resolved. Providers override
+ # these with `def self.…`.
+ class_methods do
+ # Currency of the valuations this provider returns.
+ def valuation_currency
+ "USD"
+ end
+
+ # ISO 3166-1 alpha-2 code of the country the provider covers.
+ def supported_country
+ "US"
+ end
+
+ # Whether lookups need the provider's own property identifier (passed as
+ # `external_id:`) rather than the address.
+ def requires_external_id?
+ false
+ end
+
+ def required_address_fields
+ %i[line1 locality region postal_code]
+ end
+
+ # Minimum time between automatic refreshes of the same property.
+ def refresh_interval
+ 1.day
+ end
+
+ # Whether a lookup can be made for this address/identifier — checked
+ # before spending a request, both when creating a property and when
+ # refreshing.
+ def lookup_ready?(address, external_id = nil)
+ return false if address.nil?
+ return false if required_address_fields.any? { |field| address[field].blank? }
+ return false if requires_external_id? && external_id.blank?
+
+ country = address[:country].to_s.strip.upcase
+ country.blank? || COUNTRY_ALIASES.fetch(supported_country, [ supported_country ]).include?(country)
+ end
+ end
+
+ # `external_id:` is only passed to providers that `requires_external_id?`.
+ def fetch_property_valuation(line1:, locality: nil, region: nil, postal_code: nil, external_id: 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.
+ # The refresh job checks this against the account currency before
+ # spending a request.
def valuation_currency
- "USD"
+ self.class.valuation_currency
end
# Whether the provider still has monthly request budget left. Checked by
diff --git a/app/models/provider/registry.rb b/app/models/provider/registry.rb
index 3a74fb08c6..6ffdcc730c 100644
--- a/app/models/provider/registry.rb
+++ b/app/models/provider/registry.rb
@@ -192,6 +192,14 @@ class Provider::Registry
Provider::Realie.new(api_key)
end
+
+ def chimnie
+ api_key = ENV["CHIMNIE_API_KEY"].presence || Setting.chimnie_api_key # pipelock:ignore
+
+ return nil unless api_key.present?
+
+ Provider::Chimnie.new(api_key)
+ end
end
def initialize(concept)
@@ -234,7 +242,7 @@ class Provider::Registry
# builds them by name when benchmarking against Jev.
%i[jev]
when :property_valuations
- %i[rentcast realie]
+ %i[rentcast realie chimnie]
else
%i[plaid_us plaid_eu github openai anthropic]
end
diff --git a/app/models/setting.rb b/app/models/setting.rb
index c9145d0f1b..9045098c58 100644
--- a/app/models/setting.rb
+++ b/app/models/setting.rb
@@ -99,6 +99,7 @@ class Setting < RailsSettings::Base
# 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"]
+ field :chimnie_api_key, type: :string, default: ENV["CHIMNIE_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
@@ -117,6 +118,7 @@ class Setting < RailsSettings::Base
mansa_api_key
rentcast_api_key
realie_api_key
+ chimnie_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 fe81ebbcbb..ec0a5e72d5 100644
--- a/app/views/properties/_avm_form.html.erb
+++ b/app/views/properties/_avm_form.html.erb
@@ -1,6 +1,8 @@
<%# locals: (account:, provider_key:) %>
<% provider_name = t("properties.avm_providers.#{provider_key}") %>
+<% provider = avm_provider_class(provider_key) %>
+<% uk = provider&.supported_country == "GB" %>
<%= render DS::Dialog.new do |dialog| %>
<% dialog.with_header(title: t("properties.new.avm_title", provider: provider_name)) %>
@@ -26,23 +28,35 @@
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 %>
+ label: uk ? t("properties.new.avm_town_label") : t("properties.form.locality"),
+ placeholder: uk ? nil : t("properties.form.locality_placeholder"),
+ required: provider.nil? || provider.required_address_fields.include?(:locality) %>
<%= address_form.text_field :region,
- label: t("properties.form.region"),
- placeholder: t("properties.form.region_placeholder"),
- required: true %>
+ label: uk ? t("properties.new.avm_county_label") : t("properties.form.region"),
+ placeholder: uk ? nil : t("properties.form.region_placeholder"),
+ required: provider.nil? || provider.required_address_fields.include?(:region) %>
</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"),
+ label: uk ? t("properties.new.avm_postcode_label") : t("properties.form.postal_code"),
+ placeholder: uk ? nil : 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>
+ <% if provider&.requires_external_id? %>
+ <%= form.fields_for :property, Property.new(avm_external_id: @avm_external_id) do |property_form| %>
+ <%= property_form.text_field :avm_external_id,
+ label: t("properties.new.avm_uprn_label"),
+ placeholder: t("properties.new.avm_uprn_placeholder"),
+ help_text: t("properties.new.avm_uprn_help", provider: provider_name),
+ inputmode: "numeric",
+ autocomplete: "off",
+ required: true %>
+ <% end %>
+ <% end %>
+
+ <p class="text-sm text-secondary"><%= uk ? t("properties.new.avm_uk_only", provider: provider_name) : t("properties.new.avm_us_only", provider: provider_name) %></p>
</div>
<div class="flex justify-end mt-4">
diff --git a/app/views/properties/_avm_method_option.html.erb b/app/views/properties/_avm_method_option.html.erb
index 8cf763b7dc..dd62f123b9 100644
--- a/app/views/properties/_avm_method_option.html.erb
+++ b/app/views/properties/_avm_method_option.html.erb
@@ -1,9 +1,13 @@
-<%# locals: (path:, icon_name:, label:) %>
+<%# locals: (path:, label:, icon_name: nil, provider_key: nil) %>
<%= 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>
+ <% if provider_key %>
+ <%= render ProviderLogo.new(provider_key: provider_key, class_name: "w-8 h-8 rounded-lg") %>
+ <% else %>
+ <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>
+ <% end %>
<%= 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.erb
index ff49f1e938..c733567b68 100644
--- a/app/views/properties/_avm_method_selector.html.erb
+++ b/app/views/properties/_avm_method_selector.html.erb
@@ -10,7 +10,7 @@
<% 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",
+ provider_key: provider_key,
label: t("properties.new.avm_option", provider: t("properties.avm_providers.#{provider_key}")) %>
<% end %>
</div>
diff --git a/app/views/properties/_avm_preview.html.erb b/app/views/properties/_avm_preview.html.erb
index b8b1173c37..6580b85a74 100644
--- a/app/views/properties/_avm_preview.html.erb
+++ b/app/views/properties/_avm_preview.html.erb
@@ -38,9 +38,34 @@
</div>
</div>
- <% if no_property_record %>
+ <% if preview.external_id.present? || preview.valuation_low.present? || preview.confidence.present? %>
+ <dl class="flex flex-col gap-2">
+ <% if preview.external_id.present? %>
+ <%= render DS::DetailRow.new(label: t("properties.new.avm_preview_uprn"), value: preview.external_id) %>
+ <% end %>
+ <% if preview.valuation_low.present? && preview.valuation_high.present? %>
+ <%= render DS::DetailRow.new(
+ label: t("properties.new.avm_preview_range"),
+ value: "#{format_money(Money.new(preview.valuation_low, preview.currency))} – #{format_money(Money.new(preview.valuation_high, preview.currency))}",
+ value_class: "privacy-sensitive"
+ ) %>
+ <% end %>
+ <% if preview.confidence.present? %>
+ <%= render DS::DetailRow.new(
+ label: t("properties.new.avm_preview_confidence"),
+ value: t("properties.new.avm_confidence.#{preview.confidence}", default: preview.confidence.to_s.humanize)
+ ) %>
+ <% end %>
+ </dl>
+ <% 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 %>
+
+ <% if provider_key.to_s == "chimnie" %>
+ <p class="text-xs text-secondary"><%= t("properties.new.avm_attribution_chimnie") %></p>
+ <% end %>
</div>
<%# The confirm step rebuilds everything from the signed token, proving
diff --git a/app/views/properties/tabs/_overview.html.erb b/app/views/properties/tabs/_overview.html.erb
index df34174436..4403287e82 100644
--- a/app/views/properties/tabs/_overview.html.erb
+++ b/app/views/properties/tabs/_overview.html.erb
@@ -28,6 +28,24 @@
<% end %>
</div>
+<% if account.property.avm_provider.present? %>
+ <div class="flex flex-col items-center gap-2 pt-8">
+ <% if account.property.avm_last_synced_on.present? %>
+ <p class="text-sm text-secondary">
+ <%= t(".valuation_source",
+ provider: t("properties.avm_providers.#{account.property.avm_provider}"),
+ date: l(account.property.avm_last_synced_on, format: :long)) %>
+ </p>
+ <% end %>
+ <%= render DS::Button.new(
+ text: t(".refresh_valuation"),
+ href: refresh_valuation_property_path(account),
+ variant: "outline",
+ icon: "refresh-cw"
+ ) %>
+ </div>
+<% end %>
+
<div class="flex justify-center py-8">
<%= render DS::Link.new(
text: t(".edit_account_details"),
diff --git a/app/views/settings/hostings/_chimnie_settings.html.erb b/app/views/settings/hostings/_chimnie_settings.html.erb
new file mode 100644
index 0000000000..3f93299b71
--- /dev/null
+++ b/app/views/settings/hostings/_chimnie_settings.html.erb
@@ -0,0 +1,30 @@
+<div class="space-y-4">
+ <div>
+ <h2 class="font-medium mb-1"><%= t(".title") %></h2>
+ <% if ENV["CHIMNIE_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 @chimnie_usage&.success? %>
+ <p class="text-sm text-secondary"><%= t(".usage", used: @chimnie_usage.data.used, limit: @chimnie_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["CHIMNIE_API_KEY"].present? || Setting.chimnie_api_key.present? %>
+ <%= form.text_field :chimnie_api_key,
+ label: t(".label"),
+ type: "password",
+ placeholder: t(".placeholder"),
+ value: has_key ? "********" : "",
+ disabled: ENV["CHIMNIE_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 4003929e8c..77013b39df 100644
--- a/app/views/settings/hostings/show.html.erb
+++ b/app/views/settings/hostings/show.html.erb
@@ -61,6 +61,7 @@
<div class="space-y-6">
<%= render "settings/hostings/rentcast_settings" %>
<%= render "settings/hostings/realie_settings" %>
+ <%= render "settings/hostings/chimnie_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 4e0a08dac8..84c6765151 100644
--- a/config/locales/models/provider/en.yml
+++ b/config/locales/models/provider/en.yml
@@ -4,7 +4,9 @@ en:
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).
+ missing_fields_gb: Please provide a name, the street address and postcode, and the property's UPRN.
preview_expired: This property preview has expired — please look up the address again.
+ entry_name: "%{provider} valuation"
rentcast:
errors:
no_valuation: RentCast did not return a value estimate for this address.
@@ -15,3 +17,11 @@ en:
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.
+ chimnie:
+ errors:
+ invalid_uprn: A UPRN is a number of up to 12 digits. Please check the UPRN and try again.
+ no_estimate: Chimnie does not have a value estimate for this property.
+ not_found: Chimnie could not find a property with this UPRN.
+ 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.
diff --git a/config/locales/views/properties/en.yml b/config/locales/views/properties/en.yml
index 08aba9db9d..f52a1a43e6 100644
--- a/config/locales/views/properties/en.yml
+++ b/config/locales/views/properties/en.yml
@@ -25,6 +25,7 @@ en:
avm_providers:
rentcast: RentCast
realie: Realie
+ chimnie: Chimnie
new:
title: Enter property manually
next: "Next"
@@ -32,11 +33,26 @@ en:
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_uk_only: "%{provider} only supports residential properties located in the United Kingdom."
+ avm_uprn_label: "UPRN"
+ avm_uprn_placeholder: "100023336956"
+ avm_uprn_help: "The Unique Property Reference Number (up to 12 digits) identifies every UK address. Find it on GeoPlace's findmyaddress.co.uk or ask your local council. %{provider} uses it to value the property for free."
+ avm_county_label: "County (optional)"
+ avm_town_label: "Town or city"
+ avm_postcode_label: "Postcode"
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_uprn: "UPRN"
+ avm_preview_range: "Estimate range"
+ avm_preview_confidence: "Confidence"
+ avm_confidence:
+ high: "High"
+ medium: "Medium"
+ low: "Low"
+ avm_attribution_chimnie: "Valuation data from Chimnie. Contains OS data © Crown copyright and database right, Royal Mail data © Royal Mail copyright and database right, and HM Land Registry data © Crown copyright and database right, licensed under the Open Government Licence v3.0."
avm_preview_confirm: "Add property"
address:
title: "Enter property manually"
@@ -85,6 +101,12 @@ en:
unknown: Unknown
year_built: Year Built
edit_account_details: "Edit account details"
+ refresh_valuation: "Refresh valuation"
+ valuation_source: "Valued by %{provider}, last updated %{date}"
+ refresh_valuation:
+ queued: "The valuation refresh has started. The new value will appear shortly."
+ not_linked: "This property isn't linked to a valuation provider."
+ not_configured: "%{provider} isn't configured. Add its API key in Settings → Self-Hosting to refresh this valuation."
subtypes:
apartment:
short: Apartment
diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml
index e9b31b7d61..b81b1745b2 100644
--- a/config/locales/views/settings/hostings/en.yml
+++ b/config/locales/views/settings/hostings/en.yml
@@ -236,6 +236,13 @@ en:
label: API Key
placeholder: Enter your Realie API key here
usage: "%{used} of %{limit} monthly requests used"
+ chimnie_settings:
+ title: Chimnie
+ description: Enter your Chimnie API key to value UK residential properties by their UPRN. Create a free key at dashboard.chimnie.com (sign-up requires a business or custom-domain email address; Gmail, Outlook and similar addresses are not accepted). UPRN valuations are free and refreshed monthly; Sure caps them at 1,000 requests per month, which you can change with the CHIMNIE_MAX_REQUESTS_PER_MONTH environment variable.
+ env_configured_message: Successfully configured through the CHIMNIE_API_KEY environment variable.
+ label: API Key
+ placeholder: Enter your Chimnie API key here
+ usage: "%{used} of %{limit} monthly requests used"
tiingo_settings:
title: Tiingo
description: 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/routes.rb b/config/routes.rb
index b548a61af8..ee09c80fb1 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -703,6 +703,8 @@ Rails.application.routes.draw do
get :address
patch :update_address
+
+ post :refresh_valuation
end
end
resources :vehicles, only: %i[new create edit update]
diff --git a/db/migrate/20261011090000_add_chimnie_support_to_properties.rb b/db/migrate/20261011090000_add_chimnie_support_to_properties.rb
new file mode 100644
index 0000000000..55288f4e04
--- /dev/null
+++ b/db/migrate/20261011090000_add_chimnie_support_to_properties.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+class AddChimnieSupportToProperties < ActiveRecord::Migration[8.1]
+ def up
+ # Provider-side identifier for the property (e.g. a UK UPRN for Chimnie).
+ add_column :properties, :avm_external_id, :string
+
+ 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
+
+ def down
+ # The restored constraint would reject Chimnie-linked rows, so unlink them
+ # first. The accounts and their valuation history are kept.
+ execute <<~SQL
+ UPDATE properties SET avm_provider = NULL, avm_last_synced_on = NULL
+ WHERE avm_provider = 'chimnie'
+ SQL
+
+ remove_check_constraint :properties, name: "properties_avm_provider_check"
+ add_check_constraint :properties,
+ "avm_provider IS NULL OR avm_provider IN ('rentcast', 'realie')",
+ name: "properties_avm_provider_check"
+
+ remove_column :properties, :avm_external_id
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index d0074c245e..1377cea8eb 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[8.1].define(version: 2026_10_08_120000) do
+ActiveRecord::Schema[8.1].define(version: 2026_10_11_090000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -1948,6 +1948,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_08_120000) do
create_table "properties", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.string "area_unit"
t.integer "area_value"
+ t.string "avm_external_id"
t.date "avm_last_synced_on"
t.string "avm_provider"
t.datetime "created_at", null: false
@@ -1956,7 +1957,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_08_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::text, 'realie'::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]::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/docs/hosting/property-valuations.md b/docs/hosting/property-valuations.md
new file mode 100644
index 0000000000..9e1f48c314
--- /dev/null
+++ b/docs/hosting/property-valuations.md
@@ -0,0 +1,45 @@
+# Automatic Property Valuations
+
+Sure can look up a property's estimated market value when you add it, and refresh that value automatically so it shows up in the account balance and net worth.
+
+| Provider | Coverage | Lookup by | Free tier | Environment variable |
+| --- | --- | --- | --- | --- |
+| [RentCast](https://www.rentcast.io/api) | United States | Address | 50 requests/month | `RENTCAST_API_KEY` |
+| [Realie](https://www.realie.ai/) | United States | Address | 25 requests/month | `REALIE_API_KEY` |
+| [Chimnie](https://www.chimnie.com/) | United Kingdom (residential) | UPRN | Free valuations by UPRN (1 request/second) | `CHIMNIE_API_KEY` |
+
+Each self-hosted instance needs its own API keys. Enter them under **Settings → Self-Hosting → Property valuation providers**, or set the environment variables on the web and worker services. A key set in the environment overrides the one saved in Settings.
+
+Once a key is configured, **Add via &lt;provider&gt;** appears when you add a property.
+
+## UK properties (Chimnie)
+
+Chimnie values UK residential properties by their **UPRN** (Unique Property Reference Number), an identifier of up to 12 digits that every UK address has. Look a property up for free at [findmyaddress.co.uk](https://www.findmyaddress.co.uk) or ask your local council.
+
+1. Create a free account at [dashboard.chimnie.com](https://dashboard.chimnie.com) and copy your API key. Sign-up requires a business or custom-domain email address; Gmail, Outlook and similar addresses are not accepted.
+2. Paste it into **Settings → Self-Hosting → Chimnie**, or set `CHIMNIE_API_KEY`.
+3. Add a property, choose **Add via Chimnie**, and enter the address, postcode and UPRN.
+4. Review the estimate, its range and Chimnie's confidence, then confirm.
+
+Sure only requests Chimnie's free valuation fields (estimated value, range and confidence). Valuations are stored in GBP, so the account currency must stay GBP for automatic refreshes to apply.
+
+Chimnie only covers residential properties. Commercial or mixed-use UPRNs, and properties without an estimate, are reported as errors and no property is created.
+
+## Refreshes
+
+`SyncPropertyValuationsJob` runs on the 1st of each month. For each linked property it:
+
+- skips the property if it was refreshed within the provider's minimum interval (one day for RentCast and Realie, one month for Chimnie)
+- skips it when the address, UPRN or currency no longer fit the provider
+- stops calling a provider for the rest of the run once that provider reports a rate limit
+- records the new value as that day's balance valuation, named after the provider (e.g. "Chimnie valuation"). Refreshing twice on the same day updates that valuation instead of adding a second one.
+
+On a property's overview tab, **Refresh valuation** requests a new value straight away. It skips the minimum interval but still counts against the provider's monthly request cap.
+
+Every provider has a monthly request cap enforced by Sure. Raise it with `RENTCAST_MAX_REQUESTS_PER_MONTH`, `REALIE_MAX_REQUESTS_PER_MONTH` or `CHIMNIE_MAX_REQUESTS_PER_MONTH`. Chimnie's cap defaults to 1,000 requests a month because its UPRN valuations are free.
+
+Failed and skipped refreshes are recorded in the debug log under the `provider_sync_error` category.
+
+## Attribution
+
+Chimnie valuation data contains Ordnance Survey, Royal Mail and HM Land Registry data. Sure shows the required attribution on the property preview.
diff --git a/test/controllers/properties_controller_test.rb b/test/controllers/properties_controller_test.rb
index fa4d7f19dd..8b5093ee1f 100644
--- a/test/controllers/properties_controller_test.rb
+++ b/test/controllers/properties_controller_test.rb
@@ -537,4 +537,176 @@ class PropertiesControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to new_property_path
end
+
+ # Chimnie (UK, UPRN-based) lookups
+
+ def chimnie_avm_response
+ Provider::Response.new(
+ success?: true,
+ data: Provider::PropertyValuationConcept::PropertyValuation.new(
+ valuation: 425_000,
+ currency: "GBP",
+ property_type: nil,
+ year_built: nil,
+ area_value: nil,
+ area_unit: "sqft",
+ external_id: "999000000001",
+ valuation_low: 340_000,
+ valuation_high: 530_000,
+ confidence: "high"
+ ),
+ error: nil
+ )
+ end
+
+ def chimnie_lookup_params(uprn: "999000000001")
+ {
+ avm_provider: "chimnie",
+ account: {
+ name: "Chester Flat",
+ accountable_type: "Property",
+ address: { line1: "1 High Street", locality: "Chester", region: "", postal_code: "CH1 1MN" },
+ property: { avm_external_id: uprn }
+ }
+ }
+ end
+
+ test "Chimnie lookup form asks for a UPRN and a UK address" do
+ Provider::Registry.stubs(:chimnie).returns(mock)
+
+ get new_property_path(method: "chimnie")
+
+ assert_response :success
+ assert_match "Add property via Chimnie", response.body
+ assert_select "input[name='account[property][avm_external_id]'][required]"
+ assert_select "input[name='account[address][region]']:not([required])"
+ assert_match "United Kingdom", response.body
+ end
+
+ test "Chimnie lookup previews the estimate range and confidence by UPRN" do
+ provider = mock
+ provider.expects(:fetch_property_valuation).with(
+ line1: "1 High Street",
+ locality: "Chester",
+ region: "",
+ postal_code: "CH1 1MN",
+ external_id: "999000000001"
+ ).returns(chimnie_avm_response)
+ Provider::Registry.stubs(:chimnie).returns(provider)
+
+ assert_no_difference "Account.count" do
+ post properties_path, params: chimnie_lookup_params
+ end
+
+ assert_response :success
+ assert_match "Confirm property details", response.body
+ assert_match "999000000001", response.body
+ assert_match "Estimate range", response.body
+ assert_match "High", response.body
+ assert_match "HM Land Registry", response.body
+ assert_no_match "couldn&#39;t find a property record", response.body
+ end
+
+ test "Chimnie lookup requires a UPRN without spending a request" do
+ provider = mock
+ provider.expects(:fetch_property_valuation).never
+ Provider::Registry.stubs(:chimnie).returns(provider)
+
+ assert_no_difference "Account.count" do
+ post properties_path, params: chimnie_lookup_params(uprn: "")
+ end
+
+ assert_response :unprocessable_entity
+ assert_match "UPRN", response.body
+ end
+
+ test "Chimnie confirm creates a GBP property linked by UPRN" do
+ provider = mock
+ provider.expects(:fetch_property_valuation).once.returns(chimnie_avm_response)
+ Provider::Registry.stubs(:chimnie).returns(provider)
+
+ post properties_path, params: chimnie_lookup_params
+ token = css_select("input[name='avm_preview_token']").first["value"]
+
+ assert_difference -> { Account.count } => 1 do
+ post properties_path, params: {
+ avm_provider: "chimnie",
+ avm_step: "confirm",
+ avm_preview_token: token,
+ account: { accountable_type: "Property" }
+ }
+ end
+
+ account = Account.order(:created_at).last
+ assert_equal "GBP", account.currency
+ assert_equal 425_000, account.balance
+ assert account.active?
+ assert_equal "chimnie", account.property.avm_provider
+ assert_equal "999000000001", account.property.avm_external_id
+ assert_equal "GB", account.property.address.country
+ assert_equal "GBP", account.entries.valuations.last.currency
+ assert_equal "Chimnie valuation", account.entries.valuations.last.name
+ end
+
+ test "refresh_valuation queues a forced refresh of the property" do
+ @account.property.update!(avm_provider: "chimnie", avm_external_id: "999000000001")
+ Provider::Registry.stubs(:chimnie).returns(mock)
+
+ assert_enqueued_with(job: SyncPropertyValuationsJob, args: [ { property_id: @account.property.id, force: true } ]) do
+ post refresh_valuation_property_path(@account)
+ end
+
+ assert_redirected_to account_path(@account)
+ end
+
+ test "refresh_valuation does nothing for properties without a provider" do
+ @account.property.update!(avm_provider: nil)
+
+ assert_no_enqueued_jobs(only: SyncPropertyValuationsJob) do
+ post refresh_valuation_property_path(@account)
+ end
+
+ assert_redirected_to account_path(@account)
+ end
+
+ test "refresh_valuation refuses when the provider is no longer configured" do
+ @account.property.update!(avm_provider: "chimnie", avm_external_id: "999000000001")
+ Provider::Registry.stubs(:chimnie).returns(nil)
+
+ assert_no_enqueued_jobs(only: SyncPropertyValuationsJob) do
+ post refresh_valuation_property_path(@account)
+ end
+
+ assert_redirected_to account_path(@account)
+ assert_match "Chimnie isn't configured", flash[:alert]
+ end
+
+ test "method selector shows provider logos for valuation providers" do
+ Provider::Registry.stubs(:chimnie).returns(mock)
+
+ get new_property_path(step: "method_select")
+
+ assert_response :success
+ assert_select "a[href*='method=chimnie']", text: /CH\s+Add via Chimnie/
+ end
+
+ test "refresh_valuation is scoped to the current family" do
+ @account.property.update!(avm_provider: "chimnie", avm_external_id: "999000000001")
+ sign_in users(:empty)
+
+ assert_no_enqueued_jobs(only: SyncPropertyValuationsJob) do
+ post refresh_valuation_property_path(@account)
+ end
+
+ assert_response :not_found
+ end
+
+ test "overview offers a valuation refresh for provider-linked properties" do
+ @account.property.update!(avm_provider: "chimnie", avm_external_id: "999000000001", avm_last_synced_on: Date.current)
+
+ get account_path(@account, tab: "overview")
+
+ assert_response :success
+ assert_select "form[action='#{refresh_valuation_property_path(@account)}']"
+ end
end
diff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rb
index 818c153bfa..811632c5c9 100644
--- a/test/controllers/settings/hostings_controller_test.rb
+++ b/test/controllers/settings/hostings_controller_test.rb
@@ -14,6 +14,7 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
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::Registry.stubs(:get_provider).with(:chimnie).returns(nil)
@provider.stubs(:usage).returns(provider_success_response(
OpenStruct.new(
used: 10,
@@ -27,7 +28,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 demo_family_refresh_enabled demo_family_refresh_family_id].each do |key|
+ %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].each do |key|
Setting.public_send("#{key}=", nil)
end
end
@@ -172,6 +173,14 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
end
end
+ test "can update chimnie api key when self hosting is enabled" do
+ with_self_hosting do
+ patch settings_hosting_url, params: { setting: { chimnie_api_key: "chimnie-token" } }
+
+ assert_equal "chimnie-token", Setting.chimnie_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.rb
index 5ae6ef95dd..fa005e69d4 100644
--- a/test/jobs/sync_property_valuations_job_test.rb
+++ b/test/jobs/sync_property_valuations_job_test.rb
@@ -34,6 +34,7 @@ class SyncPropertyValuationsJobTest < ActiveSupport::TestCase
assert_equal Date.current, @property.reload.avm_last_synced_on
assert_equal 600_000, @account.reload.balance
+ assert_equal "RentCast valuation", @account.entries.valuations.find_by(date: Date.current).name
end
test "resolves each provider once per run across multiple properties" do
@@ -154,7 +155,9 @@ class SyncPropertyValuationsJobTest < ActiveSupport::TestCase
test "skips properties whose provider is no longer configured" do
Provider::Registry.stubs(:rentcast).returns(nil)
- SyncPropertyValuationsJob.new.perform
+ assert_difference "DebugLogEntry.count" => 1 do
+ SyncPropertyValuationsJob.new.perform
+ end
assert_nil @property.reload.avm_last_synced_on
end
@@ -166,4 +169,145 @@ class SyncPropertyValuationsJobTest < ActiveSupport::TestCase
SyncPropertyValuationsJob.new.perform
end
+
+ # Chimnie (UK, UPRN-based) refreshes
+
+ def create_uk_property(avm_last_synced_on: nil, uprn: "999000000001")
+ @account.family.accounts.create!(
+ name: "UK AVM Property",
+ balance: 0,
+ currency: "GBP",
+ owner: @account.owner,
+ accountable: Property.new(
+ avm_provider: "chimnie",
+ avm_external_id: uprn,
+ avm_last_synced_on: avm_last_synced_on,
+ address_attributes: { line1: "1 High Street", locality: "Chester", country: "GB", postal_code: "CH1 1MN" }
+ )
+ )
+ end
+
+ def gbp_valuation_data(valuation: 425_000)
+ Provider::PropertyValuationConcept::PropertyValuation.new(
+ valuation: valuation,
+ currency: "GBP",
+ property_type: nil,
+ year_built: nil,
+ area_value: nil,
+ area_unit: "sqft",
+ external_id: "999000000001"
+ )
+ end
+
+ def stub_chimnie_provider
+ provider = mock
+ provider.stubs(:requests_remaining?).returns(true)
+ provider.stubs(:valuation_currency).returns("GBP")
+ Provider::Registry.stubs(:chimnie).returns(provider)
+ provider
+ end
+
+ test "refreshes UK properties by UPRN and stores the valuation in GBP" do
+ @property.update!(avm_provider: nil)
+ uk_account = create_uk_property
+
+ provider = stub_chimnie_provider
+ provider.expects(:fetch_property_valuation).with(
+ line1: "1 High Street",
+ locality: "Chester",
+ region: nil,
+ postal_code: "CH1 1MN",
+ external_id: "999000000001"
+ ).returns(Provider::Response.new(success?: true, data: gbp_valuation_data, error: nil))
+
+ SyncPropertyValuationsJob.new.perform
+
+ uk_account.reload
+ assert_equal 425_000, uk_account.balance
+ assert_equal "GBP", uk_account.currency
+ assert_equal "GBP", uk_account.entries.valuations.order(:date).last.currency
+ assert_equal "Chimnie valuation", uk_account.entries.valuations.order(:date).last.name
+ assert_equal Date.current, uk_account.property.avm_last_synced_on
+ end
+
+ test "does not refresh UK properties more than once a month" do
+ @property.update!(avm_provider: nil)
+ create_uk_property(avm_last_synced_on: Date.current - 2.weeks)
+
+ provider = stub_chimnie_provider
+ provider.expects(:fetch_property_valuation).never
+
+ SyncPropertyValuationsJob.new.perform
+ end
+
+ test "refreshes UK properties again once a month has passed" do
+ @property.update!(avm_provider: nil)
+ uk_account = create_uk_property(avm_last_synced_on: Date.current - 1.month)
+
+ provider = stub_chimnie_provider
+ provider.expects(:fetch_property_valuation).once
+ .returns(Provider::Response.new(success?: true, data: gbp_valuation_data, error: nil))
+
+ SyncPropertyValuationsJob.new.perform
+
+ assert_equal Date.current, uk_account.property.reload.avm_last_synced_on
+ end
+
+ test "a forced refresh of one property skips the refresh interval" do
+ uk_account = create_uk_property(avm_last_synced_on: Date.current - 2.weeks)
+
+ provider = stub_chimnie_provider
+ provider.expects(:fetch_property_valuation).once
+ .returns(Provider::Response.new(success?: true, data: gbp_valuation_data(valuation: 430_000), error: nil))
+ Provider::Registry.expects(:rentcast).never
+
+ SyncPropertyValuationsJob.new.perform(property_id: uk_account.property.id, force: true)
+
+ assert_equal 430_000, uk_account.reload.balance
+ assert_nil @property.reload.avm_last_synced_on
+ end
+
+ test "refreshing twice on the same date does not create a duplicate valuation" do
+ @property.update!(avm_provider: nil)
+ uk_account = create_uk_property
+
+ provider = stub_chimnie_provider
+ provider.stubs(:fetch_property_valuation)
+ .returns(Provider::Response.new(success?: true, data: gbp_valuation_data(valuation: 425_000), error: nil))
+ .then.returns(Provider::Response.new(success?: true, data: gbp_valuation_data(valuation: 431_000), error: nil))
+
+ SyncPropertyValuationsJob.new.perform
+
+ assert_no_difference -> { uk_account.entries.valuations.where(date: Date.current).count } do
+ SyncPropertyValuationsJob.new.perform(property_id: uk_account.property.id, force: true)
+ end
+
+ assert_equal 431_000, uk_account.reload.balance
+ end
+
+ test "skips UK properties without a UPRN without spending a request" do
+ @property.update!(avm_provider: nil)
+ create_uk_property(uprn: nil)
+
+ Provider::Registry.expects(:chimnie).never
+
+ assert_difference "DebugLogEntry.count" => 1 do
+ SyncPropertyValuationsJob.new.perform
+ end
+ end
+
+ test "stops calling a provider for the rest of the run once it is rate limited" do
+ @property.update!(avm_provider: nil)
+ create_uk_property(uprn: "999000000001")
+ create_uk_property(uprn: "999000000002")
+
+ provider = stub_chimnie_provider
+ provider.expects(:fetch_property_valuation).once.returns(
+ Provider::Response.new(success?: false, data: nil, error: Provider::Chimnie::RateLimitError.new("Chimnie rate limit exceeded"))
+ )
+
+ assert_difference "DebugLogEntry.count" => 1 do
+ SyncPropertyValuationsJob.new.perform
+ end
+ end
end
diff --git a/test/models/property_test.rb b/test/models/property_test.rb
new file mode 100644
index 0000000000..d24c39a61d
--- /dev/null
+++ b/test/models/property_test.rb
@@ -0,0 +1,53 @@
+require "test_helper"
+
+class PropertyTest < ActiveSupport::TestCase
+ setup do
+ @account = accounts(:property)
+ @property = @account.property
+ end
+
+ test "names the day's reconciliation after the AVM provider" do
+ @property.update!(avm_provider: "chimnie")
+ @account.set_current_balance(560_000)
+
+ @property.name_avm_valuation!
+
+ assert_equal "Chimnie valuation", @account.entries.valuations.find_by(date: Date.current).name
+ end
+
+ test "a later manual edit on the same day drops the provider label" do
+ @property.update!(avm_provider: "chimnie")
+ @account.set_current_balance(560_000)
+ @property.name_avm_valuation!
+ entry = @account.entries.valuations.find_by(date: Date.current)
+
+ @account.update_reconciliation(entry, balance: 570_000, date: Date.current)
+
+ assert_equal "Manual value update", entry.reload.name
+ assert_equal 570_000, entry.amount
+ end
+
+ test "leaves manual value updates alone for properties without a provider" do
+ @property.update!(avm_provider: nil)
+ @account.set_current_balance(560_000)
+
+ @property.name_avm_valuation!
+
+ assert_equal "Manual value update", @account.entries.valuations.find_by(date: Date.current).name
+ end
+
+ test "does not rename opening or current anchors" do
+ @property.update!(avm_provider: "rentcast")
+ entry = @account.entries.create!(
+ date: Date.current,
+ name: "Original purchase price",
+ amount: 500_000,
+ currency: @account.currency,
+ entryable: Valuation.new(kind: "opening_anchor")
+ )
+
+ @property.name_avm_valuation!
+
+ assert_equal "Original purchase price", entry.reload.name
+ end
+end
diff --git a/test/models/provider/chimnie_test.rb b/test/models/provider/chimnie_test.rb
new file mode 100644
index 0000000000..dcced1367c
--- /dev/null
+++ b/test/models/provider/chimnie_test.rb
@@ -0,0 +1,222 @@
+require "test_helper"
+
+class Provider::ChimnieTest < ActiveSupport::TestCase
+ VALUATION_URL = "https://api.chimnie.com/residential/uprn/999000000001".freeze
+
+ setup do
+ @provider = Provider::Chimnie.new("test_api_key")
+ @provider.stubs(:throttle_request)
+ end
+
+ def valuation_response_body(sale = nil)
+ {
+ "property" => {
+ "value" => {
+ "sale" => sale || {
+ "property_value" => 425_000,
+ "property_value_range" => [ 340_000, 530_000 ],
+ "property_value_confidence" => "high"
+ }
+ }
+ },
+ "id" => "999000000001"
+ }.to_json
+ end
+
+ def stub_valuation(status: 200, body: valuation_response_body)
+ stub_request(:get, VALUATION_URL)
+ .with(query: { "fields" => Provider::Chimnie::FREE_VALUATION_FIELDS.join(",") })
+ .to_return(status: status, body: body)
+ end
+
+ test "fetches a free valuation by UPRN with only the free fields" do
+ stub = stub_request(:get, VALUATION_URL)
+ .with(
+ query: {
+ "fields" => "property.value.sale.property_value,property.value.sale.property_value_range,property.value.sale.property_value_confidence"
+ },
+ headers: { "Authorization" => "Bearer test_api_key" }
+ )
+ .to_return(status: 200, body: valuation_response_body)
+
+ response = @provider.fetch_property_valuation(external_id: "999000000001")
+
+ assert response.success?
+ data = response.data
+ assert_equal 425_000, data.valuation
+ assert_equal "GBP", data.currency
+ assert_equal 340_000, data.valuation_low
+ assert_equal 530_000, data.valuation_high
+ assert_equal "high", data.confidence
+ assert_equal "999000000001", data.external_id
+ assert_nil data.property_type
+ assert_nil data.year_built
+ assert_nil data.area_value
+ assert_requested stub
+ end
+
+ test "normalizes spaces in the UPRN and confidence casing" do
+ stub_valuation(body: valuation_response_body(
+ "property_value" => 425_000,
+ "property_value_range" => [ 340_000, 530_000 ],
+ "property_value_confidence" => "Medium"
+ ))
+
+ response = @provider.fetch_property_valuation(external_id: " 9990 0000 0001 ")
+
+ assert response.success?
+ assert_equal "medium", response.data.confidence
+ end
+
+ test "tolerates a missing range and confidence" do
+ stub_valuation(body: valuation_response_body("property_value" => 425_000))
+
+ response = @provider.fetch_property_valuation(external_id: "999000000001")
+
+ assert response.success?
+ assert_nil response.data.valuation_low
+ assert_nil response.data.valuation_high
+ assert_nil response.data.confidence
+ end
+
+ test "returns an error when the estimate is null" do
+ stub_valuation(body: valuation_response_body("property_value" => nil))
+
+ response = @provider.fetch_property_valuation(external_id: "999000000001")
+
+ assert_not response.success?
+ assert_match(/does not have a value estimate/i, response.error.message)
+ end
+
+ test "rejects a missing or malformed UPRN without spending a request" do
+ [ nil, "", "ABC123", "1234567890123" ].each do |uprn|
+ response = @provider.fetch_property_valuation(external_id: uprn)
+
+ assert_not response.success?
+ assert_match(/UPRN/, response.error.message)
+ end
+
+ assert_equal 0, ProviderRequestCount.count_for("chimnie")
+ assert_not_requested :get, %r{api\.chimnie\.com}
+ end
+
+ test "maps not found, commercial, unauthorized and insufficient balance responses" do
+ {
+ 404 => /could not find a property/i,
+ 409 => /only values residential properties/i,
+ 401 => /rejected the API key/i,
+ 402 => /balance is too low/i
+ }.each do |status, message|
+ stub_valuation(status: status, body: { "statusCode" => status }.to_json)
+
+ response = @provider.fetch_property_valuation(external_id: "999000000001")
+
+ assert_not response.success?, "expected #{status} to fail"
+ assert_instance_of Provider::Chimnie::Error, response.error
+ assert_match message, response.error.message
+ end
+ end
+
+ test "retries 429 responses, since the per-key limit is shared across processes" do
+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)
+ stub_request(:get, VALUATION_URL)
+ .with(query: hash_including("fields"))
+ .to_return({ status: 429, body: { "statusCode" => 429 }.to_json }, { status: 200, body: valuation_response_body })
+
+ response = @provider.fetch_property_valuation(external_id: "999000000001")
+
+ assert response.success?
+ assert_equal 425_000, response.data.valuation
+ assert_requested :get, VALUATION_URL, query: hash_including("fields"), times: 2
+ assert_equal 2, ProviderRequestCount.count_for("chimnie")
+ end
+
+ test "maps persistent 429 responses to a rate limit error" do
+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)
+ stub_valuation(status: 429, body: { "statusCode" => 429, "message" => "Rate limit exceeded" }.to_json)
+
+ response = @provider.fetch_property_valuation(external_id: "999000000001")
+
+ assert_not response.success?
+ assert_instance_of Provider::Chimnie::RateLimitError, response.error
+ assert_requested :get, VALUATION_URL, query: hash_including("fields"), times: 4
+ assert_equal 4, ProviderRequestCount.count_for("chimnie")
+ end
+
+ test "throttles every attempt, including retries" do
+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)
+ stub_request(:get, VALUATION_URL)
+ .with(query: hash_including("fields"))
+ .to_return({ status: 429, body: { "statusCode" => 429 }.to_json }, { status: 200, body: valuation_response_body })
+
+ @provider.expects(:throttle_request).twice
+
+ assert @provider.fetch_property_valuation(external_id: "999000000001").success?
+ end
+
+ test "stops retrying once the monthly limit is reached" do
+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)
+ ProviderRequestCount.create!(provider_key: "chimnie", period: ProviderRequestCount.current_period, count: Provider::Chimnie::MAX_REQUESTS_PER_MONTH - 1)
+ stub_valuation(status: 429, body: { "statusCode" => 429 }.to_json)
+
+ response = @provider.fetch_property_valuation(external_id: "999000000001")
+
+ assert_instance_of Provider::Chimnie::RateLimitError, response.error
+ assert_match(/monthly request limit/, response.error.message)
+ assert_requested :get, VALUATION_URL, query: hash_including("fields"), times: 1
+ end
+
+ test "counts requests against the monthly budget" do
+ stub_valuation
+
+ @provider.fetch_property_valuation(external_id: "999000000001")
+
+ assert_equal 1, ProviderRequestCount.count_for("chimnie")
+ end
+
+ test "monthly limit can be changed via ENV override" do
+ ProviderRequestCount.create!(provider_key: "chimnie", period: ProviderRequestCount.current_period, count: Provider::Chimnie::MAX_REQUESTS_PER_MONTH)
+
+ ENV["CHIMNIE_MAX_REQUESTS_PER_MONTH"] = "2000"
+ assert @provider.requests_remaining?
+ ensure
+ ENV.delete("CHIMNIE_MAX_REQUESTS_PER_MONTH")
+ end
+
+ test "stops issuing requests once the monthly limit is reached" do
+ ProviderRequestCount.create!(provider_key: "chimnie", period: ProviderRequestCount.current_period, count: Provider::Chimnie::MAX_REQUESTS_PER_MONTH)
+
+ response = @provider.fetch_property_valuation(external_id: "999000000001")
+
+ assert_not response.success?
+ assert_instance_of Provider::Chimnie::RateLimitError, response.error
+ assert_not_requested :get, %r{api\.chimnie\.com}
+ end
+
+ test "describes UK coverage and a monthly refresh interval" do
+ assert_equal "GBP", @provider.valuation_currency
+ assert_equal "GB", Provider::Chimnie.supported_country
+ assert Provider::Chimnie.requires_external_id?
+ assert_equal 1.month, Provider::Chimnie.refresh_interval
+ end
+
+ test "is ready to look up UK addresses with a UPRN" do
+ address = { line1: "1 High Street", postal_code: "CH1 1MN", country: "GB" }
+
+ assert Provider::Chimnie.lookup_ready?(address, "999000000001")
+ assert Provider::Chimnie.lookup_ready?(address.merge(country: "UK"), "999000000001")
+ assert_not Provider::Chimnie.lookup_ready?(address, nil)
+ assert_not Provider::Chimnie.lookup_ready?(address.merge(country: "US"), "999000000001")
+ assert_not Provider::Chimnie.lookup_ready?(address.merge(postal_code: ""), "999000000001")
+ end
+
+ test "existing US providers keep requiring a complete US address" do
+ address = { line1: "123 Main Street", locality: "Los Angeles", region: "CA", postal_code: "90001", country: "US" }
+
+ assert Provider::Rentcast.lookup_ready?(address)
+ assert Provider::Realie.lookup_ready?(address.merge(country: ""))
+ assert_not Provider::Rentcast.lookup_ready?(address.merge(region: ""))
+ assert_not Provider::Rentcast.lookup_ready?(address.merge(country: "GB"))
+ assert_equal "USD", Provider::Rentcast.new("key").valuation_currency
+ end
+end
diff --git a/test/system/settings_test.rb b/test/system/settings_test.rb
index 13eebccdd7..0e7d8ed730 100644
--- a/test/system/settings_test.rb
+++ b/test/system/settings_test.rb
@@ -58,6 +58,7 @@ class SettingsTest < ApplicationSystemTestCase
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(:chimnie).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"