Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Let existing properties link to a valuation provider (#4282)

Tim Katzc2a86b4bc08c
diff --git a/app/controllers/properties_controller.rb b/app/controllers/properties_controller.rb
index 622c65b800..0a4b437289 100644
--- a/app/controllers/properties_controller.rb
+++ b/app/controllers/properties_controller.rb
@@ -1,8 +1,8 @@
class PropertiesController < ApplicationController
include AccountableResource, StreamExtensions
- 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 ]
+ before_action :set_property, only: [ :balances, :address, :update_balances, :update_address, :refresh_valuation, :link_valuation ]
+ before_action :require_property_write_permission!, only: [ :update_balances, :update_address, :refresh_valuation, :link_valuation ]
helper_method :avm_provider_class
@@ -86,6 +86,24 @@ class PropertiesController < ApplicationController
redirect_back_or_to account_path(@account), notice: t(".queued")
end
+ # Links a manually created property to an AVM provider so its value is
+ # refreshed automatically. The first valuation runs during the request and
+ # the link is only kept if it succeeds.
+ def link_valuation
+ provider_key = params[:avm_provider].to_s
+
+ unless configured_avm_providers.map(&:to_s).include?(provider_key) && @property.avm_linkable?(provider_key)
+ redirect_back_or_to account_path(@account), alert: t(".not_linkable") and return
+ end
+
+ provider_name = t("properties.avm_providers.#{provider_key}")
+ if @property.link_avm_provider!(provider_key)
+ redirect_back_or_to account_path(@account), notice: t(".linked", provider: provider_name)
+ else
+ redirect_back_or_to account_path(@account), alert: t(".link_failed", provider: provider_name)
+ end
+ end
+
def address
@property = @account.property
@property.address ||= Address.new
diff --git a/app/models/property.rb b/app/models/property.rb
index e49a43bdd7..734065d3da 100644
--- a/app/models/property.rb
+++ b/app/models/property.rb
@@ -68,6 +68,59 @@ class Property < ApplicationRecord
entry.update!(name: I18n.t("providers.property_valuation.entry_name", provider: provider_name))
end
+ # Whether an unlinked property can be linked to the given AVM provider for
+ # automatic refreshes. Only address-based providers qualify: ID-based
+ # providers (Chimnie) need an identifier that only the create-time lookup
+ # supplies. The account must already be in the provider's currency so a
+ # refresh can't write a valuation in the wrong currency. Unlike the
+ # create-time lookup, which always sets the country, a manual address may
+ # omit it, so require one to confirm the property is in the provider's
+ # country.
+ def avm_linkable?(provider_key)
+ return false if avm_provider.present? || address&.country.blank?
+
+ provider_class = Provider::PropertyValuationConcept.provider_class(provider_key)
+ return false if provider_class.nil? || provider_class.requires_external_id?
+
+ account.currency == provider_class.valuation_currency && provider_class.lookup_ready?(address)
+ end
+
+ # Configured providers this property can be linked to.
+ def linkable_avm_providers
+ return [] if avm_provider.present?
+
+ registry = Provider::Registry.for_concept(:property_valuations)
+ registry.provider_keys.select { |key| avm_linkable?(key) && registry.get_provider(key).present? }
+ end
+
+ # Links the property to an AVM provider and runs its first valuation right
+ # away. The link is kept only if that valuation succeeds; a failure (an
+ # address the provider can't value, an exhausted monthly budget) reverts
+ # it, so the property can still be linked to another provider instead of
+ # being stuck on one that never worked. Returns whether the link was kept.
+ #
+ # Claiming and reverting are conditional updates, so overlapping link
+ # attempts can't clear each other's link: only the attempt that claimed the
+ # unlinked property runs the valuation, and the revert only applies while
+ # that attempt's link is still unsynced.
+ def link_avm_provider!(provider_key)
+ raise ArgumentError, "#{provider_key} can't be linked to this property" unless avm_linkable?(provider_key)
+
+ key = provider_key.to_s
+ claimed = Property.where(id: id, avm_provider: nil)
+ .update_all(avm_provider: key, avm_last_synced_on: nil, updated_at: Time.current)
+ return false unless claimed == 1
+
+ SyncPropertyValuationsJob.perform_now(property_id: id, force: true)
+ reload
+ return true if avm_provider == key && avm_last_synced_on.present?
+
+ Property.where(id: id, avm_provider: key, avm_last_synced_on: nil)
+ .update_all(avm_provider: nil, updated_at: Time.current)
+ reload
+ false
+ end
+
private
def first_valuation_amount
account.entries.valuations.order(:date).first&.amount_money || account.balance_money
diff --git a/app/models/provider/property_valuation_concept.rb b/app/models/provider/property_valuation_concept.rb
index ac257adbf0..46377a516b 100644
--- a/app/models/provider/property_valuation_concept.rb
+++ b/app/models/provider/property_valuation_concept.rb
@@ -8,9 +8,12 @@
module Provider::PropertyValuationConcept
extend ActiveSupport::Concern
+ # Addresses entered by hand store the country as typed, so full names
+ # ("United States") must match as well as codes. Compared after
+ # upcasing and removing periods ("U.S.A." → "USA").
COUNTRY_ALIASES = {
- "US" => %w[US USA],
- "GB" => %w[GB UK GBR]
+ "US" => [ "US", "USA", "UNITED STATES", "UNITED STATES OF AMERICA" ],
+ "GB" => [ "GB", "UK", "GBR", "UNITED KINGDOM", "GREAT BRITAIN" ]
}.freeze
# `external_id` is the provider's own identifier for the property (e.g. a
@@ -71,7 +74,7 @@ module Provider::PropertyValuationConcept
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 = address[:country].to_s.delete(".").squish.upcase
country.blank? || COUNTRY_ALIASES.fetch(supported_country, [ supported_country ]).include?(country)
end
end
diff --git a/app/views/properties/tabs/_overview.html.erb b/app/views/properties/tabs/_overview.html.erb
index 4403287e82..e1fd250dc3 100644
--- a/app/views/properties/tabs/_overview.html.erb
+++ b/app/views/properties/tabs/_overview.html.erb
@@ -41,9 +41,23 @@
text: t(".refresh_valuation"),
href: refresh_valuation_property_path(account),
variant: "outline",
- icon: "refresh-cw"
+ icon: "refresh-cw",
+ data: { turbo_frame: "_top" }
) %>
</div>
+<% elsif (linkable_providers = account.property.linkable_avm_providers).any? %>
+ <div class="flex flex-col items-center gap-2 pt-8">
+ <p class="text-sm text-secondary"><%= t(".link_valuation_description") %></p>
+ <% linkable_providers.each do |provider_key| %>
+ <%= render DS::Button.new(
+ text: t(".link_valuation", provider: t("properties.avm_providers.#{provider_key}")),
+ href: link_valuation_property_path(account, avm_provider: provider_key),
+ variant: "outline",
+ icon: "link",
+ data: { turbo_frame: "_top" }
+ ) %>
+ <% end %>
+ </div>
<% end %>
<div class="flex justify-center py-8">
diff --git a/config/locales/views/properties/en.yml b/config/locales/views/properties/en.yml
index f52a1a43e6..c5b54ac0d3 100644
--- a/config/locales/views/properties/en.yml
+++ b/config/locales/views/properties/en.yml
@@ -103,10 +103,16 @@ en:
edit_account_details: "Edit account details"
refresh_valuation: "Refresh valuation"
valuation_source: "Valued by %{provider}, last updated %{date}"
+ link_valuation: "Update value automatically with %{provider}"
+ link_valuation_description: "This property's value is only updated manually."
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."
+ link_valuation:
+ linked: "Linked to %{provider} and updated the property's value."
+ link_failed: "%{provider} couldn't value this property, so it wasn't linked. Check that the address is correct, then try again."
+ not_linkable: "This property can't be linked to that provider. Check that its address is complete and in a supported country, and that the account currency matches the provider."
subtypes:
apartment:
short: Apartment
diff --git a/config/routes.rb b/config/routes.rb
index 02c50dea99..ed0a070b59 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -706,6 +706,7 @@ Rails.application.routes.draw do
patch :update_address
post :refresh_valuation
+ post :link_valuation
end
end
resources :vehicles, only: %i[new create edit update]
diff --git a/test/controllers/properties_controller_test.rb b/test/controllers/properties_controller_test.rb
index 8b5093ee1f..fc16240243 100644
--- a/test/controllers/properties_controller_test.rb
+++ b/test/controllers/properties_controller_test.rb
@@ -709,4 +709,142 @@ class PropertiesControllerTest < ActionDispatch::IntegrationTest
assert_response :success
assert_select "form[action='#{refresh_valuation_property_path(@account)}']"
end
+
+ test "link_valuation links a manual property after its first valuation succeeds" do
+ @account.property.update!(avm_provider: nil, avm_last_synced_on: 1.year.ago.to_date)
+ @account.property.address.update!(country: "United States")
+ Provider::Registry.stubs(:rentcast).returns(rentcast_provider_returning(Provider::Response.new(success?: true, data: valuation_data(612_000), error: nil)))
+
+ post link_valuation_property_path(@account, avm_provider: "rentcast")
+
+ assert_redirected_to account_path(@account)
+ assert_equal "Linked to RentCast and updated the property's value.", flash[:notice]
+ assert_equal "rentcast", @account.property.reload.avm_provider
+ assert_equal Date.current, @account.property.avm_last_synced_on
+ assert_equal 612_000, @account.reload.balance
+ end
+
+ test "link_valuation keeps the property unlinked when the first valuation fails" do
+ @account.property.update!(avm_provider: nil)
+ error = Provider::Rentcast::Error.new("No property found")
+ Provider::Registry.stubs(:rentcast).returns(rentcast_provider_returning(Provider::Response.new(success?: false, data: nil, error: error)))
+
+ post link_valuation_property_path(@account, avm_provider: "rentcast")
+
+ assert_redirected_to account_path(@account)
+ assert_equal "RentCast couldn't value this property, so it wasn't linked. Check that the address is correct, then try again.", flash[:alert]
+ assert_nil @account.property.reload.avm_provider
+ assert_equal 550_000, @account.reload.balance
+ end
+
+ test "link_valuation keeps the property unlinked when the provider budget is spent" do
+ @account.property.update!(avm_provider: nil)
+ provider = mock
+ provider.stubs(:requests_remaining?).returns(false)
+ provider.expects(:fetch_property_valuation).never
+ Provider::Registry.stubs(:rentcast).returns(provider)
+
+ post link_valuation_property_path(@account, avm_provider: "rentcast")
+
+ assert_nil @account.property.reload.avm_provider
+ assert flash[:alert].present?
+ end
+
+ test "link_valuation refuses an unconfigured provider" do
+ @account.property.update!(avm_provider: nil)
+ Provider::Registry.stubs(:rentcast).returns(nil)
+
+ assert_no_enqueued_jobs(only: SyncPropertyValuationsJob) do
+ post link_valuation_property_path(@account, avm_provider: "rentcast")
+ end
+
+ assert_redirected_to account_path(@account)
+ assert_nil @account.property.reload.avm_provider
+ end
+
+ test "link_valuation refuses providers that need a property identifier" do
+ @account.property.update!(avm_provider: nil)
+ Provider::Registry.stubs(:chimnie).returns(mock)
+
+ assert_no_enqueued_jobs(only: SyncPropertyValuationsJob) do
+ post link_valuation_property_path(@account, avm_provider: "chimnie")
+ end
+
+ assert_nil @account.property.reload.avm_provider
+ end
+
+ test "link_valuation refuses addresses outside the provider's country" do
+ @account.property.update!(avm_provider: nil)
+ @account.property.address.update!(country: "Canada")
+ Provider::Registry.stubs(:rentcast).returns(mock)
+
+ assert_no_enqueued_jobs(only: SyncPropertyValuationsJob) do
+ post link_valuation_property_path(@account, avm_provider: "rentcast")
+ end
+
+ assert_nil @account.property.reload.avm_provider
+ end
+
+ test "link_valuation requires a known country" do
+ @account.property.update!(avm_provider: nil)
+ @account.property.address.update!(country: "")
+ Provider::Registry.stubs(:rentcast).returns(mock)
+
+ assert_no_enqueued_jobs(only: SyncPropertyValuationsJob) do
+ post link_valuation_property_path(@account, avm_provider: "rentcast")
+ end
+
+ assert_nil @account.property.reload.avm_provider
+ end
+
+ test "link_valuation does not replace an existing provider" do
+ @account.property.update!(avm_provider: "realie")
+ Provider::Registry.stubs(:rentcast).returns(mock)
+
+ assert_no_enqueued_jobs(only: SyncPropertyValuationsJob) do
+ post link_valuation_property_path(@account, avm_provider: "rentcast")
+ end
+
+ assert_equal "realie", @account.property.reload.avm_provider
+ end
+
+ test "link_valuation is scoped to the current family" do
+ @account.property.update!(avm_provider: nil)
+ Provider::Registry.stubs(:rentcast).returns(mock)
+ sign_in users(:empty)
+
+ assert_no_enqueued_jobs(only: SyncPropertyValuationsJob) do
+ post link_valuation_property_path(@account, avm_provider: "rentcast")
+ end
+
+ assert_response :not_found
+ assert_nil @account.property.reload.avm_provider
+ end
+
+ test "overview offers linking a manual property to a configured provider" do
+ @account.property.update!(avm_provider: nil)
+ Provider::Registry.stubs(:rentcast).returns(mock)
+
+ get account_path(@account, tab: "overview")
+
+ assert_response :success
+ assert_select "form[action='#{link_valuation_property_path(@account, avm_provider: "rentcast")}']"
+ assert_select "form[action*='avm_provider=chimnie']", count: 0
+ end
+
+ private
+ def valuation_data(valuation)
+ Provider::PropertyValuationConcept::PropertyValuation.new(
+ valuation: valuation, currency: "USD", property_type: "single_family_home",
+ year_built: 2002, area_value: 1000, area_unit: "sqft"
+ )
+ end
+
+ def rentcast_provider_returning(response)
+ provider = mock
+ provider.stubs(:requests_remaining?).returns(true)
+ provider.stubs(:valuation_currency).returns("USD")
+ provider.stubs(:fetch_property_valuation).returns(response)
+ provider
+ end
end
diff --git a/test/models/property_test.rb b/test/models/property_test.rb
index d24c39a61d..2d7592a737 100644
--- a/test/models/property_test.rb
+++ b/test/models/property_test.rb
@@ -50,4 +50,19 @@ class PropertyTest < ActiveSupport::TestCase
assert_equal "Original purchase price", entry.reload.name
end
+
+ test "link_avm_provider! never clears a link another request already made" do
+ property = accounts(:property).property
+ property.update!(avm_provider: nil)
+ stale = Property.find(property.id)
+ Provider::Registry.stubs(:rentcast).returns(mock)
+ Property.where(id: property.id).update_all(avm_provider: "realie", avm_last_synced_on: Date.current)
+
+ SyncPropertyValuationsJob.expects(:perform_now).never
+ assert_not stale.link_avm_provider!("rentcast")
+
+ property.reload
+ assert_equal "realie", property.avm_provider
+ assert_equal Date.current, property.avm_last_synced_on
+ end
end
diff --git a/test/models/provider/chimnie_test.rb b/test/models/provider/chimnie_test.rb
index dcced1367c..d76ebaea2a 100644
--- a/test/models/provider/chimnie_test.rb
+++ b/test/models/provider/chimnie_test.rb
@@ -219,4 +219,18 @@ class Provider::ChimnieTest < ActiveSupport::TestCase
assert_not Provider::Rentcast.lookup_ready?(address.merge(country: "GB"))
assert_equal "USD", Provider::Rentcast.new("key").valuation_currency
end
+
+ test "accepts country names typed into manually entered addresses" do
+ us_address = { line1: "123 Main Street", locality: "Los Angeles", region: "CA", postal_code: "90001" }
+ uk_address = { line1: "1 High Street", postal_code: "CH1 1MN" }
+
+ [ "United States", "united states of america", "U.S.A.", " USA " ].each do |country|
+ assert Provider::Rentcast.lookup_ready?(us_address.merge(country: country)), "expected #{country.inspect} to match US"
+ end
+ [ "United Kingdom", "Great Britain", "U.K." ].each do |country|
+ assert Provider::Chimnie.lookup_ready?(uk_address.merge(country: country), "999000000001"), "expected #{country.inspect} to match GB"
+ end
+ assert_not Provider::Rentcast.lookup_ready?(us_address.merge(country: "United Kingdom"))
+ assert_not Provider::Rentcast.lookup_ready?(us_address.merge(country: "Canada"))
+ end
end