mirror of
https://github.com/maybe-finance/maybe.git
synced 2025-08-04 04:55:20 +02:00
Fix migration to handle duplicate merchants per family
This commit is contained in:
parent
297a695d0f
commit
79243822bd
1 changed files with 28 additions and 2 deletions
|
@ -12,8 +12,34 @@ class MerchantAndCategoryEnrichment < ActiveRecord::Migration[7.2]
|
||||||
|
|
||||||
reversible do |dir|
|
reversible do |dir|
|
||||||
dir.up do
|
dir.up do
|
||||||
# All of our existing merchants are family-generated right now
|
ActiveRecord::Base.transaction do
|
||||||
|
# 1) Mark all existing as FamilyMerchant
|
||||||
Merchant.update_all(type: "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
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue