The personal finance app for everyone (by everyone)
Ruby
Let a family tag a security with its own tags (#5294)
jaysbeekay4bdfd6d7e3e8
diff --git a/app/models/security.rb b/app/models/security.rbindex a63dad3e26..6d75ae00f2 100644--- a/app/models/security.rb+++ b/app/models/security.rb@@ -95,6 +95,14 @@ class Security < ApplicationRecordhas_many :trades, dependent: :nullify, class_name: "Trade"has_many :prices, dependent: :destroyhas_many :splits, dependent: :destroy+ # A security row is shared by every family that holds the instrument, but a+ # Tag belongs to one family, so a tagging is reachable only through its+ # owning family's tags. Read one family's with #tags_for and write them with+ # #set_tags_for. There is deliberately no `has_many :tags, through:`: its+ # generated `tags=`, `tag_ids=` and `tags <<` know nothing about families,+ # and would delete other families' taggings or attach a tag the family does+ # not own.+ has_many :taggings, as: :taggable, dependent: :destroyvalidates :ticker, presence: truevalidates :ticker, uniqueness: { scope: :exchange_operating_mic, case_sensitive: false }@@ -132,6 +140,68 @@ class Security < ApplicationRecordkind == "cash"end+ # `family`'s tags on this security, and no other family's.+ def tags_for(family)+ family.tags.where(id: taggings.select(:tag_id))+ end++ # Moves this security's taggings onto `canonical` when the two are merged.+ # A tag `canonical` already carries stays here and goes with this+ # security's destroy!, as the unique index on taggings allows only one.+ def move_taggings_to!(canonical)+ transaction do+ # The same row lock set_tags_for takes, on both securities in a stable+ # order, so a concurrent tag edit on either waits for the move.+ Security.where(id: [ id, canonical.id ]).order(:id).lock.load++ taggings.where(<<~SQL, canonical.id).update_all(taggable_id: canonical.id)+ NOT EXISTS (+ SELECT 1 FROM taggings carried+ WHERE carried.taggable_type = 'Security'+ AND carried.taggable_id = ?+ AND carried.tag_id = taggings.tag_id+ )+ SQL+ taggings.reset+ end+ end++ # Replaces only `family`'s tags on this security.+ #+ # A wholesale replace would delete other families' taggings on the same+ # instrument, because the row is shared. Ids are resolved through+ # `family.tags` rather than `Tag`, so a tag this family does not own is+ # never attached: that would show its name to every family holding the+ # security.+ #+ # Lock order is security (FOR UPDATE), then tags (FOR SHARE), then taggings.+ # `Tag#replace_and_destroy!` takes taggings then the tag, so the two can+ # deadlock on the same security and tag, and PostgreSQL then aborts one of+ # them with a deadlock error. A new writer should take the locks in this+ # order.+ def set_tags_for(family, tag_ids)+ # `with_lock` reloads the row, which an unsaved security does not have.+ raise ArgumentError, "save the security before tagging it" unless persisted?++ mine = family.tags.select(:id)++ # A check-then-insert on a row every family shares. The unique index on+ # taggings refuses a duplicate, so without the lock two concurrent saves+ # of the same tag would fail one of them rather than both succeed. The+ # lock also reloads the record, so no stale association survives.+ with_lock do+ # Read inside the lock and FOR SHARE: the security's row lock does not+ # cover the tags, so without it a tag deleted between this read and the+ # insert below would fail the insert. A concurrent delete of a wanted+ # tag now waits for this write to commit.+ wanted = family.tags.where(id: Array(tag_ids).reject(&:blank?)).lock("FOR SHARE").pluck(:id)++ taggings.where(tag_id: mine).where.not(tag_id: wanted).destroy_all+ already = taggings.where(tag_id: wanted).pluck(:tag_id)+ (wanted - already).each { |id| taggings.create!(tag_id: id) }+ end+ end+# True when this security represents a crypto asset. Today the only signal# is the Binance ISO MIC — when we add a second crypto provider, extend# this check rather than duplicating the test at every call site.diff --git a/app/models/tag.rb b/app/models/tag.rbindex f86ec4bd85..d05d9fce9a 100644--- a/app/models/tag.rb+++ b/app/models/tag.rb@@ -55,6 +55,12 @@ class Tag < ApplicationRecordpersisted? ? name : UNTAGGED_FILTER_VALUEend+ # Read-only: Security#set_tags_for is the one writer, so tagging a security+ # always takes its lock and stays inside the family.+ def securities+ Security.where(id: taggings.where(taggable_type: "Security").select(:taggable_id))+ end+def replace_and_destroy!(replacement)transaction doraise ActiveRecord::RecordInvalid, "Replacement tag cannot be the same as the tag being destroyed" if replacement == selfdiff --git a/lib/tasks/securities.rake b/lib/tasks/securities.rakeindex a0a81b1187..8be0dc1f46 100644--- a/lib/tasks/securities.rake+++ b/lib/tasks/securities.rake@@ -39,6 +39,7 @@ namespace :securities doHolding.where(security_id: security.id).update_all(security_id: canonical.id)Trade.where(security_id: security.id).update_all(security_id: canonical.id)Security::Price.where(security_id: security.id).update_all(security_id: canonical.id)+ security.move_taggings_to!(canonical)# Delete the duplicatesecurity.destroy!@@ -96,6 +97,7 @@ namespace :securities doHolding.where(security_id: duplicates).update_all(security_id: canonical.id)Trade.where(security_id: duplicates).update_all(security_id: canonical.id)Security::Price.where(security_id: duplicates).update_all(security_id: canonical.id)+ duplicates.each { |duplicate| duplicate.move_taggings_to!(canonical) }# Delete the duplicatesduplicates.each(&:destroy!)diff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rbindex 34071f18c7..39417d51b1 100644--- a/test/controllers/api/v1/transactions_controller_test.rb+++ b/test/controllers/api/v1/transactions_controller_test.rb@@ -1270,10 +1270,105 @@ class Api::V1::TransactionsControllerTest < ActionDispatch::IntegrationTestparams: { transaction: { tag_ids: [ "not-a-uuid" ] } },headers: api_headers(@api_key)- assert_not_equal 200, response.status+ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ assert_equal before_ids, @transaction.reload.tag_ids.sort+ end++ test "create with a malformed tag id is refused and creates nothing" do+ assert_no_difference("@account.entries.count") do+ post api_v1_transactions_url,+ params: { transaction: { account_id: @account.id, name: "Tagged", amount: 25.00, date: Date.current,+ currency: "USD", nature: "expense", tag_ids: [ "not-a-uuid" ] } },+ headers: api_headers(@api_key)+ end++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ end++ # Strong parameters drop a scalar where a list is permitted, so a check made+ # after `permit` saw no tags, and the update cleared every tag it held.+ test "update with a scalar tag id leaves the tags unchanged" do+ @transaction.update!(tag_ids: [ @family.tags.first.id ])+ before_ids = @transaction.reload.tag_ids.sort++ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: "not-a-uuid" } },+ headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ assert_equal before_ids, @transaction.reload.tag_ids.sort+ end++ test "update with a tag id that is not a string leaves the tags unchanged" do+ @transaction.update!(tag_ids: [ @family.tags.first.id ])+ before_ids = @transaction.reload.tag_ids.sort++ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: [ { id: @family.tags.first.id } ] } }.to_json,+ headers: api_headers(@api_key).merge("Content-Type" => "application/json")++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ assert_equal before_ids, @transaction.reload.tag_ids.sort+ end++ # `compact_blank` would drop an empty object or `false` before the check,+ # and then `permit` drops the whole list, or the id writer drops `false`:+ # either way the tags were cleared.+ test "update with a blank non-string tag id leaves the tags unchanged" do+ @transaction.update!(tag_ids: [ @family.tags.first.id ])+ before_ids = @transaction.reload.tag_ids.sort++ [ [ @family.tags.first.id, {} ], [ false ] ].each do |tag_ids|+ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: tag_ids } }.to_json,+ headers: api_headers(@api_key).merge("Content-Type" => "application/json")++ assert_response :unprocessable_entity, "tag_ids: #{tag_ids.inspect}"+ assert_equal "validation_failed", JSON.parse(response.body)["error"], "tag_ids: #{tag_ids.inspect}"+ assert_equal before_ids, @transaction.reload.tag_ids.sort, "tag_ids: #{tag_ids.inspect}"+ end+ end++ test "update with an object for its tag ids leaves the tags unchanged" do+ @transaction.update!(tag_ids: [ @family.tags.first.id ])+ before_ids = @transaction.reload.tag_ids.sort++ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: {} } }.to_json,+ headers: api_headers(@api_key).merge("Content-Type" => "application/json")++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]assert_equal before_ids, @transaction.reload.tag_ids.sortend+ test "create with a scalar tag id is refused and creates nothing" do+ assert_no_difference("@account.entries.count") do+ post api_v1_transactions_url,+ params: { transaction: { account_id: @account.id, name: "Tagged", amount: 25.00, date: Date.current,+ currency: "USD", nature: "expense", tag_ids: "not-a-uuid" } },+ headers: api_headers(@api_key)+ end++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ end++ test "update with a blank tag id list still clears the tags" do+ @transaction.update!(tag_ids: [ @family.tags.first.id ])++ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: [ "" ] } },+ headers: api_headers(@api_key)++ assert_response :success+ assert_empty @transaction.reload.tag_ids+ end+test "should clear tags when empty tag_ids explicitly provided in update" do# Set up transaction with existing tags@transaction.tags = [ Tag.first, Tag.second ]diff --git a/test/lib/tasks/securities_deduplicate_test.rb b/test/lib/tasks/securities_deduplicate_test.rbnew file mode 100644index 0000000000..2d57bcd28d--- /dev/null+++ b/test/lib/tasks/securities_deduplicate_test.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++require "test_helper"+require "rake"++RakeTaskTestHelper.load_task("securities:deduplicate", "securities")++class SecuritiesDeduplicateTest < ActiveSupport::TestCase+ setup do+ RakeTaskTestHelper.prepare("securities:deduplicate")+ end++ # A family's tags on a duplicate are moved like its holdings, trades and+ # prices, rather than destroyed with it.+ test "merging a duplicate without a MIC keeps its tags on the canonical security" do+ canonical = securities(:aapl)+ duplicate = Security.create!(ticker: "AAPL", exchange_operating_mic: nil, name: "Apple duplicate")+ duplicate.taggings.create!(tag: tags(:one))++ capture_io { Rake::Task["securities:deduplicate"].invoke }++ assert_not Security.exists?(duplicate.id)+ assert_equal [ tags(:one) ], canonical.tags_for(families(:dylan_family)).to_a+ end+enddiff --git a/test/models/security/tags_test.rb b/test/models/security/tags_test.rbnew file mode 100644index 0000000000..459083b168--- /dev/null+++ b/test/models/security/tags_test.rb@@ -0,0 +1,205 @@+require "test_helper"++# A security row is shared by every family that holds the instrument, while a+# tag belongs to one family. These tests pin that tagging a security stays+# family-scoped: one family's edit never reads, attaches or removes another+# family's tags on the same row.+class Security::TagsTest < ActiveSupport::TestCase+ setup do+ @security = securities(:aapl)+ @family = families(:dylan_family)+ @tag = tags(:one)+ @second_tag = tags(:two)+ @other_family = families(:empty)+ @other_tag = @other_family.tags.create!(name: "Another household's scheme")+ end++ # Merging a duplicate security keeps every family's tags on the canonical+ # row, and leaves a tag the canonical row already has with the duplicate,+ # which is about to be destroyed.+ test "move_taggings_to! moves a duplicate's taggings and skips tags the canonical row has" do+ duplicate = Security.create!(ticker: "AAPL", exchange_operating_mic: nil, name: "Apple duplicate")+ @security.taggings.create!(tag: @tag)+ duplicate.taggings.create!(tag: @tag)+ duplicate.taggings.create!(tag: @second_tag)+ duplicate.taggings.create!(tag: @other_tag)+ duplicate.taggings.load++ assert_no_difference -> { Tagging.count } do+ duplicate.move_taggings_to!(@security)+ end++ assert_equal [ @tag, @second_tag ].map(&:id).sort, @security.tags_for(@family).pluck(:id).sort+ assert_equal [ @other_tag ], @security.tags_for(@other_family).to_a+ assert_equal [ @tag.id ], Tagging.where(taggable: duplicate).pluck(:tag_id)++ assert_difference -> { Tagging.count }, -1 do+ duplicate.destroy!+ end+ assert_equal 3, Tagging.where(taggable: @security).count+ end++ # set_tags_for is the one writer: it takes the security's lock and keeps the+ # edit inside the family. Tag#securities only reads.+ test "a tag lists its securities but cannot attach one" do+ @security.set_tags_for(@family, [ @tag.id ])++ assert_equal [ @security ], @tag.securities.to_a+ assert_not_respond_to @tag, :security_ids=+ assert_not_respond_to @tag.securities, :<<+ end++ test "set_tags_for attaches the family's tag and the tag reaches the security" do+ assert_difference -> { Tagging.where(taggable: @security).count }, 1 do+ @security.set_tags_for(@family, [ @tag.id ])+ end++ assert_equal [ @tag ], @security.tags_for(@family).to_a+ assert_equal [ @security ], @tag.securities.to_a+ end++ # The security is shared, so attaching a tag the family does not own would+ # put that tag's name on an instrument other families hold.+ test "a tag belonging to another family is not attached" do+ assert_no_difference -> { Tagging.where(taggable: @security).count } do+ @security.set_tags_for(@family, [ @other_tag.id ])+ end++ assert_empty all_tags_on(@security)+ end++ # The security row is shared, so a wholesale replace of its taggings+ # would remove the other family's tagging along with this family's.+ test "set_tags_for leaves another family's tags on the security alone" do+ @security.taggings.create!(tag: @other_tag)++ @security.set_tags_for(@family, [ @tag.id ])++ assert_equal [ @other_tag, @tag ].sort_by(&:id), all_tags_on(@security).sort_by(&:id)+ end++ test "an empty selection clears this family's tags but not another family's" do+ @security.taggings.create!(tag: @tag)+ @security.taggings.create!(tag: @other_tag)++ @security.set_tags_for(@family, [ "" ])++ assert_equal [ @other_tag ], all_tags_on(@security).to_a+ end++ test "a tag left out of the selection is removed and the kept one is untouched" do+ kept = @security.taggings.create!(tag: @tag)+ @security.taggings.create!(tag: @second_tag)++ @security.set_tags_for(@family, [ @tag.id ])++ assert_equal [ kept.id ], Tagging.where(taggable: @security).pluck(:id)+ end++ test "re-submitting the same tag keeps the one existing tagging" do+ existing = @security.taggings.create!(tag: @tag)++ @security.set_tags_for(@family, [ @tag.id, @tag.id ])++ assert_equal [ existing.id ], Tagging.where(taggable: @security).pluck(:id)+ end++ # The removal runs through a query rather than the loaded association, so+ # without a reset a caller that had already loaded the tags would still+ # see the removed one.+ test "already loaded associations reflect the write without a reload" do+ @security.taggings.create!(tag: @tag)+ @security.taggings.load++ @security.set_tags_for(@family, [ @second_tag.id ])++ assert_equal [ @second_tag.id ], @security.taggings.map(&:tag_id)+ assert_equal [ @second_tag ], @security.tags_for(@family).to_a+ end++ test "destroying a tag removes its security taggings and keeps the security" do+ @security.taggings.create!(tag: @tag)++ assert_difference -> { Tagging.where(taggable: @security).count }, -1 do+ @tag.destroy!+ end++ assert Security.exists?(@security.id)+ end++ test "destroying a security removes its taggings and keeps the tags" do+ security = Security.create!(ticker: "TAGD", name: "Tagged", exchange_operating_mic: "XNAS")+ security.set_tags_for(@family, [ @tag.id ])++ assert_difference -> { Tagging.where(taggable_type: "Security", taggable_id: security.id).count }, -1 do+ security.destroy!+ end++ assert Tag.exists?(@tag.id)+ end++ # Merging two tags that are both on the same security keeps one tagging:+ # the unique index on taggings would otherwise refuse the move.+ test "merging two tags on the same security leaves one tagging" do+ @security.set_tags_for(@family, [ @tag.id, @second_tag.id ])++ @tag.replace_and_destroy!(@second_tag)++ assert_equal [ @second_tag.id ], Tagging.where(taggable: @security).pluck(:tag_id)+ end++ test "a family's data reset removes its security tags and keeps another family's" do+ @security.set_tags_for(@family, [ @tag.id ])+ @security.set_tags_for(@other_family, [ @other_tag.id ])+ Provider::Registry.stubs(:plaid_provider_for_region).returns(nil)++ Family::FinancialDataReset.new(user: users(:family_admin), dry_run: false, confirmed: true).call++ assert_equal [ @other_tag.id ], Tagging.where(taggable: @security).pluck(:tag_id)+ end++ # The security's row lock does not cover the tags, so the wanted tags are+ # read FOR SHARE: a concurrent delete of one of them then waits for this+ # write instead of failing its insert. A race can't be staged reliably in a+ # test, so this pins the lock itself.+ test "the wanted tags are read under a share lock" do+ statements = []+ subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload|+ statements << payload[:sql]+ end++ @security.set_tags_for(@family, [ @tag.id ])++ assert statements.any? { |sql| sql.include?(%("tags")) && sql.include?("FOR SHARE") },+ "expected the wanted tags to be read FOR SHARE"+ ensure+ ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber+ end++ # There is no family-blind writer to reach for: `tags=`, `tag_ids=` and+ # `tags <<` would each delete or attach taggings across every family that+ # holds the instrument.+ test "the security has no family-blind tag writer" do+ %i[tags tags= tag_ids tag_ids=].each do |method|+ assert_not @security.respond_to?(method), "Security##{method} is back, and it does not know about families"+ end+ end++ test "tags_for reads only the given family's tags" do+ @security.taggings.create!(tag: @tag)+ @security.taggings.create!(tag: @other_tag)++ assert_equal [ @tag ], @security.tags_for(@family).to_a+ assert_equal [ @other_tag ], @security.tags_for(@other_family).to_a+ end++ test "tagging an unsaved security says so instead of failing on the lock" do+ error = assert_raises(ArgumentError) { Security.new(ticker: "NEW").set_tags_for(@family, [ @tag.id ]) }+ assert_match(/save/i, error.message)+ end++ private+ def all_tags_on(security)+ Tag.where(id: security.taggings.select(:tag_id))+ end+end