The personal finance app for everyone (by everyone)
Ruby
Keep one family's merchant changes off shared provider merchants (#3824)
GFR2a061fc65964
diff --git a/app/controllers/family_merchants_controller.rb b/app/controllers/family_merchants_controller.rbindex b1bcb88115..a5109f358b 100644--- a/app/controllers/family_merchants_controller.rb+++ b/app/controllers/family_merchants_controller.rb@@ -70,17 +70,16 @@ class FamilyMerchantsController < ApplicationControllerdef updateif @merchant.is_a?(ProviderMerchant)- if merchant_params[:name].present? && merchant_params[:name] != @merchant.name- # Name changed — convert ProviderMerchant to FamilyMerchant for this family only+ # A ProviderMerchant is shared by every family whose transactions use it,+ # so changing its name or website converts it to a FamilyMerchant for this+ # family only; editing the shared row would change it for all of them.+ if provider_merchant_customized?@family_merchant = @merchant.convert_to_family_merchant_for(Current.family, merchant_params)respond_to do |format|format.html { redirect_to family_merchants_path, notice: t(".converted_success") }format.turbo_stream { render turbo_stream: turbo_stream.action(:redirect, family_merchants_path) }endelse- # Only website changed — update the ProviderMerchant directly- @merchant.update!(merchant_params.slice(:website_url))- @merchant.generate_logo_url_from_website!respond_to do |format|format.html { redirect_to family_merchants_path, notice: t(".success") }format.turbo_stream { render turbo_stream: turbo_stream.action(:redirect, family_merchants_path) }@@ -164,6 +163,14 @@ class FamilyMerchantsController < ApplicationController@family_merchant = @merchant # For backwards compatibility with viewsend+ def provider_merchant_customized?+ name_changed = merchant_params[:name].present? && merchant_params[:name] != @merchant.name+ website_changed = merchant_params.key?(:website_url) &&+ merchant_params[:website_url].to_s.strip != @merchant.website_url.to_s++ name_changed || website_changed+ end+def merchant_params# Handle both family_merchant and provider_merchant param keyskey = params.key?(:family_merchant) ? :family_merchant : :provider_merchantdiff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rbindex ad08d322f4..1aa6ed4257 100644--- a/app/models/family/data_importer.rb+++ b/app/models/family/data_importer.rb@@ -503,9 +503,15 @@ class Family::DataImporter# ProviderMerchant rows share the :merchants id-mapping namespace with# Merchant, so Transaction/RecurringTransaction merchant_id resolution below- # needs no changes to accept either source. A ProviderMerchant is shared- # across every family on the instance, so an existing match is reused as-is:- # an import never writes to a record it did not create.+ # needs no changes to accept either source.+ #+ # A ProviderMerchant is shared by every family on the instance, and bank syncs+ # find it by provider_merchant_id, which most providers derive from the payee+ # name (e.g. "simplefin_" + MD5 of it). So an import only reuses one that+ # already exists, as-is, and never creates one: otherwise any user could+ # choose the name, logo and website that other families' synced transactions+ # attach to. A merchant the instance does not know yet becomes this family's+ # own FamilyMerchant.def import_provider_merchants(records)records.each do |record|data = record["data"]@@ -519,32 +525,20 @@ class Family::DataImporternextend- merchant = ProviderMerchant.find_by_import_data(data, source)- merchant ||= create_provider_merchant(data, source)- created = merchant.previously_new_record?+ if (merchant = ProviderMerchant.find_by_import_data(data, source))+ increment_summary("ProviderMerchant", :updated)+ else+ merchant, created = FamilyMerchant.find_or_create_with_name(+ @family,+ data["name"],+ logo_url: data["logo_url"],+ website_url: data["website_url"]+ )+ increment_summary("ProviderMerchant", created ? :created : :updated)+ endmap_source!(:merchants, old_id, merchant)- increment_summary("ProviderMerchant", created ? :created : :updated)- end- end-- # ProviderMerchant does not support color, so a color in the file is not read.- # The savepoint keeps a lost race from aborting the surrounding import transaction.- # A race usually surfaces as the name-uniqueness validation (RecordInvalid) rather- # than the index (RecordNotUnique); either way, reuse the winner if it exists and- # let anything else propagate.- def create_provider_merchant(data, source)- ProviderMerchant.transaction(requires_new: true) do- ProviderMerchant.create!(- name: data["name"],- source: source,- provider_merchant_id: data["provider_merchant_id"].presence,- logo_url: data["logo_url"],- website_url: data["website_url"]- )end- rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid- ProviderMerchant.find_by_import_data(data, source) || raiseenddef import_recurring_transactions(records)diff --git a/app/models/family_merchant.rb b/app/models/family_merchant.rbindex d45947aca6..11462d60de 100644--- a/app/models/family_merchant.rb+++ b/app/models/family_merchant.rb@@ -9,6 +9,26 @@ class FamilyMerchant < Merchantvalidates :color, presence: true, format: { with: /\A#[0-9A-Fa-f]{6}\z/ }validates :name, uniqueness: { scope: :family }+ # Reuses a family's existing merchant of this name instead of raising on the+ # uniqueness validation, and survives a concurrent create for the same name+ # (e.g. two imports, or an import racing a manual edit) landing on the+ # database's unique index first. Returns [merchant, created?].+ def self.find_or_create_with_name(family, name, **attributes)+ existing = family.merchants.find_by(name: name)+ return [ existing, false ] if existing++ begin+ # requires_new: true opens a savepoint, so a RecordNotUnique here rolls+ # back only the failed insert. Without it, Postgres aborts the whole+ # enclosing transaction and the rescue's find_by! below would also fail.+ merchant = transaction(requires_new: true) { family.merchants.create!(attributes.merge(name: name)) }+ [ merchant, true ]+ rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid => e+ raise if e.is_a?(ActiveRecord::RecordInvalid) && !e.record.errors.of_kind?(:name, :taken)+ [ family.merchants.find_by!(name: name), false ]+ end+ end+privatedef set_default_colorself.color = COLORS.sample unless valid_hex_color?diff --git a/app/models/provider_merchant.rb b/app/models/provider_merchant.rbindex f88e7bdfb9..9976bca6e4 100644--- a/app/models/provider_merchant.rb+++ b/app/models/provider_merchant.rb@@ -46,12 +46,28 @@ class ProviderMerchant < Merchant# Returns the newly created FamilyMerchant.def convert_to_family_merchant_for(family, attributes = {})transaction do- family_merchant = family.merchants.create!(- name: attributes[:name].presence || name,+ # If the family already has a FamilyMerchant with this name, reuse it+ # instead of failing on the uniqueness validation.+ family_merchant, created = FamilyMerchant.find_or_create_with_name(+ family,+ attributes[:name].presence || name,color: attributes[:color].presence || FamilyMerchant::COLORS.sample,- website_url: attributes[:website_url].presence || website_url+ # A submitted blank website clears it; only an omitted one is inherited.+ website_url: attributes.key?(:website_url) ? attributes[:website_url].presence : website_url)+ # find_or_create_with_name doesn't touch a merchant it reused, so+ # explicitly submitted attributes still need applying here; omitted+ # ones leave the reused merchant untouched. A submitted website+ # (present or blank-to-clear) is honored; color can't be cleared+ # (FamilyMerchant requires it), so only a non-blank submission applies.+ if !created+ reuse_updates = {}+ reuse_updates[:website_url] = attributes[:website_url].presence if attributes.key?(:website_url)+ reuse_updates[:color] = attributes[:color] if attributes[:color].present?+ family_merchant.update!(reuse_updates) if reuse_updates.any?+ end+scope = family.transactions.where(merchant_id: id)# Protect the manual reassignment from being reverted on the nextdiff --git a/app/models/sure_import.rb b/app/models/sure_import.rbindex a4e213953a..0c3b06c2e1 100644--- a/app/models/sure_import.rb+++ b/app/models/sure_import.rb@@ -148,7 +148,11 @@ class SureImport < Importupdate!(summary: result[:summary]) if has_attribute?(:summary)end- record_readback_verification!(before_counts:, reused_counts: reused_counts_from(result[:summary]))+ record_readback_verification!(+ before_counts:,+ reused_counts: reused_counts_from(result[:summary]),+ created_counts: created_counts_from(result[:summary])+ )resultrescue => errorrecord_failed_readback_verification!(before_counts:, error:)@@ -276,9 +280,17 @@ class SureImport < Import%w[categories tags merchants].index_with { |key| (summary || {}).dig(key, "updated").to_i }end- def record_readback_verification!(before_counts:, reused_counts: {})+ # A ProviderMerchant row with no shared match yet becomes a FamilyMerchant+ # (see Family::DataImporter#import_provider_merchants), which isn't counted+ # under the "Merchant" NDJSON line type, so its creation must be added to+ # the expected merchant delta explicitly.+ def created_counts_from(summary)+ { "merchants" => (summary || {}).dig("provider_merchants", "created").to_i }+ end++ def record_readback_verification!(before_counts:, reused_counts: {}, created_counts: {})update_columns(- readback_verification: build_readback_verification(before_counts:, status_for_mismatch: "mismatch", reused_counts:),+ readback_verification: build_readback_verification(before_counts:, status_for_mismatch: "mismatch", reused_counts:, created_counts:),updated_at: Time.current)end@@ -297,11 +309,12 @@ class SureImport < ImportRails.logger.warn("Failed to record Sure import readback verification for import #{id}: #{verification_error.message}")end- def build_readback_verification(before_counts:, status_for_mismatch:, reused_counts: {})+ def build_readback_verification(before_counts:, status_for_mismatch:, reused_counts: {}, created_counts: {})after_counts = readback_count_snapshotactual_delta_counts = delta_counts(before_counts, after_counts)expected_counts = normalized_expected_record_counts- expected_creations = expected_counts.merge(reused_counts) { |_key, expected, reused| [ expected - reused, 0 ].max }+ expected_creations = expected_counts.merge(created_counts) { |_key, expected, created| expected + created }+ expected_creations = expected_creations.merge(reused_counts) { |_key, expected, reused| [ expected - reused, 0 ].max }checked_counts = (actual_delta_counts.keys | expected_counts.keys).index_with do |key|expected_creations.fetch(key, 0).to_ienddiff --git a/test/controllers/family_merchants_controller_test.rb b/test/controllers/family_merchants_controller_test.rbindex e7715d2467..4906cf2a05 100644--- a/test/controllers/family_merchants_controller_test.rb+++ b/test/controllers/family_merchants_controller_test.rb@@ -11,6 +11,53 @@ class FamilyMerchantsControllerTest < ActionDispatch::IntegrationTestassert_response :successend+ # A ProviderMerchant is shared by every family whose transactions use it, so+ # one family's edit must not change what the others see.+ test "changing a provider merchant's website gives only this family its own merchant" do+ shared = ProviderMerchant.create!(name: "Coffee Co", source: "plaid", website_url: "https://coffee.example")+ transaction = Transaction.joins(entry: :account).merge(@user.accessible_accounts).first+ transaction.update!(merchant: shared)++ assert_difference -> { @user.family.merchants.count }, 1 do+ patch family_merchant_url(shared), params: { provider_merchant: { name: "Coffee Co", website_url: "https://attacker.example" } }+ end++ assert_redirected_to family_merchants_path+ assert_equal "https://coffee.example", shared.reload.website_url++ own = transaction.reload.merchant+ assert_instance_of FamilyMerchant, own+ assert_equal "https://attacker.example", own.website_url+ end++ test "changing a provider merchant's website reuses an existing same-name family merchant" do+ shared = ProviderMerchant.create!(name: "Coffee Co", source: "plaid", website_url: "https://coffee.example")+ existing = @user.family.merchants.create!(name: "Coffee Co", website_url: "https://old.example")+ transaction = Transaction.joins(entry: :account).merge(@user.accessible_accounts).first+ transaction.update!(merchant: shared)++ assert_no_difference -> { @user.family.merchants.count } do+ patch family_merchant_url(shared), params: { provider_merchant: { name: "Coffee Co", website_url: "https://attacker.example" } }+ end++ assert_redirected_to family_merchants_path+ assert_equal existing, transaction.reload.merchant+ assert_equal "https://attacker.example", existing.reload.website_url+ end++ test "saving a provider merchant unchanged keeps using the shared merchant" do+ shared = ProviderMerchant.create!(name: "Coffee Co", source: "plaid", website_url: "https://coffee.example")+ transaction = Transaction.joins(entry: :account).merge(@user.accessible_accounts).first+ transaction.update!(merchant: shared)++ assert_no_difference -> { @user.family.merchants.count } do+ patch family_merchant_url(shared), params: { provider_merchant: { name: "Coffee Co", website_url: "https://coffee.example" } }+ end++ assert_redirected_to family_merchants_path+ assert_equal shared, transaction.reload.merchant+ end+test "new" doget new_family_merchant_pathassert_response :successdiff --git a/test/models/family_merchant_test.rb b/test/models/family_merchant_test.rbindex c100af2a3c..823fae44c4 100644--- a/test/models/family_merchant_test.rb+++ b/test/models/family_merchant_test.rb@@ -46,4 +46,146 @@ class FamilyMerchantTest < ActiveSupport::TestCaseassert_includes FamilyMerchant::COLORS, merchant.colorend++ test "find_or_create_with_name reuses an existing merchant instead of raising" do+ existing = FamilyMerchant.create!(family: @family, name: "Existing Merchant")++ merchant, created = FamilyMerchant.find_or_create_with_name(@family, "Existing Merchant", website_url: "https://ignored.example")++ assert_equal existing, merchant+ assert_not created+ assert_nil merchant.website_url+ end++ test "find_or_create_with_name creates a new merchant when none exists" do+ merchant, created = FamilyMerchant.find_or_create_with_name(@family, "Brand New Merchant", website_url: "https://new.example")++ assert created+ assert_equal "Brand New Merchant", merchant.name+ assert_equal "https://new.example", merchant.website_url+ end++ test "find_or_create_with_name recovers from a RecordInvalid uniqueness conflict" do+ existing = FamilyMerchant.create!(family: @family, name: "Race Merchant")+ relation = @family.merchants++ relation.stub :find_by, nil do+ merchant, created = FamilyMerchant.find_or_create_with_name(@family, "Race Merchant")++ assert_equal existing, merchant+ assert_not created+ end+ end+end++# A duplicate name reaching the database's unique index (rather than being+# caught by the model's own uniqueness validation first) needs a genuine+# second, concurrently-committing connection to reproduce: Postgres only+# raises RecordNotUnique, instead of the app-level RecordInvalid, when the+# conflicting row wasn't yet visible to this session's own validation query.+# Runs without transactional fixtures so the writer thread's commit is+# visible to the reader's separate connection.+class FamilyMerchantConcurrencyTest < ActiveSupport::TestCase+ self.use_transactional_tests = false++ setup do+ # The test's main thread, writer thread and reader thread each hold their+ # own checked-out connection at once. The default pool (RAILS_MAX_THREADS,+ # 3) leaves zero headroom for that, so under CI's parallelized test load a+ # thread's connection checkout can itself queue behind another test's use+ # of the pool, throwing off the race entirely. Widen it for this test only.+ @original_db_config = ActiveRecord::Base.connection_db_config+ if @original_db_config.max_connections.to_i < 6+ ActiveRecord::Base.establish_connection(@original_db_config.configuration_hash.except(:pool).merge(max_connections: 6))+ else+ @original_db_config = nil+ end++ @family = Family.create!(+ name: "Race Family", currency: "USD", locale: "en", country: "US",+ date_format: "%m/%d/%Y", timezone: "UTC"+ )+ end++ teardown do+ @family.destroy+ ensure+ ActiveRecord::Base.establish_connection(@original_db_config) if @original_db_config+ end++ test "find_or_create_with_name survives a real unique-constraint violation without aborting the caller's transaction" do+ name = "Race Merchant"+ writer_inserted = Queue.new+ release_writer = Queue.new+ reader_pid = Queue.new+ writer = nil+ reader = nil++ begin+ writer = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ ActiveRecord::Base.transaction do+ FamilyMerchant.create!(family: @family, name: name)+ writer_inserted << true+ release_writer.pop+ end+ end+ end++ reader = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do |connection|+ reader_pid << connection.select_value("SELECT pg_backend_pid()")++ ActiveRecord::Base.transaction do+ merchant, created = FamilyMerchant.find_or_create_with_name(@family, name)+ # Proves the rescued RecordNotUnique didn't poison this transaction.+ count_inside_tx = @family.merchants.where(name: name).count+ { merchant: merchant, created: created, count_inside_tx: count_inside_tx }+ end+ end+ end++ writer_inserted.pop+ pid = reader_pid.pop.to_i++ # Wait until Postgres itself reports the reader blocked on a lock, proving+ # it reached the INSERT (not the early find_by return) and is genuinely+ # waiting on the writer's uncommitted row -- only then is releasing the+ # writer guaranteed to exercise the RecordNotUnique/savepoint path rather+ # than a RecordInvalid from a stale read, or no conflict at all.+ deadline = Time.current + 10.seconds+ wait_event_type = nil+ loop do+ wait_event_type = ActiveRecord::Base.connection.select_value(+ "SELECT wait_event_type FROM pg_stat_activity WHERE pid = #{pid}"+ )+ break if wait_event_type == "Lock" || Time.current > deadline || !reader.alive?+ sleep 0.01+ end++ unless wait_event_type == "Lock"+ # The reader finished (or died) before ever blocking on the lock --+ # most likely it took the early find_by return because the writer's+ # insert became visible too soon, rather than genuine CI slowness.+ diagnosis = reader.alive? ? "timed out waiting" : "the reader thread already finished (status: #{reader.status.inspect})"+ flunk "reader never blocked on the unique index (wait_event_type=#{wait_event_type.inspect}); #{diagnosis}; the race wasn't reproduced"+ end++ release_writer << true+ # .value joins the thread and re-raises any exception it raised, instead+ # of leaving the test hanging on a queue that a dead reader never pushed to.+ result = reader.value++ assert_equal name, result[:merchant].name+ assert_not result[:created]+ assert_equal 1, result[:count_inside_tx]+ assert_equal 1, @family.merchants.where(name: name).count+ ensure+ # Unblocks the writer even if an assertion above failed, so its thread+ # (and checked-out connection) don't leak past this test.+ release_writer << true+ writer&.join(2)+ reader&.join(2)+ end+ endenddiff --git a/test/models/provider_merchant_test.rb b/test/models/provider_merchant_test.rbindex e01f1ff2f9..627291f468 100644--- a/test/models/provider_merchant_test.rb+++ b/test/models/provider_merchant_test.rb@@ -105,4 +105,60 @@ class ProviderMerchantTest < ActiveSupport::TestCaseassert_equal "#4da568", converted.colorassert_nil @provider_merchant.reload.colorend++ test "convert_to_family_merchant_for clears a website submitted blank and inherits an omitted one" do+ @provider_merchant.update!(website_url: "https://acme.example")++ cleared = @provider_merchant.convert_to_family_merchant_for(@family, name: "Acme Cleared", website_url: "")+ inherited = @provider_merchant.convert_to_family_merchant_for(@family, name: "Acme Inherited")++ assert_nil cleared.website_url+ assert_equal "https://acme.example", inherited.website_url+ end++ test "convert_to_family_merchant_for reuses an existing same-name family merchant instead of raising" do+ existing = @family.merchants.create!(name: "Acme Synced", color: "#4da568", website_url: "https://old.example")++ converted = @provider_merchant.convert_to_family_merchant_for(@family, website_url: "https://new.example")++ assert_equal existing.id, converted.id+ assert_equal 1, @family.merchants.where(name: "Acme Synced").count+ assert_equal "https://new.example", existing.reload.website_url+ end++ test "convert_to_family_merchant_for clears a reused merchant's website when submitted blank" do+ existing = @family.merchants.create!(name: "Acme Synced", color: "#4da568", website_url: "https://old.example")++ converted = @provider_merchant.convert_to_family_merchant_for(@family, website_url: "")++ assert_equal existing.id, converted.id+ assert_nil existing.reload.website_url+ end++ test "convert_to_family_merchant_for leaves a reused merchant's website untouched when omitted" do+ existing = @family.merchants.create!(name: "Acme Synced", color: "#4da568", website_url: "https://old.example")++ converted = @provider_merchant.convert_to_family_merchant_for(@family, name: "Acme Synced")++ assert_equal existing.id, converted.id+ assert_equal "https://old.example", existing.reload.website_url+ end++ test "convert_to_family_merchant_for applies a submitted color when reusing a merchant" do+ existing = @family.merchants.create!(name: "Acme Synced", color: "#4da568")++ converted = @provider_merchant.convert_to_family_merchant_for(@family, color: "#db5a54")++ assert_equal existing.id, converted.id+ assert_equal "#db5a54", existing.reload.color+ end++ test "convert_to_family_merchant_for leaves a reused merchant's color untouched when blank or omitted" do+ existing = @family.merchants.create!(name: "Acme Synced", color: "#4da568")++ converted = @provider_merchant.convert_to_family_merchant_for(@family, color: "")++ assert_equal existing.id, converted.id+ assert_equal "#4da568", existing.reload.color+ endenddiff --git a/test/models/sure_import_test.rb b/test/models/sure_import_test.rbindex 5dd7cbc2dc..85ce106202 100644--- a/test/models/sure_import_test.rb+++ b/test/models/sure_import_test.rb@@ -764,6 +764,14 @@ class SureImportTest < ActiveSupport::TestCaseaccountable_type: "Depository",accountable: { subtype: "checking" }} },+ { type: "Valuation", data: {+ id: "valuation-1",+ account_id: "account-1",+ date: "2024-01-14",+ amount: "1000.00",+ currency: "USD",+ kind: "opening_anchor"+ } },{ type: "ProviderMerchant", data: {id: "provider-merchant-1",name: "AMZN MKTP",@@ -784,19 +792,56 @@ class SureImportTest < ActiveSupport::TestCaseresult = @import.sure_preflightassert result.valid?, result.error_message- assert_difference -> { ProviderMerchant.count }, 1 do- @import.publish+ assert_no_difference -> { ProviderMerchant.count } do+ assert_difference -> { @family.merchants.count }, 1 do+ @import.publish+ endendassert_equal "complete", @import.status+ assert_equal "matched", @import.verification_statusentry = @family.entries.find_by!(name: "Amazon purchase")merchant = entry.entryable.merchant- assert_instance_of ProviderMerchant, merchant+ assert_instance_of FamilyMerchant, merchantassert_equal "AMZN MKTP", merchant.name- assert_equal "plaid", merchant.source- assert_equal "plaid_amzn", merchant.provider_merchant_id+ end++ # ProviderMerchant rows are shared across families and bank syncs look them up+ # by provider_merchant_id, which most providers derive from the payee name. An+ # import that created one would pick the name, logo and website other+ # families' synced transactions attach to.+ test "provider merchant import never creates a shared provider merchant" do+ attach_ndjson(provider_merchant_ndjson(+ name: "Call +1 555 0100 for your refund",+ logo_url: "https://tracker.example/pixel.png",+ website_url: "https://phish.example"+ ))++ assert_no_difference -> { ProviderMerchant.count } do+ @import.publish+ end++ assert_equal "complete", @import.status+ assert_equal "matched", @import.verification_status+ assert_nil ProviderMerchant.find_by(provider_merchant_id: "plaid_amzn", source: "plaid")++ merchant = @family.entries.find_by!(name: "Amazon purchase").entryable.merchant+ assert_instance_of FamilyMerchant, merchant+ assert_equal @family, merchant.family+ assert_equal "https://phish.example", merchant.website_url+ end++ test "provider merchant import reuses the family's own merchant of the same name" do+ own = @family.merchants.create!(name: "AMZN MKTP")+ attach_ndjson(provider_merchant_ndjson)++ assert_no_difference [ -> { ProviderMerchant.count }, -> { @family.merchants.count } ] do+ @import.publish+ end++ assert_equal own, @family.entries.find_by!(name: "Amazon purchase").entryable.merchantendtest "provider merchant import reuses an existing matching record instead of duplicating or overwriting it" do@@ -863,45 +908,6 @@ class SureImportTest < ActiveSupport::TestCaseassert_equal existing.id, @family.entries.find_by!(name: "Amazon purchase").entryable.merchant_idend- test "a color in the file is not read when a provider merchant is created" do- attach_ndjson(provider_merchant_ndjson(color: "#123456"))-- assert_difference -> { ProviderMerchant.count }, 1 do- @import.publish- end-- assert_equal "complete", @import.status- assert_nil ProviderMerchant.where(name: "AMZN MKTP", source: "plaid").pick(:color)- end-- {- "RecordNotUnique" => -> { ActiveRecord::RecordNotUnique.new("duplicate key") },- "RecordInvalid" => -> { ActiveRecord::RecordInvalid.new(ProviderMerchant.new.tap { |merchant| merchant.errors.add(:name, :taken) }) }- }.each do |label, build_error|- test "provider merchant import recovers when another import wins the creation race (#{label})" do- winner = ProviderMerchant.create!(name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn")- attach_ndjson(provider_merchant_ndjson)-- ProviderMerchant.stubs(:find_by_import_data).returns(nil).then.returns(winner)- ProviderMerchant.stubs(:create!).raises(build_error.call)-- assert_no_difference -> { ProviderMerchant.count } do- @import.import!- end-- assert_equal winner.id, @family.entries.find_by!(name: "Amazon purchase").entryable.merchant_id- end- end-- test "provider merchant import surfaces validation errors that are not a lost creation race" do- attach_ndjson(provider_merchant_ndjson)- invalid = ActiveRecord::RecordInvalid.new(ProviderMerchant.new.tap { |merchant| merchant.errors.add(:name, :blank) })- ProviderMerchant.stubs(:find_by_import_data).returns(nil)- ProviderMerchant.stubs(:create!).raises(invalid)-- assert_raises(ActiveRecord::RecordInvalid) { @import.import! }- end-test "preflight warns with the actual diff when an existing provider merchant differs from the file" doProviderMerchant.create!(name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn", website_url: "https://amazon.com")attach_ndjson(provider_merchant_ndjson(website_url: "https://amazon.co.uk"))@@ -1080,6 +1086,10 @@ class SureImportTest < ActiveSupport::TestCaseid: "account-1", name: "Provider Merchant Checking", balance: "1000.00", currency: "USD",accountable_type: "Depository", accountable: { subtype: "checking" }} },+ { type: "Valuation", data: {+ id: "valuation-1", account_id: "account-1", date: "2024-01-14", amount: "1000.00",+ currency: "USD", kind: "opening_anchor"+ } },{ type: "ProviderMerchant", data: {id: "provider-merchant-1", name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn"}.merge(merchant_attrs) },