Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Ask for the purchase date when setting up a property (#5054)

arnaurodondev91d0747287cc
diff --git a/app/controllers/properties_controller.rb b/app/controllers/properties_controller.rb
index e8c8f173cd..c3d14f5cc6 100644
--- a/app/controllers/properties_controller.rb
+++ b/app/controllers/properties_controller.rb
@@ -4,7 +4,7 @@ class PropertiesController < ApplicationController
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
+ helper_method :avm_provider_class, :purchase_value
def new
@account = Current.family.accounts.build(accountable: Property.new)
@@ -53,10 +53,22 @@ class PropertiesController < ApplicationController
end
def update_balances
+ if balance_params[:currency].present? && !known_currency?(balance_params[:currency])
+ return render_balances_error(t(".invalid_currency"))
+ end
+
+ if @account.draft? && !purchase_value.valid_date?
+ return render_balances_error(t(".invalid_purchase_date"))
+ end
+
result = nil
Account.transaction do
@account.update!(currency: balance_params[:currency]) if balance_params[:currency].present?
- result = @account.set_current_balance(balance_params[:balance].to_d)
+ result = if @account.draft?
+ purchase_value.save(balance_params[:balance].to_d)
+ else
+ @account.set_current_balance(balance_params[:balance].to_d)
+ end
raise ActiveRecord::Rollback unless result.success?
end
@@ -69,8 +81,7 @@ class PropertiesController < ApplicationController
redirect_to address_property_path(@account)
end
else
- @error_message = result&.error_message
- render :balances, status: :unprocessable_entity
+ render_balances_error(result&.error)
end
end
@@ -276,7 +287,28 @@ class PropertiesController < ApplicationController
end
def balance_params
- params.require(:account).permit(:balance, :currency)
+ params.require(:account).permit(:balance, :currency, :purchase_date)
+ end
+
+ def purchase_value
+ @purchase_value ||= Property::PurchaseValue.new(
+ @account, date: (balance_params[:purchase_date] if params[:account].is_a?(ActionController::Parameters))
+ )
+ end
+
+ # Re-renders the value step with what the user typed, not the saved value.
+ # A currency the app doesn't know is left out, since the form can't render it.
+ def render_balances_error(message)
+ submitted = balance_params.slice(:balance, :currency).compact_blank
+ submitted.delete(:currency) unless known_currency?(submitted[:currency])
+ @account.assign_attributes(submitted)
+ @submitted_balance = submitted.key?(:balance)
+ @error_message = message
+ render :balances, status: :unprocessable_entity
+ end
+
+ def known_currency?(code)
+ Money::Currency.all.key?(code.to_s.downcase)
end
def address_params
diff --git a/app/models/property/purchase_value.rb b/app/models/property/purchase_value.rb
new file mode 100644
index 0000000000..f020baed90
--- /dev/null
+++ b/app/models/property/purchase_value.rb
@@ -0,0 +1,75 @@
+# The value step of the property setup wizard. What the property was bought
+# for is its opening anchor ("Original purchase price") on the purchase date,
+# as the generic account form does with its opening balance date.
+# Saving again moves that one valuation rather than adding one.
+class Property::PurchaseValue
+ attr_reader :account, :submitted_date
+
+ # +date+ is the submitted purchase date; nil or a blank string means the
+ # default.
+ def initialize(account, date: nil)
+ @account = account
+ @submitted_date = date
+ end
+
+ # Raises Date::Error when the submitted date can't be parsed. A JSON body
+ # can send a number or a boolean, and the parser rejects a string over 128
+ # characters with a plain ArgumentError; both count as unparseable.
+ def date
+ return default_date if @submitted_date.nil?
+ # Checked before blank?, which counts false, [] and {} as blank too.
+ raise Date::Error, "invalid date" unless @submitted_date.is_a?(String)
+ return default_date if @submitted_date.blank?
+
+ begin
+ @submitted_date.to_date
+ rescue ArgumentError
+ raise Date::Error, "invalid date"
+ end
+ end
+
+ # What the date field shows: the text submitted, or the default. A
+ # non-string submission is not shown back, since the field can only format
+ # text or a date.
+ def field_date
+ submitted = @submitted_date if @submitted_date.is_a?(String)
+ submitted.presence || default_date
+ end
+
+ # Not in the future, and after the oldest date an entry may have.
+ def valid_date?
+ date > Entry.min_supported_date && date <= Date.current
+ rescue Date::Error
+ false
+ end
+
+ # The purchase valuation must come before any other value the draft
+ # already has, so the default is the latest date that allows it, kept
+ # within the range the field accepts.
+ def default_date
+ return account.opening_anchor_date if account.has_opening_anchor?
+
+ oldest = Account::OpeningBalanceManager.new(account).oldest_entry_date
+ latest = oldest ? [ oldest.prev_day, Date.current ].min : Date.current
+ [ latest, Entry.min_supported_date + 1 ].max
+ end
+
+ # The account's balance is its latest value, which on a draft that already
+ # had a value can differ from the purchase price saved before.
+ def price
+ account.has_opening_anchor? ? account.opening_anchor_balance : account.balance
+ end
+
+ # Returns the opening balance manager's result.
+ def save(balance)
+ result = Account::OpeningBalanceManager.new(account).set_opening_balance(balance: balance, date: date)
+ return result unless result.success?
+
+ # The amount was typed in the account's current currency, which a
+ # resubmitted step may have changed.
+ account.valuations.opening_anchor.first.entry.update!(currency: account.currency)
+ account.update!(balance: balance)
+ account.sync_later
+ result
+ end
+end
diff --git a/app/views/properties/balances.html.erb b/app/views/properties/balances.html.erb
index 9477213f70..4604a19898 100644
--- a/app/views/properties/balances.html.erb
+++ b/app/views/properties/balances.html.erb
@@ -11,9 +11,18 @@
<%= render "properties/form_alert", notice: @success_message, error: @error_message %>
<%= form.money_field :balance,
- label: t(".market_value_label"),
- label_tooltip: t(".market_value_tooltip"),
+ label: @account.draft? ? t("vehicles.form.purchase_price") : t(".market_value_label"),
+ label_tooltip: (t(".market_value_tooltip") unless @account.draft?),
+ value: (purchase_value.price if @account.draft? && !@submitted_balance),
placeholder: "0" %>
+
+ <% if @account.draft? %>
+ <%= form.date_field :purchase_date,
+ label: t(".purchase_date_label"),
+ value: purchase_value.field_date,
+ min: Entry.min_supported_date + 1,
+ max: Date.current %>
+ <% end %>
</div>
<!-- Next button -->
diff --git a/config/locales/views/properties/en.yml b/config/locales/views/properties/en.yml
index 23c8dd50be..85594f082b 100644
--- a/config/locales/views/properties/en.yml
+++ b/config/locales/views/properties/en.yml
@@ -76,6 +76,7 @@ en:
title: "Enter property manually"
market_value_label: "Estimated market value"
market_value_tooltip: "The estimated market value of your property. This number can often be found on sites like Zillow or Redfin, and is never an exact number."
+ purchase_date_label: "Purchase date"
save: "Save"
next: "Next"
overview_fields:
@@ -112,6 +113,9 @@ en:
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."
+ update_balances:
+ invalid_currency: "Choose a currency from the list."
+ invalid_purchase_date: "Enter a purchase date that isn't in the future or more than 30 years ago."
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."
diff --git a/test/controllers/properties_controller_test.rb b/test/controllers/properties_controller_test.rb
index f9571282de..2653bed07b 100644
--- a/test/controllers/properties_controller_test.rb
+++ b/test/controllers/properties_controller_test.rb
@@ -147,8 +147,220 @@ class PropertiesControllerTest < ActionDispatch::IntegrationTest
end
end
+ test "value step dates the first valuation on the purchase date" do
+ account = create_draft_property
+
+ patch update_balances_property_path(account), params: {
+ account: { balance: 150_000_000, currency: "PYG", purchase_date: 3.years.ago.to_date.iso8601 }
+ }
+
+ assert_redirected_to address_property_path(account)
+ account.reload
+ assert_equal "PYG", account.currency
+ assert_equal 150_000_000, account.balance
+
+ valuations = account.entries.valuations
+ assert_equal 1, valuations.count
+ assert_equal 3.years.ago.to_date, valuations.first.date
+ assert_equal "PYG", valuations.first.currency
+ assert_equal Money.new(150_000_000, "PYG"), account.property.purchase_price
+ end
+
+ test "value step defaults the purchase date to today" do
+ account = create_draft_property
+
+ patch update_balances_property_path(account), params: { account: { balance: 500_000, currency: "USD" } }
+
+ assert_redirected_to address_property_path(account)
+ assert_equal [ Date.current ], account.entries.valuations.pluck(:date)
+ end
+
+ test "resubmitting the value step moves the purchase valuation instead of adding one" do
+ account = create_draft_property
+
+ patch update_balances_property_path(account), params: {
+ account: { balance: 100, currency: "EUR", purchase_date: 1.year.ago.to_date.iso8601 }
+ }
+ patch update_balances_property_path(account), params: {
+ account: { balance: 150_000_000, currency: "PYG", purchase_date: 2.years.ago.to_date.iso8601 }
+ }
+
+ valuation = account.entries.valuations.sole
+ assert_equal 2.years.ago.to_date, valuation.date
+ assert_equal 150_000_000, valuation.amount
+ assert_equal "PYG", valuation.currency
+ end
+
+ test "value step rejects a purchase date in the future" do
+ account = create_draft_property
+
+ patch update_balances_property_path(account), params: {
+ account: { balance: 100, currency: "EUR", purchase_date: 1.day.from_now.to_date.iso8601 }
+ }
+
+ assert_response :unprocessable_entity
+ assert_empty account.entries.valuations
+ end
+
+ test "value step shows the purchase date only while the property is being set up" do
+ get balances_property_path(create_draft_property)
+ assert_select "input[name='account[purchase_date]']"
+
+ get balances_property_path(@account)
+ assert_select "input[name='account[purchase_date]']", count: 0
+ end
+
+ test "value step asks for the purchase price while the property is being set up" do
+ get balances_property_path(create_draft_property)
+ assert_select "label", text: "Purchase price"
+ assert_select "label", text: "Estimated market value", count: 0
+ assert_no_match "Zillow", response.body
+
+ get balances_property_path(@account)
+ assert_select "label", text: "Estimated market value"
+ assert_select "label", text: "Purchase price", count: 0
+ end
+
+ test "value step defaults the purchase date to before a value the draft already has" do
+ account = create_draft_property
+ add_reconciliation(account, date: Date.current, amount: 90_000)
+
+ get balances_property_path(account)
+ assert_select "input[name='account[purchase_date]'][value='#{Date.yesterday.iso8601}']"
+
+ patch update_balances_property_path(account), params: {
+ account: { balance: 100_000, currency: "EUR", purchase_date: Date.yesterday.iso8601 }
+ }
+ assert_redirected_to address_property_path(account)
+ assert_equal Date.yesterday, account.reload.opening_anchor_date
+ end
+
+ test "value step dates a blank purchase date before a value the draft already has" do
+ account = create_draft_property
+ oldest = 5.years.ago.to_date
+ add_reconciliation(account, date: oldest, amount: 90_000)
+
+ patch update_balances_property_path(account), params: { account: { balance: 100_000, currency: "EUR" } }
+
+ assert_redirected_to address_property_path(account)
+ assert_equal oldest.prev_day, account.reload.opening_anchor_date
+ end
+
+ test "value step keeps the default purchase date within the accepted range" do
+ account = create_draft_property
+ add_reconciliation(account, date: Entry.min_supported_date + 1, amount: 90_000)
+
+ get balances_property_path(account)
+ assert_select "input[name='account[purchase_date]'][value='#{(Entry.min_supported_date + 1).iso8601}']"
+ end
+
+ test "value step shows the saved purchase price, not a later value" do
+ account = create_draft_property
+ add_reconciliation(account, date: Date.current, amount: 90_000)
+ patch update_balances_property_path(account), params: {
+ account: { balance: 100_000, currency: "EUR", purchase_date: 1.year.ago.to_date.iso8601 }
+ }
+ account.update!(balance: 90_000)
+
+ get balances_property_path(account)
+ assert_select "input[name='account[balance]'][value='100000.00']"
+ end
+
+ test "value step keeps showing the saved purchase price when a blank price is rejected" do
+ account = create_draft_property
+ add_reconciliation(account, date: Date.current, amount: 90_000)
+ patch update_balances_property_path(account), params: {
+ account: { balance: 100_000, currency: "EUR", purchase_date: 1.year.ago.to_date.iso8601 }
+ }
+ account.update!(balance: 90_000)
+
+ patch update_balances_property_path(account), params: {
+ account: { balance: "", currency: "EUR", purchase_date: 1.day.from_now.to_date.iso8601 }
+ }
+ assert_response :unprocessable_entity
+ assert_select "input[name='account[balance]'][value='100000.00']"
+ end
+
+ test "value step ignores a malformed account parameter" do
+ get balances_property_path(create_draft_property), params: { account: "x" }
+
+ assert_response :success
+ assert_select "input[name='account[purchase_date]'][value='#{Date.current.iso8601}']"
+ end
+
+ test "value step rejects an unknown currency" do
+ account = create_draft_property
+ add_reconciliation(account, date: 1.year.ago.to_date, amount: 90_000)
+
+ [ 1.day.from_now.to_date, Date.current ].each do |purchase_date|
+ patch update_balances_property_path(account), params: {
+ account: { balance: 250_000, currency: "XXX", purchase_date: purchase_date.iso8601 }
+ }
+
+ assert_response :unprocessable_entity
+ assert_select "input[name='account[balance]'][value='250000.00']"
+ end
+ assert_equal "EUR", account.reload.currency
+ assert_not account.has_opening_anchor?
+ end
+
+ test "value step rejects an unknown currency on a valid submission" do
+ account = create_draft_property
+
+ patch update_balances_property_path(account), params: {
+ account: { balance: 250_000, currency: "XXX", purchase_date: 1.year.ago.to_date.iso8601 }
+ }
+
+ assert_response :unprocessable_entity
+ assert_match "Choose a currency from the list.", response.body
+ assert_equal "EUR", account.reload.currency
+ assert_not account.has_opening_anchor?
+ end
+
+ test "value step keeps the submitted price when the purchase date is rejected" do
+ account = create_draft_property
+ add_reconciliation(account, date: 1.year.ago.to_date, amount: 90_000)
+
+ patch update_balances_property_path(account), params: {
+ account: { balance: 250_000, currency: "EUR", purchase_date: Date.current.iso8601 }
+ }
+ assert_response :unprocessable_entity
+ assert_select "input[name='account[balance]'][value='250000.00']"
+
+ patch update_balances_property_path(account), params: {
+ account: { balance: 260_000, currency: "EUR", purchase_date: 1.day.from_now.to_date.iso8601 }
+ }
+ assert_response :unprocessable_entity
+ assert_select "input[name='account[balance]'][value='260000.00']"
+ end
+
+ test "value step rejects an oversized or non-string purchase date and keeps the submitted price" do
+ account = create_draft_property
+
+ patch update_balances_property_path(account), params: {
+ account: { balance: 250_000, currency: "EUR", purchase_date: "2020-03-01#{" " * 119}" }
+ }
+ assert_response :unprocessable_entity
+ assert_select "input[name='account[balance]'][value='250000.00']"
+
+ patch update_balances_property_path(account),
+ params: { account: { balance: 260_000, currency: "EUR", purchase_date: 20200301 } }.to_json,
+ headers: { "CONTENT_TYPE" => "application/json" }
+ assert_response :unprocessable_entity
+ assert_select "input[name='account[balance]'][value='260000.00']"
+
+ patch update_balances_property_path(account),
+ params: { account: { balance: 270_000, currency: "EUR", purchase_date: false } }.to_json,
+ headers: { "CONTENT_TYPE" => "application/json" }
+ assert_response :unprocessable_entity
+ assert_select "input[name='account[balance]'][value='270000.00']"
+
+ assert_not account.reload.has_opening_anchor?
+ end
+
test "balances update handles validation errors" do
- Account.any_instance.stubs(:set_current_balance).returns(OpenStruct.new(success?: false, error_message: "Invalid balance"))
+ Account.any_instance.stubs(:set_current_balance)
+ .returns(Account::CurrentBalanceManager::Result.new(success?: false, changes_made?: false, error: "Invalid balance"))
patch update_balances_property_path(@account), params: {
account: {
@@ -158,6 +370,7 @@ class PropertiesControllerTest < ActionDispatch::IntegrationTest
}
assert_response :unprocessable_entity
+ assert_match "Invalid balance", response.body
end
test "address update handles validation errors" do
@@ -930,4 +1143,18 @@ class PropertiesControllerTest < ActionDispatch::IntegrationTest
provider.stubs(:fetch_property_valuation).returns(response)
provider
end
+
+ def create_draft_property
+ @user.family.accounts.create!(
+ name: "Land", balance: 0, currency: "EUR", status: "draft", owner: @user,
+ accountable: Property.new(subtype: "plot")
+ )
+ end
+
+ def add_reconciliation(account, date:, amount:)
+ account.entries.create!(
+ date: date, name: "Manual value update", amount: amount, currency: account.currency,
+ entryable: Valuation.new(kind: "reconciliation")
+ )
+ end
end
diff --git a/test/models/property/purchase_value_test.rb b/test/models/property/purchase_value_test.rb
new file mode 100644
index 0000000000..8568a5612e
--- /dev/null
+++ b/test/models/property/purchase_value_test.rb
@@ -0,0 +1,85 @@
+require "test_helper"
+
+class Property::PurchaseValueTest < ActiveSupport::TestCase
+ setup do
+ @account = families(:dylan_family).accounts.create!(
+ name: "Land", balance: 0, currency: "EUR", status: "draft", owner: users(:family_admin),
+ accountable: Property.new(subtype: "plot")
+ )
+ end
+
+ test "defaults the date to today on a draft without values" do
+ assert_equal Date.current, Property::PurchaseValue.new(@account).date
+ end
+
+ test "defaults the date to the day before a value the draft already has" do
+ add_reconciliation(date: 5.years.ago.to_date, amount: 90_000)
+
+ assert_equal 5.years.ago.to_date.prev_day, Property::PurchaseValue.new(@account).default_date
+ end
+
+ test "uses a submitted date over the default" do
+ assert_equal Date.new(2020, 3, 1), Property::PurchaseValue.new(@account, date: "2020-03-01").date
+ end
+
+ test "accepts dates from the day after the oldest supported date to today" do
+ assert Property::PurchaseValue.new(@account, date: (Entry.min_supported_date + 1).iso8601).valid_date?
+ assert Property::PurchaseValue.new(@account, date: Date.current.iso8601).valid_date?
+ assert_not Property::PurchaseValue.new(@account, date: Entry.min_supported_date.iso8601).valid_date?
+ assert_not Property::PurchaseValue.new(@account, date: Date.tomorrow.iso8601).valid_date?
+ assert_not Property::PurchaseValue.new(@account, date: "not a date").valid_date?
+ end
+
+ test "rejects a submitted date that is not a string the parser accepts" do
+ # A JSON body can send a number or a boolean, and the date parser rejects
+ # strings over 128 characters with a plain ArgumentError.
+ [ 20200301, 1.5, true, false, [], {}, "2020-03-01#{" " * 119}" ].each do |submitted|
+ assert_not Property::PurchaseValue.new(@account, date: submitted).valid_date?, submitted.inspect
+ end
+ end
+
+ test "nil or a blank string uses the default date" do
+ [ nil, "", " " ].each do |submitted|
+ assert_equal Date.current, Property::PurchaseValue.new(@account, date: submitted).date, submitted.inspect
+ end
+ end
+
+ test "saving dates the purchase valuation and sets the balance" do
+ @account.update!(currency: "PYG")
+
+ result = Property::PurchaseValue.new(@account, date: 3.years.ago.to_date.iso8601).save(150_000_000)
+
+ assert result.success?
+ valuation = @account.entries.valuations.sole
+ assert_equal 3.years.ago.to_date, valuation.date
+ assert_equal 150_000_000, valuation.amount
+ assert_equal "PYG", valuation.currency
+ assert_equal 150_000_000, @account.reload.balance
+ end
+
+ test "saving a date on or after the draft's other values fails without writing" do
+ add_reconciliation(date: 1.year.ago.to_date, amount: 90_000)
+
+ result = Property::PurchaseValue.new(@account, date: Date.current.iso8601).save(100_000)
+
+ assert_not result.success?
+ assert_equal "Opening balance date must be before the oldest entry date", result.error
+ assert_not @account.has_opening_anchor?
+ end
+
+ test "the price is the saved purchase valuation, not the latest value" do
+ Property::PurchaseValue.new(@account, date: 2.years.ago.to_date.iso8601).save(100_000)
+ add_reconciliation(date: Date.current, amount: 250_000)
+ @account.update!(balance: 250_000)
+
+ assert_equal 100_000, Property::PurchaseValue.new(@account).price
+ end
+
+ private
+ def add_reconciliation(date:, amount:)
+ @account.entries.create!(
+ date: date, name: "Manual value update", amount: amount, currency: @account.currency,
+ entryable: Valuation.new(kind: "reconciliation")
+ )
+ end
+end