The personal finance app for everyone (by everyone)
Ruby
Count tagged transactions as a property's purchase costs (#5066)
arnaurodondev65ab3e7b0ea1
diff --git a/app/controllers/properties_controller.rb b/app/controllers/properties_controller.rbindex c3d14f5cc6..65fb0ed7e2 100644--- a/app/controllers/properties_controller.rb+++ b/app/controllers/properties_controller.rb@@ -325,7 +325,7 @@ class PropertiesController < ApplicationController:institution_name,:institution_domain,:notes,- accountable_attributes: [ :id, :subtype, :year_built, :area_unit, :area_value ]+ accountable_attributes: [ :id, :subtype, :year_built, :area_unit, :area_value, :cost_tag_id ])enddiff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rbindex c2bc40ccc0..80d224878c 100644--- a/app/helpers/accounts_helper.rb+++ b/app/helpers/accounts_helper.rb@@ -1,7 +1,7 @@module AccountsHelper- def summary_card(title:, &block)+ def summary_card(title:, footer: nil, &block)content = capture(&block)- render "accounts/summary_card", title: title, content: content+ render "accounts/summary_card", title: title, content: content, footer: footerenddef sync_path_for(account)diff --git a/app/models/account.rb b/app/models/account.rbindex e6dafe8ef3..25261b92d9 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -8,6 +8,9 @@ class Account < ApplicationRecordafter_destroy_commit :move_account_statements_to_inbox+ # Property checks its cost tag once it belongs to a saved account; a new+ # one cannot reach the family yet, so the new account checks it.+ validate :cost_tag_in_family, if: -> { new_record? && property? && accountable&.cost_tag_id.present? }validates :name, :balance, :currency, presence: truevalidate :owner_belongs_to_family, if: -> { owner_id.present? && family_id.present? }@@ -1112,6 +1115,12 @@ class Account < ApplicationRecorderrors.add(:owner, :invalid, message: "must belong to the same family as the account")end+ def cost_tag_in_family+ return if family && accountable.cost_tag_in?(family)++ errors.add(:base, :cost_tag_other_family)+ end+# AASM transition callbacks run after the timestamp is set and before the# state is saved, so both land in the event's own save.def clear_disabled_atdiff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rbindex 61d49a1e10..5aad0c4385 100644--- a/app/models/family/data_importer.rb+++ b/app/models/family/data_importer.rb@@ -129,6 +129,7 @@ class Family::DataImporterimport_balances(records["Balance"] || [])import_categories(records["Category"] || [])import_tags(records["Tag"] || [])+ link_property_cost_tags(records["Account"] || [])import_merchants(records["Merchant"] || [])import_provider_merchants(records["ProviderMerchant"] || [])import_recurring_transactions(records["RecurringTransaction"] || [])@@ -155,6 +156,14 @@ class Family::DataImporter{ account_ids: @created_account_ids, entry_ids: @created_entry_ids, summary: compact_summary }end+ # A session imports each chunk through its own importer, so a property can+ # land in an earlier chunk than its cost tag. The session calls this for+ # every chunk after all of them are in, when every tag has its new id.+ def link_property_cost_tags!+ records = parse_ndjson+ Import.transaction { link_property_cost_tags(records["Account"] || []) }+ end+privatedef parse_ndjson@@ -550,6 +559,27 @@ class Family::DataImporterendend+ # A property's cost tag is imported after the accounts, so the link is+ # restored once both have their new ids. A record that carries the key+ # sets the link: no tag, a tag the import does not carry, or a session+ # mapping to a tag since deleted leaves the property unlinked, clearing a+ # link an earlier import made. A record without the key (an older export,+ # or another app's) keeps the property's link.+ def link_property_cost_tags(records)+ records.each do |record|+ data = record["data"] || {}+ accountable = data["accountable"]+ next unless data["accountable_type"] == "Property" && accountable.is_a?(Hash) && accountable.key?("cost_tag_id")++ account = mapped_record(:accounts, data["id"], @family.accounts, record_type: "Account")+ next unless account&.property?++ tag_id = mapped_id(:tags, accountable["cost_tag_id"], record_type: "Account", required: false)+ tag_id = nil unless tag_id && @family.tags.exists?(id: tag_id)+ account.property.update!(cost_tag_id: tag_id) unless account.property.cost_tag_id == tag_id+ end+ end+def import_merchants(records)records.each do |record|data = record["data"]diff --git a/app/models/import_session.rb b/app/models/import_session.rbindex 0daa0abd5a..45e4fb3d1f 100644--- a/app/models/import_session.rb+++ b/app/models/import_session.rb@@ -264,9 +264,14 @@ class ImportSession < ApplicationRecordRails.logger.info("ImportSession publish started import_session_id=#{id}")- imports.ordered_by_sequence.each do |import|+ # Loaded once, so the link pass below reuses each chunk's downloaded file.+ chunks = imports.ordered_by_sequence.to_a+ chunks.each do |import|process_chunk!(import)end+ # A property and its cost tag can arrive in different chunks, so the links+ # are restored again once every tag is in.+ chunks.each { |import| import.link_property_cost_tags!(import_session: self) }update!(status: :complete, summary: aggregate_chunk_summaries, error_details: {})enqueue_family_syncdiff --git a/app/models/property.rb b/app/models/property.rbindex a0c56fff4d..328033ae4d 100644--- a/app/models/property.rb+++ b/app/models/property.rb@@ -15,6 +15,11 @@ class Property < ApplicationRecord}.freezehas_one :address, as: :addressable, dependent: :destroy+ # Transactions with this tag count as the property's purchase costs. The+ # tag must be one of the family's own. A property not yet attached to a+ # saved account cannot reach the family, so Account checks it on create.+ belongs_to :cost_tag, class_name: "Tag", optional: true+ validate :cost_tag_in_family, if: -> { cost_tag_id.present? && will_save_change_to_cost_tag_id? }accepts_nested_attributes_for :address@@ -62,6 +67,12 @@ class Property < ApplicationRecordTrend.new(current: account.balance_money, previous: first_valuation_amount)end+ # Whether the given family owns this property's cost tag. An id that+ # matches no tag (deleted meanwhile, or made up) is not the family's.+ def cost_tag_in?(family)+ cost_tag_id.nil? || family.tags.exists?(id: cost_tag_id)+ end+# Whether the overview should also show the trend in the family currency:# the property is valued in another currency and has a purchase value.def family_currency_trend_applicable?@@ -89,9 +100,72 @@ class Property < ApplicationRecorddef reload(*)remove_instance_variable(:@first_valuation_entry) if defined?(@first_valuation_entry)+ @purchase_costs = nil+ @stored_rates = nilsuperend+ # The transactions carrying the cost tag, in any of the family's accounts+ # that +user+ can see, closed ones included (the costs stay part of the+ # purchase). Excluded, pending, scheduled (future-dated) and split-parent+ # entries and transfers (Transaction::TRANSFER_KINDS, loan payments among+ # them) are left out, as in spending totals.+ def cost_entries_for(user)+ return Entry.none if cost_tag_id.nil?++ tagged = Tagging.where(tag_id: cost_tag_id, taggable_type: "Transaction").select(:taggable_id)++ account.family.entries+ .where(account_id: user.accessible_accounts.historical.select(:id))+ .where(entryable_type: "Transaction", entryable_id: Transaction.where(id: tagged).where.not(kind: Transaction::TRANSFER_KINDS).select(:id))+ .where(excluded: false)+ .excluding_pending+ .excluding_scheduled+ .excluding_split_parents+ end++ # The sum of the linked costs in the family currency: outflows add and+ # refunds subtract. Each transaction is converted into the family currency+ # at the stored rate on its own date (ExchangeRate.rate_sql), the pair+ # account syncs import for every currency in use. Nil when a cost's+ # currency has no stored rate at all. One query, run once per viewer,+ # currency and cost tag, as the overview reads it for several figures.+ def purchase_costs_for(user)+ currency = account.family.currency+ @purchase_costs ||= {}+ key = [ user.id, currency, cost_tag_id ]+ return @purchase_costs[key] if @purchase_costs.key?(key)++ rate = ExchangeRate.rate_sql(from: "entries.currency", to: ":currency", on: "entries.date")+ totals = Entry.sanitize_sql_array([+ "COALESCE(SUM(entries.amount * #{rate}), 0), COUNT(*) FILTER (WHERE (#{rate}) IS NULL)",+ { currency: currency }+ ])+ total, unconverted = cost_entries_for(user).pick(Arel.sql(totals)) || [ 0, 0 ]++ @purchase_costs[key] = unconverted.zero? ? Money.new(total, currency) : nil+ end++ # The purchase price, converted at the rate on its own date, plus the+ # linked costs, in the family currency; nil when a rate is missing.+ def cost_basis_for(user)+ currency = account.family.currency+ purchase = first_valuation_entry+ purchase_value = convert_with_stored_rate(first_valuation_amount, currency, purchase&.date || Date.current)+ costs = purchase_costs_for(user)+ return nil if purchase_value.nil? || costs.nil?++ purchase_value + costs+ end++ # The current value, at today's rate, against the cost basis, in the+ # family currency; nil when a rate is missing.+ def cost_adjusted_trend_for(user)+ basis = cost_basis_for(user)+ current = convert_with_stored_rate(account.balance_money, account.family.currency, Date.current)+ Trend.new(current: current, previous: basis) if basis && current+ end+def balance_display_name"market value"end@@ -168,6 +242,13 @@ class Property < ApplicationRecordendprivate+ def cost_tag_in_family+ family = account&.family+ return if family.nil? || cost_tag_in?(family)++ errors.add(:cost_tag, :other_family)+ end+# Read up to three times per overview render (the card check, the trend# and its purchase value), so it is looked up once.def first_valuation_entry@@ -183,9 +264,17 @@ class Property < ApplicationRecorddef convert_with_stored_rate(money, to_currency, date)return money if money.currency.iso_code == to_currency- rate = ExchangeRate.find_stored_rate(from: money.currency.iso_code, to: to_currency, date: date)+ rate = stored_rate(money.currency.iso_code, to_currency, date)return nil unless ratemoney.exchange_to(to_currency, custom_rate: rate.rate)end++ def stored_rate(from, to, date)+ @stored_rates ||= {}+ key = [ from, to, date ]+ return @stored_rates[key] if @stored_rates.key?(key)++ @stored_rates[key] = ExchangeRate.find_stored_rate(from: from, to: to, date: date)+ endenddiff --git a/app/models/sure_import.rb b/app/models/sure_import.rbindex a3038e7470..723fe0ff77 100644--- a/app/models/sure_import.rb+++ b/app/models/sure_import.rb@@ -165,6 +165,16 @@ class SureImport < Importraiseend+ def link_property_cost_tags!(import_session:)+ # Every exported property carries the key, so a chunk without it has no+ # link. JSON can only spell the key differently through a \u escape, so a+ # chunk with one is parsed and the linker checks the decoded key.+ blob = ndjson_blob_string+ return unless blob.include?("cost_tag_id") || blob.include?("\\u")++ Family::DataImporter.new(family, blob, import_session: import_session, import: self).link_property_cost_tags!+ end+def publish_laterraise MaxRowCountExceededError if row_count_exceeded?diff --git a/app/models/tag.rb b/app/models/tag.rbindex d05d9fce9a..c42ca89e3e 100644--- a/app/models/tag.rb+++ b/app/models/tag.rb@@ -81,6 +81,8 @@ class Tag < ApplicationRecord# A loaded taggings association still lists the moved rows, and# destroy! would delete them by id.taggings.reset+ # Properties counting this tag's transactions as costs follow them.+ Property.where(cost_tag_id: id).update_all cost_tag_id: replacement.idenddestroy!diff --git a/app/views/accounts/_summary_card.html.erb b/app/views/accounts/_summary_card.html.erbindex b711c1cd90..579d6723f3 100644--- a/app/views/accounts/_summary_card.html.erb+++ b/app/views/accounts/_summary_card.html.erb@@ -1,8 +1,10 @@-<%# locals: (title:, content:) %>+<%# locals: (title:, content:, footer: nil) %><div class="rounded-xl bg-container shadow-xs border border-alpha-black-25 p-4"><h4 class="text-secondary text-sm"><%= title %></h4><p class="text-xl font-medium text-primary privacy-sensitive"><%= content %></p>+ <%# Outside the privacy-sensitive value so a link here stays clickable in privacy mode. %>+ <%= footer %></div>diff --git a/app/views/properties/_currency_trend_card.html.erb b/app/views/properties/_currency_trend_card.html.erbnew file mode 100644index 0000000000..1af919e5b8--- /dev/null+++ b/app/views/properties/_currency_trend_card.html.erb@@ -0,0 +1,13 @@+<%# locals: (title:, trend:) %>+<%# A trend in the family currency, or a note when a stored rate is missing. %>++<%= summary_card title: title do %>+ <% if trend %>+ <span class="flex items-center gap-1" style="color: <%= trend.color %>">+ <span><%= trend.value %></span>+ <span class="text-base font-normal">(<%= trend.percent_formatted %>)</span>+ </span>+ <% else %>+ <span class="text-sm font-normal text-secondary"><%= t("properties.tabs.overview.rate_unavailable") %></span>+ <% end %>+<% end %>diff --git a/app/views/properties/_overview_fields.html.erb b/app/views/properties/_overview_fields.html.erbindex 325f272ec0..9df237fcbc 100644--- a/app/views/properties/_overview_fields.html.erb+++ b/app/views/properties/_overview_fields.html.erb@@ -30,6 +30,11 @@[[t(".square_feet"), "sqft"], [t(".square_meters"), "sqm"]],{ label: t(".area_unit_label") } %></div>++ <%= property_form.collection_select :cost_tag_id,+ Current.family.tags.alphabetically, :id, :name,+ { include_blank: t(".cost_tag_prompt"), label: t(".cost_tag_label") } %>+ <p class="text-xs text-secondary"><%= t(".cost_tag_hint") %></p><% end %><%= form.text_area :notes,diff --git a/app/views/properties/tabs/_overview.html.erb b/app/views/properties/tabs/_overview.html.erbindex 4df1161d0b..30fd35ba7c 100644--- a/app/views/properties/tabs/_overview.html.erb+++ b/app/views/properties/tabs/_overview.html.erb@@ -21,16 +21,33 @@<% if account.property.family_currency_trend_applicable? %><div data-testid="family-currency-trend">- <%= summary_card title: t(".trend_in_currency", currency: account.family.currency) do %>- <% if (family_trend = account.property.family_currency_trend) %>- <span class="flex items-center gap-1" style="color: <%= family_trend.color %>">- <span><%= family_trend.value %></span>- <span class="text-base font-normal">(<%= family_trend.percent_formatted %>)</span>- </span>- <% else %>- <span class="text-sm font-normal text-secondary"><%= t(".rate_unavailable") %></span>- <% end %>+ <%= render "properties/currency_trend_card",+ title: t(".trend_in_currency", currency: account.family.currency),+ trend: account.property.family_currency_trend %>+ </div>+ <% end %>++ <% if (cost_tag = account.property.cost_tag) %>+ <%# The costs are summed in the family currency, the currency stored rates convert into. %>+ <% foreign = account.currency != account.family.currency %>+ <div class="contents" data-testid="purchase-costs">+ <% costs = account.property.purchase_costs_for(Current.user) %>+ <% cost_link = link_to t(".cost_transactions", count: account.property.cost_entries_for(Current.user).count, tag: cost_tag.name),+ transactions_path(q: { tags: [ cost_tag.name ], types: %w[expense income], status: %w[confirmed], active_accounts_only: false }),+ class: "block text-sm text-secondary hover:underline",+ data: { turbo_frame: "_top" } %>+ <%= summary_card title: t(foreign ? ".purchase_costs_in_currency" : ".purchase_costs", currency: account.family.currency), footer: cost_link do %>+ <%= costs ? format_money(costs) : t(".rate_unavailable") %><% end %>++ <%= summary_card title: t(foreign ? ".cost_basis_in_currency" : ".cost_basis", currency: account.family.currency) do %>+ <% cost_basis = account.property.cost_basis_for(Current.user) %>+ <%= cost_basis ? format_money(cost_basis) : t(".rate_unavailable") %>+ <% end %>++ <%= render "properties/currency_trend_card",+ title: t(foreign ? ".gain_after_costs_in_currency" : ".gain_after_costs", currency: account.family.currency),+ trend: account.property.cost_adjusted_trend_for(Current.user) %></div><% end %>diff --git a/config/locales/models/account/en.yml b/config/locales/models/account/en.ymlindex 7a6db6d23d..20c9d29e5c 100644--- a/config/locales/models/account/en.yml+++ b/config/locales/models/account/en.yml@@ -39,6 +39,8 @@ en:logo:invalid_content_type: must be a PNG, JPEG, GIF, WebP or ICO imagetoo_large: must be smaller than %{max_size} MB+ base:+ cost_tag_other_family: The cost tag must be one of your own tagsmodels:account: Accountaccount/credit: Credit Carddiff --git a/config/locales/models/property/en.yml b/config/locales/models/property/en.ymlnew file mode 100644index 0000000000..98a0933824--- /dev/null+++ b/config/locales/models/property/en.yml@@ -0,0 +1,12 @@+---+en:+ activerecord:+ attributes:+ property:+ cost_tag: Cost tag+ errors:+ models:+ property:+ attributes:+ cost_tag:+ other_family: must be one of your own tagsdiff --git a/config/locales/views/properties/en.yml b/config/locales/views/properties/en.ymlindex 8969daa8df..9e9739c84f 100644--- a/config/locales/views/properties/en.yml+++ b/config/locales/views/properties/en.yml@@ -93,6 +93,9 @@ en:square_feet: "Square Feet"square_meters: "Square Meters"area_unit_label: "Area Unit"+ cost_tag_label: "Cost tag (optional)"+ cost_tag_prompt: "None"+ cost_tag_hint: "Transactions with this tag, such as notary fees and taxes, count towards the property's cost basis."overview:living_area: Living Areamarket_value: Market Value@@ -108,6 +111,15 @@ en:trend: Trendtrend_in_currency: "Trend in %{currency}"rate_unavailable: "Exchange rate unavailable"+ purchase_costs: Purchase costs+ purchase_costs_in_currency: "Purchase costs in %{currency}"+ cost_transactions:+ one: "1 transaction tagged %{tag}"+ other: "%{count} transactions tagged %{tag}"+ cost_basis: Cost basis+ cost_basis_in_currency: "Cost basis in %{currency}"+ gain_after_costs: Gain after costs+ gain_after_costs_in_currency: "Gain after costs in %{currency}"unknown: Unknownyear_built: Year Builtedit_account_details: "Edit account details"diff --git a/db/migrate/20261117120000_add_cost_tag_to_properties.rb b/db/migrate/20261117120000_add_cost_tag_to_properties.rbnew file mode 100644index 0000000000..13507d71f8--- /dev/null+++ b/db/migrate/20261117120000_add_cost_tag_to_properties.rb@@ -0,0 +1,8 @@+class AddCostTagToProperties < ActiveRecord::Migration[8.1]+ def change+ # The tag that marks a property's purchase costs (notary fees, taxes,+ # registration). Deleting the tag clears the link, not the property.+ add_reference :properties, :cost_tag, type: :uuid, null: true, index: true,+ foreign_key: { to_table: :tags, on_delete: :nullify }+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 4e666ea235..d6fd19e89e 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -1992,12 +1992,14 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_21_110000) dot.string "avm_external_id"t.date "avm_last_synced_on"t.string "avm_provider"+ t.uuid "cost_tag_id"t.datetime "created_at", null: falset.jsonb "locked_attributes", default: {}t.string "subtype"t.datetime "updated_at", null: falset.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.index ["cost_tag_id"], name: "index_properties_on_cost_tag_id"t.check_constraint "avm_provider IS NULL OR (avm_provider::text = ANY (ARRAY['rentcast'::character varying::text, 'realie'::character varying::text, 'chimnie'::character varying::text, 'terrascoutx'::character varying::text]))", name: "properties_avm_provider_check"end@@ -3294,6 +3296,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_21_110000) doadd_foreign_key "plaid_accounts", "plaid_items"add_foreign_key "plaid_items", "families"add_foreign_key "plaid_items", "users", column: "owner_id", on_delete: :nullify+ add_foreign_key "properties", "tags", column: "cost_tag_id", on_delete: :nullifyadd_foreign_key "push_deliveries", "insights"add_foreign_key "push_subscriptions", "users"add_foreign_key "questrade_accounts", "questrade_items"diff --git a/test/controllers/properties_controller_test.rb b/test/controllers/properties_controller_test.rbindex 1445a201fa..1e8959452d 100644--- a/test/controllers/properties_controller_test.rb+++ b/test/controllers/properties_controller_test.rb@@ -1121,6 +1121,155 @@ class PropertiesControllerTest < ActionDispatch::IntegrationTestassert_select "[data-testid='family-currency-trend']", text: /€/, count: 0end+ test "updates the property's cost tag" do+ tag = @account.family.tags.create!(name: "Land costs")++ patch property_path(@account), params: {+ account: { accountable_attributes: { id: @account.accountable.id, cost_tag_id: tag.id } }+ }++ assert_response :success+ assert_equal tag.id, @account.property.reload.cost_tag_id+ end++ test "rejects a cost tag from another family" do+ other_tag = families(:empty).tags.create!(name: "Not ours")++ patch property_path(@account), params: {+ account: { accountable_attributes: { id: @account.accountable.id, cost_tag_id: other_tag.id } }+ }++ assert_response :unprocessable_entity+ assert_nil @account.property.reload.cost_tag_id+ end++ test "rejects a cost tag that no longer exists" do+ tag = @account.family.tags.create!(name: "Land costs")+ tag.destroy!++ patch property_path(@account), params: {+ account: { accountable_attributes: { id: @account.accountable.id, cost_tag_id: tag.id } }+ }++ assert_response :unprocessable_entity+ assert_nil @account.property.reload.cost_tag_id+ end++ test "edit form offers the family's tags as the cost tag" do+ get edit_property_path(@account)++ assert_response :success+ assert_select "input[name='account[accountable_attributes][cost_tag_id]']"+ assert_select "[role='option']", text: tags(:one).name+ end++ test "overview shows the purchase costs, cost basis and gain after costs" do+ tag = cost_tagged_property+ create_cost(accounts(:depository), 8_000, tag)+ create_cost(accounts(:credit_card), 2_000, tag)++ get account_path(@account, tab: "overview")++ assert_response :success+ assert_select "[data-testid='purchase-costs']" do+ assert_select "h4", text: "Purchase costs"+ assert_select "*", text: /\$10,000/+ assert_select "a[href*='tags']", text: "2 transactions tagged Land costs"+ # Costs in closed accounts count too, so the list it opens includes them.+ assert_select "a[href*='active_accounts_only%5D=false']"+ # Outside the blurred value, so privacy mode leaves the link clickable.+ assert_select ".privacy-sensitive a", count: 0+ assert_select ".privacy-sensitive", text: /\$10,000/+ assert_select "*", text: /\$510,000/+ assert_select "span", text: /\$40,000/+ assert_select "span", text: "(7.8%)"+ end+ end++ test "the cost link leaves out transfers, pending transactions and accounts the viewer can't see" do+ tag = cost_tagged_property+ create_cost(accounts(:depository), 8_000, tag)+ create_cost(accounts(:credit_card), 2_000, tag)+ # A tagged transfer is not a cost.+ accounts(:depository).entries.create!(+ date: 1.year.ago.to_date, name: "To savings", amount: 5_000, currency: "USD",+ entryable: Transaction.new(tags: [ tag ], kind: "funds_movement")+ )+ # Pending at the bank, so not counted yet.+ accounts(:depository).entries.create!(+ date: 1.year.ago.to_date, name: "Pending deposit", amount: 1_000, currency: "USD",+ entryable: Transaction.new(tags: [ tag ], extra: { "simplefin" => { "pending" => true } })+ )+ # Not shared with the member.+ create_cost(accounts(:investment), 3_000, tag)+ AccountShare.create!(account: @account, user: users(:family_member), permission: "read_only")+ sign_in users(:family_member)++ get account_path(@account, tab: "overview")++ assert_response :success+ assert_select "[data-testid='purchase-costs']" do+ assert_select "*", text: /\$10,000/+ assert_select "a[href*='tags']", text: "2 transactions tagged Land costs"+ end++ # The list the link opens leaves the transfer and the pending one out too.+ get css_select("[data-testid='purchase-costs'] a[href*='tags']").first["href"]+ assert_response :success+ assert_includes response.body, "Notary"+ assert_not_includes response.body, "To savings"+ assert_not_includes response.body, "Pending deposit"+ end++ test "overview says the rate is unavailable for a cost without a stored rate" do+ tag = cost_tagged_property+ eur_account = @account.family.accounts.create!(name: "Euro bank", balance: 0, currency: "EUR", owner: @user, accountable: Depository.new)+ create_cost(eur_account, 1_000, tag, currency: "EUR")+ ExchangeRate.stubs(:provider).returns(nil)++ get account_path(@account, tab: "overview")++ assert_response :success+ assert_select "[data-testid='purchase-costs']", text: /Exchange rate unavailable/+ assert_select "[data-testid='purchase-costs'] h4", text: "Gain after costs"+ end++ test "overview shows the costs of a foreign-currency property in the family currency" do+ purchase_date = 1.year.ago.to_date+ tag = cost_tagged_property+ @account.family.update!(currency: "EUR")+ eur_account = @account.family.accounts.create!(name: "Euro bank", balance: 0, currency: "EUR", owner: @user, accountable: Depository.new)+ pyg_account = @account.family.accounts.create!(name: "Guarani bank", balance: 0, currency: "PYG", owner: @user, accountable: Depository.new)+ create_cost(eur_account, 9_000, tag, currency: "EUR")+ create_cost(pyg_account, 8_000_000, tag, currency: "PYG")+ # The pairs sync stores: each account's currency into the family's, and the inverse.+ [ [ "USD", purchase_date, 1.0 ], [ "USD", Date.current, 0.9 ], [ "PYG", purchase_date, 0.000125 ] ].each do |currency, date, rate|+ ExchangeRate.create!(from_currency: currency, to_currency: "EUR", date: date, rate: rate)+ ExchangeRate.create!(from_currency: "EUR", to_currency: currency, date: date, rate: 1 / rate.to_d)+ end+ ExchangeRate.stubs(:provider).returns(nil)++ get account_path(@account, tab: "overview")++ assert_response :success+ assert_select "[data-testid='purchase-costs']" do+ assert_select "h4", text: "Purchase costs in EUR"+ assert_select "h4", text: "Cost basis in EUR"+ assert_select "h4", text: "Gain after costs in EUR"+ assert_select "*", text: /€10[.,]000/+ assert_select "*", text: /€510[.,]000/+ assert_select "span", text: /-€15[.,]000/+ assert_select "*", text: /Exchange rate unavailable/, count: 0+ end+ end++ test "overview has no purchase costs without a cost tag" do+ get account_path(@account, tab: "overview")++ assert_response :success+ assert_select "[data-testid='purchase-costs']", count: 0+ end+test "overview has no family-currency trend when the property is in the family currency" doget account_path(@account, tab: "overview")@@ -1129,6 +1278,25 @@ class PropertiesControllerTest < ActionDispatch::IntegrationTestendprivate+ def cost_tagged_property+ tag = @account.family.tags.create!(name: "Land costs")+ @account.property.update!(cost_tag: tag)+ @account.entries.valuations.destroy_all+ @account.entries.create!(+ date: 1.year.ago.to_date, name: "Original purchase price", amount: 500_000, currency: "USD",+ entryable: Valuation.new(kind: "opening_anchor")+ )+ @account.update!(balance: 550_000)+ tag+ end++ def create_cost(account, amount, tag, currency: "USD")+ account.entries.create!(+ date: 1.year.ago.to_date, name: "Notary", amount: amount, currency: currency,+ entryable: Transaction.new(tags: [ tag ])+ )+ end+def foreign_property_with_value(purchase_date:, purchase_amount: 100_000)@account.family.update!(currency: "EUR")@account.entries.valuations.destroy_alldiff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rbindex 619cdf6fc9..778d75c3ee 100644--- a/test/models/family/data_importer_test.rb+++ b/test/models/family/data_importer_test.rb@@ -778,6 +778,88 @@ class Family::DataImporterTest < ActiveSupport::TestCaseassert_equal Tag::COLORS.first, tag.colorend+ test "round trips a property's cost tag through full export" do+ source_family = Family.create!(name: "Source Cost Tag Family", currency: "USD", locale: "en", date_format: "%Y-%m-%d")+ tag = source_family.tags.create!(name: "Round Trip Land Costs")+ source_family.accounts.create!(name: "Round Trip Plot", balance: 30_000, currency: "USD", accountable: Property.new(cost_tag: tag))++ ndjson = nil+ Zip::File.open_buffer(Family::DataExporter.new(source_family).generate_export) do |zip|+ ndjson = zip.read("all.ndjson")+ end++ Family::DataImporter.new(@family, ndjson).import!++ imported_tag = @family.tags.find_by!(name: "Round Trip Land Costs")+ assert_not_equal tag.id, imported_tag.id+ assert_equal imported_tag.id, @family.accounts.find_by!(name: "Round Trip Plot").property.cost_tag_id+ end++ test "a property whose cost tag is not in the import is left unlinked" do+ ndjson = build_ndjson([+ { type: "Account", data: { id: "old-plot", name: "Orphan Plot", balance: "100", currency: "USD",+ accountable_type: "Property", accountable: { cost_tag_id: "missing-tag" } } }+ ])++ Family::DataImporter.new(@family, ndjson).import!++ assert_nil @family.accounts.find_by!(name: "Orphan Plot").property.cost_tag_id+ end++ test "a session mapping to a since-deleted cost tag leaves the property unlinked" do+ session = @family.import_sessions.create!(expected_chunks: 1)+ tag = @family.tags.create!(name: "Gone Land Costs")+ session.source_mappings.create!(family: @family, source_type: "Tag", source_id: "tag-gone", target: tag)+ tag.delete++ ndjson = build_ndjson([+ { type: "Account", data: { id: "old-plot", name: "Replayed Plot", balance: "100", currency: "USD",+ accountable_type: "Property", accountable: { cost_tag_id: "tag-gone" } } }+ ])++ Family::DataImporter.new(@family, ndjson, import_session: session).import!++ assert_nil @family.accounts.find_by!(name: "Replayed Plot").property.cost_tag_id+ end++ test "a replayed import clears a cost tag link the file no longer has" do+ session = @family.import_sessions.create!(expected_chunks: 1)+ tag = @family.tags.create!(name: "Replayed Land Costs")+ session.source_mappings.create!(family: @family, source_type: "Tag", source_id: "tag-1", target: tag)+ plot = { type: "Account", data: { id: "old-plot", name: "Relinked Plot", balance: "100", currency: "USD",+ accountable_type: "Property", accountable: { cost_tag_id: "tag-1" } } }++ Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!+ property = @family.accounts.find_by!(name: "Relinked Plot").property+ assert_equal tag.id, property.cost_tag_id++ plot[:data][:accountable] = { cost_tag_id: "tag-unknown" }+ Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!+ assert_nil property.reload.cost_tag_id++ plot[:data][:accountable] = { cost_tag_id: "tag-1" }+ Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!+ assert_equal tag.id, property.reload.cost_tag_id++ plot[:data][:accountable] = { cost_tag_id: nil }+ Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!+ assert_nil property.reload.cost_tag_id+ end++ test "an import without the cost tag key keeps the property's link" do+ session = @family.import_sessions.create!(expected_chunks: 1)+ tag = @family.tags.create!(name: "Kept Land Costs")+ session.source_mappings.create!(family: @family, source_type: "Tag", source_id: "tag-1", target: tag)+ plot = { type: "Account", data: { id: "old-plot", name: "Kept Plot", balance: "100", currency: "USD",+ accountable_type: "Property", accountable: { cost_tag_id: "tag-1" } } }+ Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!++ plot[:data][:accountable] = {}+ Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!++ assert_equal tag.id, @family.accounts.find_by!(name: "Kept Plot").property.cost_tag_id+ end+test "imports merchants" dondjson = build_ndjson([{diff --git a/test/models/import_session_test.rb b/test/models/import_session_test.rbindex af8f1dfaf5..463580e535 100644--- a/test/models/import_session_test.rb+++ b/test/models/import_session_test.rb@@ -58,6 +58,58 @@ class ImportSessionTest < ActiveSupport::TestCaseassert_source_mapping session, "Transaction", "txn-1", transactionend+ test "links a property to its cost tag when the tag arrives in a later chunk" do+ session = @family.import_sessions.create!(expected_chunks: 2)+ session.attach_chunk!(+ sequence: 1,+ client_chunk_id: "property",+ content: build_ndjson([+ { type: "Account", data: { id: "home-1", name: "Session Home", balance: "300000", currency: "USD",+ accountable_type: "Property", accountable: { cost_tag_id: "tag-costs" } } }+ ]),+ filename: "property.ndjson",+ content_type: "application/x-ndjson"+ )+ session.attach_chunk!(+ sequence: 2,+ client_chunk_id: "tags",+ content: build_ndjson([ { type: "Tag", data: { id: "tag-costs", name: "Home costs", color: "#407706" } } ]),+ filename: "tags.ndjson",+ content_type: "application/x-ndjson"+ )++ session.publish++ assert session.reload.complete?+ tag = @family.tags.find_by!(name: "Home costs")+ assert_equal tag.id, @family.accounts.find_by!(name: "Session Home").property.cost_tag_id+ end++ test "links a cost tag whose key the property chunk spells with a JSON escape" do+ session = @family.import_sessions.create!(expected_chunks: 2)+ property = { type: "Account", data: { id: "home-1", name: "Escaped Home", balance: "300000", currency: "USD",+ accountable_type: "Property", accountable: { cost_tag_id: "tag-costs" } } }+ content = build_ndjson([ property ]).sub('"cost_tag_id"', '"cost\\u005ftag_id"')+ assert_includes content, "cost\\u005ftag_id"+ assert_equal "tag-costs", JSON.parse(content).dig("data", "accountable", "cost_tag_id")++ session.attach_chunk!(sequence: 1, client_chunk_id: "property", content: content,+ filename: "property.ndjson", content_type: "application/x-ndjson")+ session.attach_chunk!(+ sequence: 2,+ client_chunk_id: "tags",+ content: build_ndjson([ { type: "Tag", data: { id: "tag-costs", name: "Home costs", color: "#407706" } } ]),+ filename: "tags.ndjson",+ content_type: "application/x-ndjson"+ )++ session.publish++ assert session.reload.complete?+ tag = @family.tags.find_by!(name: "Home costs")+ assert_equal tag.id, @family.accounts.find_by!(name: "Escaped Home").property.cost_tag_id+ end+test "publishing session chunks records readback verification for each chunk" dosession = @family.import_sessions.create!(expected_chunks: 2)session.attach_chunk!(diff --git a/test/models/property/cost_tag_test.rb b/test/models/property/cost_tag_test.rbnew file mode 100644index 0000000000..ff4758c2e5--- /dev/null+++ b/test/models/property/cost_tag_test.rb@@ -0,0 +1,282 @@+require "test_helper"++class Property::CostTagTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @admin = users(:family_admin)+ @account = accounts(:property)+ @property = @account.property+ @family = @account.family+ @tag = @family.tags.create!(name: "Land costs")+ @property.update!(cost_tag: @tag)++ @purchase_date = 2.years.ago.to_date+ @account.entries.valuations.destroy_all+ @account.entries.create!(+ date: @purchase_date, name: "Original purchase price", amount: 500_000, currency: "USD",+ entryable: Valuation.new(kind: "opening_anchor")+ )+ @account.update!(balance: 550_000)+ # Saving the tag loaded the account and family; tests change the family's currency.+ @property.reload+ end++ test "sums the tagged transactions in any of the family's accounts into the cost basis" do+ create_transaction(account: accounts(:depository), amount: 8_000, date: @purchase_date, tags: [ @tag ])+ create_transaction(account: accounts(:credit_card), amount: 2_500, date: @purchase_date + 3, tags: [ @tag ])+ # A refund reduces the costs.+ create_transaction(account: accounts(:depository), amount: -500, date: @purchase_date + 30, tags: [ @tag ])+ # Untagged and excluded transactions do not count.+ create_transaction(account: accounts(:depository), amount: 1_000, date: @purchase_date)+ create_transaction(account: accounts(:depository), amount: 9_999, date: @purchase_date, tags: [ @tag ], excluded: true)++ assert_equal Money.new(10_000, "USD"), @property.purchase_costs_for(@admin)+ assert_equal Money.new(510_000, "USD"), @property.cost_basis_for(@admin)++ trend = @property.cost_adjusted_trend_for(@admin)+ assert_equal Money.new(40_000, "USD"), trend.value+ assert_equal 7.8, trend.percent+ # The existing trend against the purchase price is unchanged.+ assert_equal Money.new(50_000, "USD"), @property.trend.value+ end++ test "has no costs without a cost tag" do+ create_transaction(account: accounts(:depository), amount: 8_000, tags: [ @tag ])+ @property.update!(cost_tag: nil)++ assert_equal Money.new(0, "USD"), @property.purchase_costs_for(@admin)+ assert_equal Money.new(500_000, "USD"), @property.cost_basis_for(@admin)+ end++ test "changing the cost tag recomputes the costs" do+ other = @family.tags.create!(name: "Plot costs")+ create_transaction(account: accounts(:depository), amount: 100, date: @purchase_date, tags: [ @tag ])+ create_transaction(account: accounts(:depository), amount: 300, date: @purchase_date, tags: [ other ])++ assert_equal Money.new(100, "USD"), @property.purchase_costs_for(@admin)++ @property.update!(cost_tag: other)++ assert_equal Money.new(300, "USD"), @property.purchase_costs_for(@admin)+ end++ test "converts a cost in another currency at the stored rate on its own date" do+ eur_account = @family.accounts.create!(name: "Euro bank", balance: 0, currency: "EUR", owner: @admin, accountable: Depository.new)+ create_transaction(account: eur_account, amount: 1_000, currency: "EUR", date: @purchase_date, tags: [ @tag ])+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @purchase_date, rate: 1.2)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.current, rate: 1.5)++ assert_equal Money.new(1_200, "USD"), @property.purchase_costs_for(@admin)+ assert_equal Money.new(501_200, "USD"), @property.cost_basis_for(@admin)+ end++ test "costs are unavailable without a stored rate and never fetch one" do+ eur_account = @family.accounts.create!(name: "Euro bank", balance: 0, currency: "EUR", owner: @admin, accountable: Depository.new)+ create_transaction(account: eur_account, amount: 1_000, currency: "EUR", date: @purchase_date, tags: [ @tag ])+ create_transaction(account: accounts(:depository), amount: 8_000, date: @purchase_date, tags: [ @tag ])+ ExchangeRate.expects(:provider).never++ assert_nil @property.purchase_costs_for(@admin)+ assert_nil @property.cost_basis_for(@admin)+ assert_nil @property.cost_adjusted_trend_for(@admin)+ end++ test "only counts the costs in accounts the viewer can see" do+ member = users(:family_member)+ # Shared with the member.+ create_transaction(account: accounts(:depository), amount: 8_000, date: @purchase_date, tags: [ @tag ])+ # Not shared with the member.+ create_transaction(account: accounts(:investment), amount: 3_000, date: @purchase_date, tags: [ @tag ])++ assert_equal Money.new(11_000, "USD"), @property.purchase_costs_for(@admin)+ assert_equal Money.new(8_000, "USD"), @property.purchase_costs_for(member)+ assert_equal 1, @property.cost_entries_for(member).count+ end++ test "a foreign-currency property's costs in other currencies use only the rates sync stores" do+ @family.update!(currency: "EUR")+ eur_account = @family.accounts.create!(name: "Euro bank", balance: 0, currency: "EUR", owner: @admin, accountable: Depository.new)+ pyg_account = @family.accounts.create!(name: "Guarani bank", balance: 0, currency: "PYG", owner: @admin, accountable: Depository.new)+ create_transaction(account: eur_account, amount: 10_000, currency: "EUR", date: @purchase_date, tags: [ @tag ])+ create_transaction(account: pyg_account, amount: 8_000_000, currency: "PYG", date: @purchase_date, tags: [ @tag ])+ create_transaction(account: accounts(:depository), amount: 1_000, currency: "USD", date: @purchase_date, tags: [ @tag ])+ # Sync stores each account's currency into the family currency and the+ # inverse, never a pair between two other currencies (PYG->USD).+ [ [ "USD", @purchase_date, 0.92 ], [ "USD", Date.current, 0.9 ], [ "PYG", @purchase_date, 0.000125 ] ].each do |currency, date, rate|+ ExchangeRate.create!(from_currency: currency, to_currency: "EUR", date: date, rate: rate)+ ExchangeRate.create!(from_currency: "EUR", to_currency: currency, date: date, rate: 1 / rate.to_d)+ end+ ExchangeRate.expects(:provider).never++ # 10,000 EUR, 8,000,000 PYG at 0.000125 and 1,000 USD at 0.92, each on its date.+ assert_equal Money.new(11_920, "EUR"), @property.purchase_costs_for(@admin)+ # 500,000 USD at 0.92 on the purchase date, plus the costs.+ assert_equal Money.new(471_920, "EUR"), @property.cost_basis_for(@admin)++ trend = @property.cost_adjusted_trend_for(@admin)+ # 550,000 USD at today's 0.9.+ assert_equal Money.new(495_000, "EUR"), trend.current+ assert_equal Money.new(471_920, "EUR"), trend.previous+ end++ test "the cost basis is unavailable without a stored rate for the property's currency" do+ @family.update!(currency: "EUR")+ ExchangeRate.create!(from_currency: "GBP", to_currency: "EUR", date: Date.current, rate: 1.2)+ ExchangeRate.expects(:provider).never++ assert_equal Money.new(0, "EUR"), @property.purchase_costs_for(@admin)+ assert_nil @property.cost_basis_for(@admin)+ assert_nil @property.cost_adjusted_trend_for(@admin)+ end++ test "split parents are not counted next to their parts" do+ parent = create_transaction(account: accounts(:depository), amount: 1_000, date: @purchase_date, tags: [ @tag ])+ parent.split!([+ { name: "Notary", amount: 600, tag_ids: [ @tag.id ] },+ { name: "Lunch", amount: 400 }+ ])+ # Counted once through its tagged part, even with the parent's excluded+ # flag cleared.+ parent.update_column(:excluded, false)++ assert_equal Money.new(600, "USD"), @property.purchase_costs_for(@admin)+ assert_equal 1, @property.cost_entries_for(@admin).count+ end++ test "pending transactions are not purchase costs" do+ create_transaction(account: accounts(:depository), amount: 2_000, date: @purchase_date, tags: [ @tag ])+ pending = create_transaction(account: accounts(:depository), amount: 900, date: @purchase_date, tags: [ @tag ])+ pending.entryable.update!(extra: { "simplefin" => { "pending" => true } })++ assert_equal Money.new(2_000, "USD"), @property.purchase_costs_for(@admin)+ end++ test "scheduled transactions are not purchase costs until their date" do+ create_transaction(account: accounts(:depository), amount: 2_000, date: @purchase_date, tags: [ @tag ])+ create_transaction(account: accounts(:depository), amount: 900, date: Date.current + 10, tags: [ @tag ])++ assert_equal Money.new(2_000, "USD"), @property.purchase_costs_for(@admin)+ assert_equal 1, @property.cost_entries_for(@admin).count++ travel_to Date.current + 10 do+ assert_equal Money.new(2_900, "USD"), @property.reload.purchase_costs_for(@admin)+ end+ end++ test "reload recomputes the costs" do+ create_transaction(account: accounts(:depository), amount: 100, date: @purchase_date, tags: [ @tag ])+ assert_equal Money.new(100, "USD"), @property.purchase_costs_for(@admin)++ create_transaction(account: accounts(:depository), amount: 50, date: @purchase_date, tags: [ @tag ])+ assert_equal Money.new(100, "USD"), @property.purchase_costs_for(@admin)++ assert_equal Money.new(150, "USD"), @property.reload.purchase_costs_for(@admin)+ end++ test "costs paid from an account later closed still count" do+ old_bank = @family.accounts.create!(name: "Old bank", balance: 0, currency: "USD", owner: @admin, accountable: Depository.new)+ create_transaction(account: old_bank, amount: 8_000, date: @purchase_date, tags: [ @tag ])++ old_bank.disable!++ assert_equal Money.new(8_000, "USD"), @property.purchase_costs_for(@admin)+ assert_equal 1, @property.cost_entries_for(@admin).count+ end++ test "costs paid from an account being deleted do not count" do+ old_bank = @family.accounts.create!(name: "Old bank", balance: 0, currency: "USD", owner: @admin, accountable: Depository.new)+ create_transaction(account: old_bank, amount: 8_000, date: @purchase_date, tags: [ @tag ])++ old_bank.update!(status: "pending_deletion")++ assert_equal Money.new(0, "USD"), @property.purchase_costs_for(@admin)+ end++ test "tagged transfers and loan payments are not purchase costs" do+ Transaction::TRANSFER_KINDS.each do |kind|+ create_transaction(account: accounts(:depository), amount: 1_500, date: @purchase_date, tags: [ @tag ], kind: kind)+ end+ create_transaction(account: accounts(:depository), amount: 700, date: @purchase_date, tags: [ @tag ])++ assert_equal Money.new(700, "USD"), @property.purchase_costs_for(@admin)+ assert_equal 1, @property.cost_entries_for(@admin).count+ end++ test "costs and their rates take the same few queries however many cost dates, once across the overview's figures" do+ @family.update!(currency: "EUR")+ eur = @family.accounts.create!(name: "EUR", balance: 0, currency: "EUR", owner: @admin, accountable: Depository.new)+ 20.times do |i|+ date = @purchase_date + i+ create_transaction(account: eur, amount: 10, currency: "EUR", date: date, tags: [ @tag ])+ create_transaction(account: accounts(:depository), amount: 10, currency: "USD", date: date, tags: [ @tag ])+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: date, rate: 0.9)+ end+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.9)+ @property.reload++ rate_queries = 0+ count_rates = ->(*, payload) { rate_queries += 1 if payload[:sql].include?("exchange_rates") && !payload[:cached] }+ ActiveRecord::Base.uncached do+ ActiveSupport::Notifications.subscribed(count_rates, "sql.active_record") do+ 2.times do+ @property.purchase_costs_for(@admin)+ @property.cost_basis_for(@admin)+ @property.cost_adjusted_trend_for(@admin)+ @property.family_currency_trend+ end+ end+ end++ # The costs in one query, and USD->EUR on the purchase date and today.+ assert_equal 3, rate_queries+ assert_in_delta 550_000 * 0.9 - (500_000 * 0.9 + 200 + 180), @property.cost_adjusted_trend_for(@admin).value.amount, 0.01+ end++ test "the cost tag must belong to the property's family" do+ other_tag = families(:empty).tags.create!(name: "Someone else's")++ assert_not @account.update(accountable_attributes: { id: @property.id, cost_tag_id: other_tag.id })+ assert_equal @tag.id, @property.reload.cost_tag_id+ end++ test "a property saved on its own also checks the cost tag" do+ other_tag = families(:empty).tags.create!(name: "Someone else's")++ assert_not @property.update(cost_tag: other_tag)+ assert_includes @property.errors.details[:cost_tag], { error: :other_family }+ assert_equal @tag.id, @property.reload.cost_tag_id+ end++ test "a cost tag id that matches no tag is rejected" do+ missing_id = SecureRandom.uuid++ assert_not @account.update(accountable_attributes: { id: @property.id, cost_tag_id: missing_id })+ assert_not @property.reload.update(cost_tag_id: missing_id)+ assert_equal @tag.id, @property.reload.cost_tag_id+ end++ test "a new property account checks its cost tag" do+ other_tag = families(:empty).tags.create!(name: "Someone else's")+ account = @family.accounts.build(+ name: "Plot", balance: 0, currency: "USD", owner: @admin,+ accountable: Property.new(cost_tag_id: other_tag.id)+ )++ assert_not account.save+ assert_includes account.errors.details[:base], { error: :cost_tag_other_family }++ account.accountable.cost_tag = @tag+ assert account.save+ end++ test "deleting the tag unlinks the property and replacing it moves the link" do+ replacement = @family.tags.create!(name: "Plot costs")++ @tag.replace_and_destroy!(replacement)+ assert_equal replacement.id, @property.reload.cost_tag_id++ replacement.destroy!+ assert_nil @property.reload.cost_tag_id+ end+end