1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-08-03 04:25:21 +02:00

Fix migration to handle duplicate merchants per family

This commit is contained in:
Zach Gollwitzer 2025-04-18 12:09:46 -04:00
parent 297a695d0f
commit 79243822bd

View file

@ -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