diff --git a/db/migrate/20250416235758_merchant_and_category_enrichment.rb b/db/migrate/20250416235758_merchant_and_category_enrichment.rb index 2c25eeb3..0bde5a90 100644 --- a/db/migrate/20250416235758_merchant_and_category_enrichment.rb +++ b/db/migrate/20250416235758_merchant_and_category_enrichment.rb @@ -12,8 +12,34 @@ class MerchantAndCategoryEnrichment < ActiveRecord::Migration[7.2] reversible do |dir| dir.up do - # All of our existing merchants are family-generated right now - Merchant.update_all(type: "FamilyMerchant") + ActiveRecord::Base.transaction do + # 1) Mark all existing as FamilyMerchant + Merchant.update_all(type: "FamilyMerchant") + + # 2) Find duplicate family merchants + Merchant + .where(type: 'FamilyMerchant') + .group(:family_id, :name) + .having("COUNT(*) > 1") + .pluck(:family_id, :name) + .each do |family_id, name| + # 3) Grab sorted IDs, first is keeper + ids, duplicate_ids = Merchant + .where(family_id: family_id, name: name) + .order(:id) + .pluck(:id) + .then { |arr| [ arr.first, arr.drop(1) ] } + + next if duplicate_ids.empty? + + # 4) Reassign all transactions pointing at the duplicates + Transaction.where(merchant_id: duplicate_ids) + .update_all(merchant_id: ids) + + # 5) Delete the duplicate merchant rows + Merchant.where(id: duplicate_ids).delete_all + end + end end end