mirror of
https://github.com/we-promise/sure.git
synced 2026-07-27 20:22:16 +00:00
* Add RentCast and Realie AVM providers for property valuation Adds Automated Valuation Model (AVM) provider support so self-hosted users can create property accounts from a US address lookup instead of entering details manually: - Provider::Rentcast and Provider::Realie clients, each fetching the property record (type, year built, square footage) and value estimate in a single API request, registered under a new :property_valuations registry concept - API key fields (encrypted, ENV-overridable) with monthly usage display in Settings > Self-Hosting under "Property Valuation Providers" - New property flow: when a provider key is configured, the method selector offers "Add via RentCast/Realie" alongside manual entry; the lookup form reuses the manual flow's localized address fields and creates the account active with fetched attributes, valuation as balance, and the address saved - SyncPropertyValuationsJob refreshes linked property valuations once a day (never hourly) via config/schedule.yml; each provider enforces its monthly request cap (RentCast 50, Realie 25) with a calendar-month counter shared between creation lookups and refreshes Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Allow ENV override of AVM provider monthly request caps The RentCast (50/month) and Realie (25/month) budgets default to the free tier limits but can now be raised for paid plans via RENTCAST_MAX_REQUESTS_PER_MONTH / REALIE_MAX_REQUESTS_PER_MONTH, mirroring the AlphaVantage and Tiingo request limit overrides. The settings descriptions and usage display reflect the effective cap. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Address review feedback: durable request counters, safer refresh job - Move monthly AVM request counters from Rails.cache to a new provider_request_counts table with atomic upsert increments, so the hard budget caps survive cache eviction, restarts, and Redis flushes - SyncPropertyValuationsJob: only mark a property synced when the balance update succeeds (wrapped in a transaction), process stalest valuations first so a tight budget goes where it matters, and report failures via DebugLogEntry.capture instead of Rails.logger - Realie: reject lookups whose returned city/ZIP contradict the entered address (street+state queries can match the wrong city); document that numeric use codes are unpublished and leave the subtype unset - Add Faraday open/request timeouts to both provider clients - Localize all user-facing provider error messages (config/locales/models/provider/en.yml) - Add a check constraint restricting properties.avm_provider to known providers - Use the min-h-80 scale token instead of min-h-[320px] - Tests: exact-argument expectations on the lookup stub, provider stubs in the no-provider test, RentCast/Realie API key update tests, ProviderRequestCount unit tests, failed-balance regression test Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Stub AVM provider registry lookups in settings system test Settings::HostingsController#show now resolves the RentCast and Realie providers for usage display; the system test's partial get_provider stubbing treats the new lookups as unexpected invocations without these. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Address second-round review: candidate scan, provider reuse, shared row partial - Realie: when the address lookup returns multiple candidates, pick the first one consistent with the entered city/ZIP instead of judging only the first array element; the location-mismatch error now only fires when no candidate matches - SyncPropertyValuationsJob: resolve one provider instance per key for the whole run, so the per-instance request throttle actually spaces requests across properties instead of resetting on each iteration - Extract the AVM method selector row into a shared partial so the manual and provider options render one shape Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Add retry middleware and sync index from review feedback - Both AVM clients now retry transient connection failures (same Faraday retry config as Tiingo) so a network blip doesn't burn one of the tight monthly budget's requests - Partial index on properties(avm_provider, avm_last_synced_on) backing the daily sync job's filter and stalest-first ordering Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Key the AVM sync index on avm_last_synced_on The daily job orders by avm_last_synced_on ASC NULLS FIRST across all AVM-linked properties, so leading the partial index with avm_provider prevented it from serving the sort. Rekeyed on avm_last_synced_on with matching null ordering; the partial predicate still covers the filter. Amended in place since the migration is unmerged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Map Realie numeric use codes; skip incomplete addresses in sync job - Realie documents its numeric use codes at docs.realie.ai/api-reference/feature-key (earlier skip reason was wrong — the table exists). Map the residential/land/agricultural codes to Property subtypes, leaving codes without a subtype equivalent (e.g. 1006 mobile/manufactured) unset like the RentCast mapping. - The daily job now skips properties whose address is missing a street or state before resolving a provider, logging a warn-level DebugLogEntry, so a malformed address can't burn a monthly-budget request every day. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Guard currency mismatches in refresh; reset AVM keys in test teardown - The daily job now skips (with a warn-level DebugLogEntry) properties whose account currency no longer matches the provider's valuation currency, checked via the concept's valuation_currency before spending a request — writing a USD valuation into a re-currencied account would corrupt the balance - Hostings controller test teardown now clears rentcast_api_key and realie_api_key alongside the other cached global settings Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Validate AVM lookup inputs before spending a provider request The form marks name and address fields required, but a forged or JS-less submission bypasses that and would burn one of the tight monthly-budget requests on a lookup that can't produce a property. Property::AvmImport now validates name and the full address locally (localized error) before calling the provider. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Add preview-and-confirm step to the AVM property lookup RentCast's AVM endpoint is location-based: a plausible but nonexistent address still geocodes and returns an area-derived estimate with no property record behind it. Instead of silently creating an account from that, the lookup now shows what the provider returned — type, year built, area (each "Unknown" when missing), and the estimated value — with an explicit notice when no property record was found, and only the user's confirmation creates the account. The confirm step reuses the fetched data via the form (sanitized server-side), so the flow still costs exactly one provider request. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Require a complete US address before daily valuation refresh The job's guard only required street and state, but a later-blanked city or ZIP silently disables the Realie wrong-city check (blank entered fields count as "no mismatch"), so a refresh could accept another property's valuation. The guard now mirrors the import-time completeness check and also skips addresses edited to a non-US country. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Sign the AVM preview payload; blur valuation in privacy mode - The confirm step now rebuilds everything from a signed, 1-hour message-verifier token generated at lookup time, proving the lookup (and its counted provider request) actually ran — a direct confirm POST with fabricated data can no longer create provider-linked properties that the daily refresh job would then spend quota on. Forged/expired tokens re-render the lookup form with a clear error. - The preview's market value now carries the privacy-sensitive class so privacy mode blurs it like other account amounts. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Treat zero Realie valuations as absent; bind preview token to family Review follow-ups from PR #2727: - Realie returns modelValue: 0 when it can't produce an AVM estimate; zero now falls back to the assessed market value instead of syncing a $0 balance, and an all-zero record errors out. - Monetary values now parse via BigDecimal(value.to_s) rather than Float#to_d, avoiding binary float rounding artifacts in balances. - The signed AVM preview token's purpose is scoped to the family that ran the lookup, so a leaked token can't be replayed cross-family. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Refresh AVM property valuations monthly instead of daily Per @jjmata's review on #2727: valuations change slowly and providers enforce tight monthly request caps, so a daily cron adds no value. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
296 lines
11 KiB
Ruby
296 lines
11 KiB
Ruby
# Dynamic settings the user can change within the app (helpful for self-hosting)
|
|
class Setting < RailsSettings::Base
|
|
class ValidationError < StandardError; end
|
|
|
|
cache_prefix { "v1" }
|
|
|
|
# Third-party API keys
|
|
field :twelve_data_api_key, type: :string, default: ENV["TWELVE_DATA_API_KEY"]
|
|
field :openai_access_token, type: :string, default: ENV["OPENAI_ACCESS_TOKEN"]
|
|
field :openai_uri_base, type: :string, default: ENV["OPENAI_URI_BASE"]
|
|
field :openai_model, type: :string, default: ENV["OPENAI_MODEL"]
|
|
field :openai_json_mode, type: :string, default: ENV["LLM_JSON_MODE"]
|
|
field :anthropic_access_token, type: :string, default: ENV["ANTHROPIC_ACCESS_TOKEN"].presence || ENV["ANTHROPIC_API_KEY"].presence
|
|
field :anthropic_model, type: :string, default: ENV["ANTHROPIC_MODEL"]
|
|
field :anthropic_base_url, type: :string, default: ENV["ANTHROPIC_BASE_URL"]
|
|
field :llm_provider, type: :string, default: ENV.fetch("LLM_PROVIDER", "openai")
|
|
|
|
# LLM token budget (applies to every outbound LLM call: chat, auto-categorize,
|
|
# merchant detection, enhance-merchants, PDF processing). Defaults track
|
|
# Ollama's historical 2048-token baseline so local small-context models work
|
|
# out of the box. ENV overrides Setting at read time in Provider::Openai.
|
|
field :llm_context_window, type: :integer, default: ENV["LLM_CONTEXT_WINDOW"]&.to_i
|
|
field :llm_max_response_tokens, type: :integer, default: ENV["LLM_MAX_RESPONSE_TOKENS"]&.to_i
|
|
field :llm_max_items_per_call, type: :integer, default: ENV["LLM_MAX_ITEMS_PER_CALL"]&.to_i
|
|
field :external_assistant_url, type: :string
|
|
field :external_assistant_token, type: :string
|
|
field :external_assistant_agent_id, type: :string
|
|
field :brand_fetch_client_id, type: :string, default: ENV["BRAND_FETCH_CLIENT_ID"]
|
|
field :brand_fetch_high_res_logos, type: :boolean, default: ENV.fetch("BRAND_FETCH_HIGH_RES_LOGOS", "false") == "true"
|
|
|
|
BRAND_FETCH_LOGO_SIZE_STANDARD = 40
|
|
BRAND_FETCH_LOGO_SIZE_HIGH_RES = 120
|
|
# Matches both legacy single-segment URLs (`/apple.com/icon/...`) and
|
|
# explicit type-routed URLs introduced 2026 (`/crypto/BTC/icon/...`,
|
|
# `/domain/apple.com/icon/...`). `[^?]+` reaches across the extra slash
|
|
# so transform_brand_fetch_url can rewrite the size params on both shapes.
|
|
BRAND_FETCH_URL_PATTERN = %r{(https://cdn\.brandfetch\.io/[^?]+/icon/fallback/lettermark/)w/\d+/h/\d+(\?c=.+)}
|
|
|
|
def self.brand_fetch_logo_size
|
|
brand_fetch_high_res_logos ? BRAND_FETCH_LOGO_SIZE_HIGH_RES : BRAND_FETCH_LOGO_SIZE_STANDARD
|
|
end
|
|
|
|
# Transforms a stored Brandfetch URL to use the current logo size setting
|
|
def self.transform_brand_fetch_url(url)
|
|
return url unless url.present? && url.match?(BRAND_FETCH_URL_PATTERN)
|
|
|
|
size = brand_fetch_logo_size
|
|
url.gsub(BRAND_FETCH_URL_PATTERN, "\\1w/#{size}/h/#{size}\\2")
|
|
end
|
|
|
|
# Provider selection
|
|
field :exchange_rate_provider, type: :string, default: ENV.fetch("EXCHANGE_RATE_PROVIDER", "twelve_data")
|
|
field :securities_provider, type: :string, default: ENV.fetch("SECURITIES_PROVIDER", "twelve_data")
|
|
|
|
# Multi-provider: comma-separated list of enabled securities providers
|
|
field :securities_providers, type: :string, default: ENV.fetch("SECURITIES_PROVIDERS", "")
|
|
|
|
# New provider API keys (encrypted at rest — see EncryptedSettingFields below)
|
|
field :tiingo_api_key, type: :string, default: ENV["TIINGO_API_KEY"]
|
|
field :eodhd_api_key, type: :string, default: ENV["EODHD_API_KEY"]
|
|
field :alpha_vantage_api_key, type: :string, default: ENV["ALPHA_VANTAGE_API_KEY"]
|
|
field :tinkoff_invest_api_key, type: :string, default: ENV["TINKOFF_INVEST_API_KEY"]
|
|
|
|
# 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
|
|
# original getter/setter generated by rails-settings-cached.
|
|
#
|
|
# Backward-compatible: if decryption fails (e.g. the value was stored before
|
|
# encryption was enabled) the raw value is returned as-is.
|
|
module EncryptedSettingFields
|
|
ENCRYPTED_FIELDS = %i[
|
|
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
|
|
anthropic_access_token
|
|
external_assistant_token
|
|
].freeze
|
|
|
|
ENCRYPTED_FIELDS.each do |field_name|
|
|
define_method(field_name) do
|
|
raw = super()
|
|
decrypt_setting(raw)
|
|
end
|
|
|
|
define_method(:"#{field_name}=") do |value|
|
|
super(encrypt_setting(value))
|
|
end
|
|
end
|
|
|
|
private
|
|
|
|
def setting_encryptor
|
|
@setting_encryptor ||= begin
|
|
key = ActiveSupport::KeyGenerator.new(
|
|
Rails.application.secret_key_base
|
|
).generate_key("setting_encryption", 32)
|
|
ActiveSupport::MessageEncryptor.new(key)
|
|
end
|
|
end
|
|
|
|
def encrypt_setting(value)
|
|
return value if value.blank?
|
|
setting_encryptor.encrypt_and_sign(value)
|
|
end
|
|
|
|
def decrypt_setting(value)
|
|
return value if value.blank?
|
|
setting_encryptor.decrypt_and_verify(value)
|
|
rescue ActiveSupport::MessageVerifier::InvalidSignature,
|
|
ActiveSupport::MessageEncryptor::InvalidMessage
|
|
# Value was stored before encryption was enabled — return as-is.
|
|
# It will be re-encrypted on next write.
|
|
value
|
|
end
|
|
end
|
|
|
|
class << self
|
|
prepend EncryptedSettingFields
|
|
end
|
|
|
|
def self.enabled_securities_providers
|
|
plural = ENV["SECURITIES_PROVIDERS"].presence || securities_providers.presence
|
|
if plural.present?
|
|
plural.to_s.split(",").map(&:strip).reject(&:blank?)
|
|
else
|
|
# Backward compat: fall back to singular setting
|
|
[ ENV["SECURITIES_PROVIDER"].presence || securities_provider ].compact
|
|
end
|
|
end
|
|
|
|
# Sync settings - check both provider env vars for default
|
|
# Only defaults to true if neither provider explicitly disables pending
|
|
SYNCS_INCLUDE_PENDING_DEFAULT = begin
|
|
simplefin = ENV.fetch("SIMPLEFIN_INCLUDE_PENDING", "1") == "1"
|
|
plaid = ENV.fetch("PLAID_INCLUDE_PENDING", "1") == "1"
|
|
simplefin && plaid
|
|
end
|
|
field :syncs_include_pending, type: :boolean, default: SYNCS_INCLUDE_PENDING_DEFAULT
|
|
field :auto_sync_enabled, type: :boolean, default: ENV.fetch("AUTO_SYNC_ENABLED", "1") == "1"
|
|
field :auto_sync_time, type: :string, default: ENV.fetch("AUTO_SYNC_TIME", "02:22")
|
|
field :auto_sync_timezone, type: :string, default: ENV.fetch("AUTO_SYNC_TIMEZONE", "UTC")
|
|
|
|
AUTO_SYNC_TIME_FORMAT = /\A([01]?\d|2[0-3]):([0-5]\d)\z/
|
|
|
|
def self.valid_auto_sync_time?(time_str)
|
|
return false if time_str.blank?
|
|
AUTO_SYNC_TIME_FORMAT.match?(time_str.to_s.strip)
|
|
end
|
|
|
|
def self.valid_auto_sync_timezone?(timezone_str)
|
|
return false if timezone_str.blank?
|
|
ActiveSupport::TimeZone[timezone_str].present?
|
|
end
|
|
|
|
# Dynamic fields are now stored as individual entries with "dynamic:" prefix
|
|
# This prevents race conditions and ensures each field is independently managed
|
|
|
|
# Onboarding and app settings
|
|
ONBOARDING_STATES = %w[open closed invite_only].freeze
|
|
DEFAULT_ONBOARDING_STATE = begin
|
|
env_value = ENV["ONBOARDING_STATE"].to_s.presence || "open"
|
|
ONBOARDING_STATES.include?(env_value) ? env_value : "open"
|
|
end
|
|
|
|
field :onboarding_state, type: :string, default: DEFAULT_ONBOARDING_STATE
|
|
field :require_invite_for_signup, type: :boolean, default: false
|
|
field :require_email_confirmation, type: :boolean, default: ENV.fetch("REQUIRE_EMAIL_CONFIRMATION", "true") == "true"
|
|
field :invite_only_default_family_id, type: :string, default: nil
|
|
|
|
def self.validate_onboarding_state!(state)
|
|
return if ONBOARDING_STATES.include?(state)
|
|
|
|
raise ValidationError, I18n.t("settings.hostings.update.invalid_onboarding_state")
|
|
end
|
|
|
|
class << self
|
|
alias_method :raw_onboarding_state, :onboarding_state
|
|
alias_method :raw_onboarding_state=, :onboarding_state=
|
|
alias_method :raw_openai_model, :openai_model
|
|
alias_method :raw_openai_model=, :openai_model=
|
|
|
|
def onboarding_state
|
|
value = raw_onboarding_state
|
|
return "invite_only" if value.blank? && require_invite_for_signup
|
|
|
|
value.presence || DEFAULT_ONBOARDING_STATE
|
|
end
|
|
|
|
def onboarding_state=(state)
|
|
validate_onboarding_state!(state)
|
|
self.require_invite_for_signup = state == "invite_only"
|
|
self.raw_onboarding_state = state
|
|
end
|
|
|
|
def openai_model=(value)
|
|
old_value = raw_openai_model
|
|
self.raw_openai_model = value
|
|
|
|
if old_value != value && old_value.present?
|
|
Rails.logger.info("OpenAI model changed from #{old_value} to #{value}, clearing AI cache for all families")
|
|
Family.find_each do |family|
|
|
ClearAiCacheJob.perform_later(family)
|
|
end
|
|
end
|
|
end
|
|
|
|
# Support dynamic field access via bracket notation
|
|
# First checks if it's a declared field, then falls back to individual dynamic entries
|
|
def [](key)
|
|
key_str = key.to_s
|
|
|
|
# Check if it's a declared field first
|
|
if respond_to?(key_str)
|
|
public_send(key_str)
|
|
else
|
|
# Fall back to individual dynamic entry lookup
|
|
find_by(var: dynamic_key_name(key_str))&.value
|
|
end
|
|
end
|
|
|
|
def []=(key, value)
|
|
key_str = key.to_s
|
|
|
|
# If it's a declared field, use the setter
|
|
if respond_to?("#{key_str}=")
|
|
public_send("#{key_str}=", value)
|
|
else
|
|
# Store as individual dynamic entry
|
|
dynamic_key = dynamic_key_name(key_str)
|
|
if value.nil?
|
|
where(var: dynamic_key).destroy_all
|
|
clear_cache
|
|
else
|
|
# Use upsert for atomic insert/update to avoid race conditions
|
|
upsert({ var: dynamic_key, value: value.to_yaml }, unique_by: :var)
|
|
clear_cache
|
|
end
|
|
end
|
|
end
|
|
|
|
# Check if a dynamic field exists (useful to distinguish nil value vs missing key)
|
|
def key?(key)
|
|
key_str = key.to_s
|
|
return true if respond_to?(key_str)
|
|
|
|
# Check if dynamic entry exists
|
|
where(var: dynamic_key_name(key_str)).exists?
|
|
end
|
|
|
|
# Delete a dynamic field
|
|
def delete(key)
|
|
key_str = key.to_s
|
|
return nil if respond_to?(key_str) # Can't delete declared fields
|
|
|
|
dynamic_key = dynamic_key_name(key_str)
|
|
value = self[key_str]
|
|
where(var: dynamic_key).destroy_all
|
|
clear_cache
|
|
value
|
|
end
|
|
|
|
# List all dynamic field keys (excludes declared fields)
|
|
def dynamic_keys
|
|
where("var LIKE ?", "dynamic:%").pluck(:var).map { |var| var.sub(/^dynamic:/, "") }
|
|
end
|
|
|
|
private
|
|
|
|
def dynamic_key_name(key_str)
|
|
"dynamic:#{key_str}"
|
|
end
|
|
end
|
|
|
|
# Validates OpenAI configuration requires model when custom URI base is set
|
|
def self.validate_openai_config!(uri_base: nil, model: nil)
|
|
# Use provided values or current settings
|
|
uri_base_value = uri_base.nil? ? openai_uri_base : uri_base
|
|
model_value = model.nil? ? openai_model : model
|
|
|
|
# If custom URI base is set, model must also be set
|
|
if uri_base_value.present? && model_value.blank?
|
|
raise ValidationError, "OpenAI model is required when custom URI base is configured"
|
|
end
|
|
end
|
|
end
|