The personal finance app for everyone (by everyone)
Ruby
Let vehicles set their purchase price and date (#4580)
Rubén Rodríguez09fef115d67d
diff --git a/app/controllers/vehicles_controller.rb b/app/controllers/vehicles_controller.rbindex 487f1439fd..aed444cdae 100644--- a/app/controllers/vehicles_controller.rb+++ b/app/controllers/vehicles_controller.rb@@ -2,6 +2,7 @@ class VehiclesController < ApplicationControllerinclude AccountableResourcepermitted_accountable_attributes(- :id, :make, :model, :year, :mileage_value, :mileage_unit+ :id, :make, :model, :year, :mileage_value, :mileage_unit,+ :initial_balance, :initial_balance_shown, :purchase_date)enddiff --git a/app/javascript/controllers/money_field_controller.js b/app/javascript/controllers/money_field_controller.jsindex 3868e51358..7d425d6882 100644--- a/app/javascript/controllers/money_field_controller.js+++ b/app/javascript/controllers/money_field_controller.js@@ -22,6 +22,7 @@ export default class extends Controller {maxMessage: String,separator: String,separatorCurrency: String,+ currencySource: String,};requestSequence = 0;@@ -135,6 +136,15 @@ export default class extends Controller {this.updateAmount(selectedCurrency);}+ // A field with its currency picker hidden can follow another field's+ // picker in the same form, named by a CSS selector, so its symbol and+ // precision match.+ followCurrencySource(e) {+ if (e.target !== this.#currencySourceElement()) return;++ this.updateAmount(e.target.value);+ }+updateAmount(currency) {const requestId = ++this.requestSequence;new CurrenciesService().get(currency).then((currencyData) => {@@ -277,13 +287,22 @@ export default class extends Controller {// is not the selected currency, so the paste falls back to the unhinted// heuristic instead of settling it with another currency's separator.#pasteSeparator() {- if (this.hasCurrencyTarget && this.currencyTarget.value !== this.separatorCurrencyValue) {+ const picker = this.hasCurrencyTarget+ ? this.currencyTarget+ : this.#currencySourceElement();+ if (picker && picker.value !== this.separatorCurrencyValue) {return undefined;}return this.separatorValue;}+ #currencySourceElement() {+ if (!this.hasCurrencySourceValue) return null;++ return this.form?.querySelector(this.currencySourceValue) ?? null;+ }+// The amount input's step already carries the selected currency's precision,// rendered server-side and refreshed by updateAmount, so it tracks the live// currency selection without a second lookup. BTC's step arrives asdiff --git a/app/models/vehicle.rb b/app/models/vehicle.rbindex 255e11d669..7a9e5ab272 100644--- a/app/models/vehicle.rb+++ b/app/models/vehicle.rb@@ -3,16 +3,36 @@ class Vehicle < ApplicationRecordattribute :mileage_unit, :string, default: "mi"+ # Form inputs for the purchase price and date, stored on the opening anchor.+ attribute :initial_balance, :decimal+ attribute :purchase_date, :date+ # The price the form showed. The account's balance is saved first and can+ # rewrite a same-day opening anchor, so edits are judged against this.+ attribute :initial_balance_shown, :decimal++ validate :purchase_date_is_valid, if: :persisted?+ after_update :update_purchase_anchor, if: -> { purchase_price_edited? || purchase_date_edited? }++ # An unparseable purchase date casts to nil, which reads as unchanged, and+ # the account would then skip validating this record.+ def changed_for_autosave?+ super || invalid_purchase_date?+ end+def mileageMeasurement.new(mileage_value, mileage_unit) if mileage_value.present?end+ # The opening anchor ("Original purchase price") is what the form edits, so+ # it is the purchase price even when a valuation predates it.def purchase_price+ return Money.new(account.opening_anchor_balance, account.currency) if account.has_opening_anchor?+first_valuation_amountenddef trend- Trend.new(current: account.balance_money, previous: first_valuation_amount)+ Trend.new(current: account.balance_money, previous: purchase_price)endclass << self@@ -30,6 +50,84 @@ class Vehicle < ApplicationRecordendprivate+ # The form posts both fields prefilled on every edit, so only a value that+ # differs from what was shown (or, without that, stored) counts as an edit.+ # Both sides are rounded as the money field displays them.+ def purchase_price_edited?+ return false if initial_balance.blank?++ round_to_currency(initial_balance) != round_to_currency(initial_balance_shown || purchase_price.amount)+ end++ def purchase_date_edited?+ purchase_date.present? && purchase_date != account.opening_anchor_date+ end++ def invalid_purchase_date?+ purchase_date.nil? && purchase_date_before_type_cast.present?+ end++ def purchase_date_is_valid+ if invalid_purchase_date?+ errors.add(:purchase_date, :invalid)+ elsif purchase_date_edited? && Account::OpeningBalanceManager.new(account).date_error(purchase_date)+ errors.add(:purchase_date, :must_precede_entries)+ end+ end++ def update_purchase_anchor+ current_balance = account.balance+ anchor_balance = purchase_price_edited? ? initial_balance : unedited_anchor_balance++ result = account.set_opening_anchor_balance(+ balance: anchor_balance,+ date: (purchase_date if purchase_date_edited?)+ )+ raise_purchase_error(result.error) unless result.success?++ # Applied; a later save of this record, such as lock_saved_attributes!,+ # must not apply them again against the anchor they just moved.+ self.initial_balance = self.purchase_date = self.initial_balance_shown = nil++ keep_current_balance(current_balance) if anchor_balance != current_balance+ end++ # Moving only the date keeps the purchase price. A same-day anchor is also+ # today's balance, which the account update may just have rewritten; the+ # price shown is what it held before.+ def unedited_anchor_balance+ return initial_balance_shown if initial_balance_shown && account.opening_anchor_date == Date.current++ purchase_price.amount+ end++ def round_to_currency(amount)+ amount.round(Money::Currency.new(account.currency).default_precision)+ end++ # With no valuation between the anchor and today, the anchor carries+ # forward to today, so a new anchor balance would become the current value+ # too. Pin today's value, as Account.create_and_sync does on create.+ def keep_current_balance(balance)+ anchor_date = account.opening_anchor_date+ return unless anchor_date < Date.current+ return if account.entries.valuations.where(date: (anchor_date + 1)..Date.current).exists?++ result = Account::ReconciliationManager.new(account).reconcile_balance(balance: balance, date: Date.current)+ raise_purchase_error(result.error_message) unless result.success?+ end++ def raise_purchase_error(message)+ errors.add(:base, message)+ raise ActiveRecord::RecordInvalid.new(self)+ end++ # Form inputs for the opening anchor, not vehicle details a provider could+ # overwrite.+ def ignored_enrichable_attributes+ super + %w[initial_balance initial_balance_shown purchase_date]+ end+def first_valuation_amountaccount.entries.valuations.order(:date).first&.amount_money || account.balance_moneyenddiff --git a/app/views/shared/_money_field.html.erb b/app/views/shared/_money_field.html.erbindex 90876257eb..f8f1d9651c 100644--- a/app/views/shared/_money_field.html.erb+++ b/app/views/shared/_money_field.html.erb@@ -18,6 +18,7 @@data-money-field-separator-currency-value="<%= currency.iso_code %>"<% if options[:precision].present? %> data-money-field-precision-value="<%= options[:precision] %>"<% end %><% if options[:step].present? %> data-money-field-step-value="<%= options[:step] %>"<% end %>+ <% if options[:currency_source].present? %> data-money-field-currency-source-value="<%= options[:currency_source] %>" data-action="change@document->money-field#followCurrencySource"<% end %>data-money-field-min-value="<%= amount_min %>"data-money-field-max-value="<%= amount_max %>"data-money-field-invalid-message-value="<%= t(".invalid_amount") %>"diff --git a/app/views/vehicles/_form.html.erb b/app/views/vehicles/_form.html.erbindex 0194b19126..0c148ebf73 100644--- a/app/views/vehicles/_form.html.erb+++ b/app/views/vehicles/_form.html.erb@@ -28,6 +28,24 @@[[t("vehicles.form.mileage_unit_miles"), "mi"], [t("vehicles.form.mileage_unit_kilometers"), "km"]],{ label: t("vehicles.form.mileage_unit") } %></div>++ <% unless account.linked? %>+ <div class="flex items-center gap-2">+ <%= vehicle_form.money_field :initial_balance,+ label: t("vehicles.form.purchase_price"),+ currency_value_override: account.currency,+ currency_source: "select[name='account[currency]']",+ value: vehicle_form.object.initial_balance || (vehicle_form.object.purchase_price.amount if account.persisted?),+ hide_currency: true %>+ <% if account.persisted? %>+ <%= vehicle_form.hidden_field :initial_balance_shown,+ value: vehicle_form.object.initial_balance_shown || vehicle_form.object.purchase_price.amount %>+ <%= vehicle_form.date_field :purchase_date,+ label: t("vehicles.form.purchase_date"),+ value: vehicle_form.object.purchase_date || account.opening_anchor_date %>+ <% end %>+ </div>+ <% end %><% end %></div><% end %>diff --git a/config/locales/models/vehicle/en.yml b/config/locales/models/vehicle/en.ymlnew file mode 100644index 0000000000..95b0b8cab1--- /dev/null+++ b/config/locales/models/vehicle/en.yml@@ -0,0 +1,15 @@+---+en:+ activerecord:+ attributes:+ # How the account form names the vehicle's field in its error messages.+ account/accountable:+ purchase_date: Purchase date+ vehicle:+ purchase_date: Purchase date+ errors:+ models:+ vehicle:+ attributes:+ purchase_date:+ must_precede_entries: must be before the account's oldest entrydiff --git a/config/locales/models/vehicle/es.yml b/config/locales/models/vehicle/es.ymlnew file mode 100644index 0000000000..9bb425110a--- /dev/null+++ b/config/locales/models/vehicle/es.yml@@ -0,0 +1,15 @@+---+es:+ activerecord:+ attributes:+ # How the account form names the vehicle's field in its error messages.+ account/accountable:+ purchase_date: Fecha de compra+ vehicle:+ purchase_date: Fecha de compra+ errors:+ models:+ vehicle:+ attributes:+ purchase_date:+ must_precede_entries: debe ser anterior al movimiento más antiguo de la cuentadiff --git a/config/locales/views/vehicles/en.yml b/config/locales/views/vehicles/en.ymlindex 7bb3fea296..cf81c92415 100644--- a/config/locales/views/vehicles/en.yml+++ b/config/locales/views/vehicles/en.yml@@ -11,6 +11,8 @@ en:mileage_unit: Unitmodel: Modelmodel_placeholder: Camry+ purchase_date: Purchase date+ purchase_price: Purchase priceyear: Yearyear_placeholder: '2023'mileage_unit_kilometers: Kilometersdiff --git a/config/locales/views/vehicles/es.yml b/config/locales/views/vehicles/es.ymlindex 2fabc859ca..a95a1f8c73 100644--- a/config/locales/views/vehicles/es.yml+++ b/config/locales/views/vehicles/es.yml@@ -11,6 +11,8 @@ es:mileage_unit: Unidadmodel: Modelomodel_placeholder: Camry+ purchase_date: Fecha de compra+ purchase_price: Precio de comprayear: Añoyear_placeholder: '2025'new:diff --git a/test/controllers/vehicles_controller_test.rb b/test/controllers/vehicles_controller_test.rbindex d4896230eb..4bc6c46b06 100644--- a/test/controllers/vehicles_controller_test.rb+++ b/test/controllers/vehicles_controller_test.rb@@ -1,7 +1,7 @@require "test_helper"class VehiclesControllerTest < ActionDispatch::IntegrationTest- include AccountableResourceInterfaceTest+ include AccountableResourceInterfaceTest, EntriesTestHelpersetup dosign_in @user = users(:family_admin)@@ -70,7 +70,8 @@ class VehiclesControllerTest < ActionDispatch::IntegrationTestyear: 2021,mileage_value: 20000,mileage_unit: "mi",- purchase_price: 32000+ initial_balance: 32000,+ purchase_date: 3.years.ago.to_date}}}@@ -82,9 +83,309 @@ class VehiclesControllerTest < ActionDispatch::IntegrationTestassert_equal "Updated Lender", @account[:institution_name]assert_equal "updatedlender.example", @account[:institution_domain]assert_equal "Updated lease notes", @account[:notes]+ assert_equal 32000, @account.opening_anchor_balance+ assert_equal 3.years.ago.to_date, @account.opening_anchor_dateassert_redirected_to account_path(@account)assert_equal "Vehicle account updated", flash[:notice]assert_enqueued_with(job: SyncJob)end++ test "creates with a purchase price below the current value" do+ post vehicles_path, params: {+ account: {+ name: "Vehicle",+ balance: 30000,+ currency: "USD",+ opening_balance_date: 1.year.ago.to_date,+ accountable_type: "Vehicle",+ accountable_attributes: { make: "Toyota", initial_balance: 35000 }+ }+ }++ account = Account.order(:created_at).last+ assert_equal 30000, account.balance+ assert_equal 35000, account.opening_anchor_balance+ assert_equal 1.year.ago.to_date, account.opening_anchor_date+ assert_equal 30000, account.valuations.reconciliation.first.entry.amount+ assert_equal Money.new(35000, "USD"), account.vehicle.purchase_price+ assert_empty account.vehicle.locked_attributes.keys & %w[initial_balance purchase_date]+ end++ test "edit form shows the purchase price and date" do+ @account.set_opening_anchor_balance(balance: 21000, date: 2.years.ago.to_date)++ get edit_vehicle_path(@account)++ assert_response :success+ assert_select "input[name='account[accountable_attributes][initial_balance]'][value='21000.00']"+ assert_select "input[name='account[accountable_attributes][purchase_date]'][value='#{2.years.ago.to_date}']"+ assert_select "input[type=hidden][name='account[accountable_attributes][initial_balance_shown]'][value='21000.0']"+ end++ test "updates the purchase price without touching the purchase date" do+ @account.set_opening_anchor_balance(balance: 0, date: 2.years.ago.to_date)++ patch vehicle_path(@account), params: {+ account: {+ accountable_attributes: { id: @account.accountable_id, initial_balance: 21000, purchase_date: "" }+ }+ }++ assert_redirected_to account_path(@account)+ assert_equal 21000, @account.reload.opening_anchor_balance+ assert_equal 2.years.ago.to_date, @account.opening_anchor_date+ end++ test "keeps the current value when only the purchase price changes" do+ @account.set_opening_anchor_balance(balance: 18000, date: 2.years.ago.to_date)++ patch vehicle_path(@account), params: {+ account: {+ accountable_attributes: { id: @account.accountable_id, initial_balance: 25000, purchase_date: 2.years.ago.to_date }+ }+ }++ assert_redirected_to account_path(@account)+ @account.reload+ assert_equal 25000, @account.opening_anchor_balance+ assert_equal 18000, @account.balance+ reconciliation = @account.valuations.reconciliation.first.entry+ assert_equal [ Date.current, 18000 ], [ reconciliation.date, reconciliation.amount ]+ end++ test "a future valuation does not stop the current value being kept" do+ @account.set_opening_anchor_balance(balance: 18000, date: 2.years.ago.to_date)+ create_valuation(account: @account, date: 1.month.from_now.to_date, amount: 15000)++ patch vehicle_path(@account), params: {+ account: {+ accountable_attributes: { id: @account.accountable_id, initial_balance: 25000, purchase_date: 2.years.ago.to_date }+ }+ }++ assert_redirected_to account_path(@account)+ today = @account.reload.entries.valuations.find_by(date: Date.current)+ assert_equal 18000, today&.amount+ end++ test "moving only the purchase date keeps the anchor's balance when a valuation predates it" do+ @account.set_opening_anchor_balance(balance: 21000, date: 1.year.ago.to_date)+ create_valuation(account: @account, date: 2.years.ago.to_date, amount: 22000)++ patch vehicle_path(@account), params: {+ account: {+ accountable_attributes: { id: @account.accountable_id, initial_balance: "21000.00", purchase_date: 3.years.ago.to_date }+ }+ }++ assert_redirected_to account_path(@account)+ assert_equal 21000, @account.reload.opening_anchor_balance+ assert_equal 3.years.ago.to_date, @account.opening_anchor_date+ end++ test "an edit that resubmits the prefilled purchase fields changes nothing" do+ @account.set_opening_anchor_balance(balance: 21000, date: 2.years.ago.to_date)+ clear_enqueued_jobs++ assert_no_difference "Entry.count" do+ patch vehicle_path(@account), params: {+ account: {+ name: "Renamed",+ accountable_attributes: { id: @account.accountable_id, initial_balance: "21000.00", purchase_date: 2.years.ago.to_date }+ }+ }+ end++ assert_redirected_to account_path(@account)+ assert_equal "Renamed", @account.reload.name+ assert_no_enqueued_jobs only: SyncJob+ end++ test "an edit of a vehicle without an opening anchor does not invent one" do+ assert_not @account.has_opening_anchor?++ get edit_vehicle_path(@account)+ assert_select "input[name='account[accountable_attributes][initial_balance]'][value='18000.00']"++ assert_no_difference "Entry.count" do+ patch vehicle_path(@account), params: {+ account: {+ name: "Renamed",+ accountable_attributes: { id: @account.accountable_id, initial_balance: "18000.00", purchase_date: @account.opening_anchor_date }+ }+ }+ end++ assert_redirected_to account_path(@account)+ assert_equal "Renamed", @account.reload.name+ end++ test "moving the purchase date of a vehicle without an anchor keeps its purchase price" do+ create_valuation(account: @account, date: 1.year.ago.to_date, amount: 20000)++ patch vehicle_path(@account), params: {+ account: {+ accountable_attributes: { id: @account.accountable_id, initial_balance: "20000.00", purchase_date: 2.years.ago.to_date }+ }+ }++ assert_redirected_to account_path(@account)+ assert_equal 20000, @account.reload.opening_anchor_balance+ assert_equal 2.years.ago.to_date, @account.opening_anchor_date+ assert_equal Money.new(20000, "USD"), @account.vehicle.purchase_price+ end++ test "an unchanged purchase date is not revalidated against older entries" do+ @account.set_opening_anchor_balance(balance: 21000, date: 1.year.ago.to_date)+ create_valuation(account: @account, date: 2.years.ago.to_date, amount: 22000)++ patch vehicle_path(@account), params: {+ account: {+ name: "Renamed",+ accountable_attributes: { id: @account.accountable_id, purchase_date: 1.year.ago.to_date }+ }+ }++ assert_redirected_to account_path(@account)+ assert_equal "Renamed", @account.reload.name+ end++ test "rejects a purchase date that is not a date" do+ @account.set_opening_anchor_balance(balance: 21000, date: 2.years.ago.to_date)++ patch vehicle_path(@account), params: {+ account: {+ name: "Renamed",+ accountable_attributes: { id: @account.accountable_id, purchase_date: "not-a-date" }+ }+ }++ assert_response :unprocessable_entity+ assert_equal "Honda Accord", @account.reload.name+ assert_equal 2.years.ago.to_date, @account.opening_anchor_date+ end++ test "a balance-only edit keeps the new balance when the anchor is dated today" do+ @account.set_opening_anchor_balance(balance: 18000, date: Date.current)++ patch vehicle_path(@account), params: {+ account: {+ balance: 15000,+ accountable_attributes: {+ id: @account.accountable_id, initial_balance: "18000.00", initial_balance_shown: "18000.00", purchase_date: Date.current+ }+ }+ }++ assert_redirected_to account_path(@account)+ @account.reload+ assert_equal 15000, @account.balance+ assert_equal 15000, @account.opening_anchor_balance+ end++ test "moving a same-day purchase date while changing the balance keeps both" do+ @account.set_opening_anchor_balance(balance: 18000, date: Date.current)++ patch vehicle_path(@account), params: {+ account: {+ balance: 15000,+ accountable_attributes: {+ id: @account.accountable_id, initial_balance: "18000.00", initial_balance_shown: "18000.00", purchase_date: 1.year.ago.to_date+ }+ }+ }++ assert_redirected_to account_path(@account)+ @account.reload+ assert_equal [ 18000, 1.year.ago.to_date ], [ @account.opening_anchor_balance, @account.opening_anchor_date ]+ assert_equal 15000, @account.balance+ reconciliation = @account.valuations.reconciliation.first.entry+ assert_equal [ Date.current, 15000 ], [ reconciliation.date, reconciliation.amount ]+ end++ test "a date-only edit alongside other details keeps the anchor's own balance" do+ @account.set_opening_anchor_balance(balance: 21000, date: 1.year.ago.to_date)+ create_valuation(account: @account, date: 2.years.ago.to_date, amount: 22000)++ patch vehicle_path(@account), params: {+ account: {+ accountable_attributes: {+ id: @account.accountable_id, make: "Honda", initial_balance: "21000.00", initial_balance_shown: "21000.00",+ purchase_date: 3.years.ago.to_date+ }+ }+ }++ assert_redirected_to account_path(@account)+ @account.reload+ assert_equal [ 21000, 3.years.ago.to_date ], [ @account.opening_anchor_balance, @account.opening_anchor_date ]+ end++ test "the purchase price is the opening anchor even when a valuation predates it" do+ @account.set_opening_anchor_balance(balance: 21000, date: 1.year.ago.to_date)+ create_valuation(account: @account, date: 2.years.ago.to_date, amount: 22000)++ get edit_vehicle_path(@account)+ assert_select "input[name='account[accountable_attributes][initial_balance]'][value='21000.00']"++ patch vehicle_path(@account), params: {+ account: {+ accountable_attributes: { id: @account.accountable_id, initial_balance: "25000.00", initial_balance_shown: "21000.00" }+ }+ }++ assert_redirected_to account_path(@account)+ assert_equal Money.new(25000, "USD"), @account.reload.vehicle.purchase_price+ end++ test "a price shown rounded to the currency's precision is not an edit" do+ @account.set_opening_anchor_balance(balance: 21000.1234, date: 2.years.ago.to_date)++ patch vehicle_path(@account), params: {+ account: {+ name: "Renamed",+ accountable_attributes: {+ id: @account.accountable_id, initial_balance: "21000.12", initial_balance_shown: "21000.1234", purchase_date: 2.years.ago.to_date+ }+ }+ }++ assert_redirected_to account_path(@account)+ assert_equal 21000.1234.to_d, @account.reload.opening_anchor_balance+ end++ test "leaves the opening anchor alone when the purchase fields are blank" do+ @account.set_opening_anchor_balance(balance: 21000, date: 2.years.ago.to_date)++ patch vehicle_path(@account), params: {+ account: {+ name: "Renamed",+ accountable_attributes: { id: @account.accountable_id, initial_balance: "", purchase_date: "" }+ }+ }++ assert_redirected_to account_path(@account)+ assert_equal "Renamed", @account.reload.name+ assert_equal 21000, @account.opening_anchor_balance+ assert_equal 2.years.ago.to_date, @account.opening_anchor_date+ end++ test "rejects a purchase date that is not before the oldest entry" do+ @account.set_opening_anchor_balance(balance: 21000, date: 2.years.ago.to_date)+ create_valuation(account: @account, date: 1.year.ago.to_date, amount: 19000)++ patch vehicle_path(@account), params: {+ account: {+ name: "Renamed",+ accountable_attributes: { id: @account.accountable_id, initial_balance: 25000, purchase_date: 6.months.ago.to_date }+ }+ }++ assert_response :unprocessable_entity+ assert_includes response.body, "Purchase date must be before the account's oldest entry"+ assert_equal "Honda Accord", @account.reload.name+ assert_equal 21000, @account.opening_anchor_balance+ assert_equal 2.years.ago.to_date, @account.opening_anchor_date+ endend