|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +namespace :duplicate_payments do |
| 4 | + desc "Remove duplicate payment records from database" |
| 5 | + task destroy: :environment do |
| 6 | + duplicate_refund_stripe_ids = StripeRecord |
| 7 | + .group(:stripe_id) |
| 8 | + .having("COUNT(*) > 1") |
| 9 | + .count |
| 10 | + .keys |
| 11 | + |
| 12 | + puts "About to process #{duplicate_refund_stripe_ids}. Continue? [y/N]" |
| 13 | + proceed = $stdin.gets.chomp.downcase |
| 14 | + return unless proceed == 'y' |
| 15 | + |
| 16 | + negative_entry_fees = [] |
| 17 | + |
| 18 | + duplicate_refund_stripe_ids.each do |id| |
| 19 | + puts "handling: #{id}" |
| 20 | + |
| 21 | + # First, get to the state where we have identified the webhook/non-webhook records |
| 22 | + records = StripeRecord.where(stripe_id: id) |
| 23 | + |
| 24 | + if records.count != 2 |
| 25 | + puts "Expected 2 records but got #{records.count} - aborting" |
| 26 | + break |
| 27 | + end |
| 28 | + |
| 29 | + if records.first.parameters.blank? |
| 30 | + wh_record = records.first |
| 31 | + non_wh_record = records.last |
| 32 | + else |
| 33 | + wh_record = records.last |
| 34 | + non_wh_record = records.first |
| 35 | + end |
| 36 | + |
| 37 | + unless wh_record.present? && non_wh_record.present? |
| 38 | + puts "Stripe Records not defined as expect. wh_record: #{wh_record} | non_wh_record: #{non_wh_record} - aborting." |
| 39 | + break |
| 40 | + end |
| 41 | + |
| 42 | + if non_wh_record.registration_payment.blank? |
| 43 | + puts "No registration_payment present for non_wh_record: #{non_wh_record} - aborting." |
| 44 | + break |
| 45 | + end |
| 46 | + |
| 47 | + # Now we've identified the webhook/non-webhook records, we should: |
| 48 | + |
| 49 | + # 1. Associate the webhook events of the wh record to the non-wh record |
| 50 | + wh_record.stripe_webhook_events.each { it.update!(stripe_record: non_wh_record) } |
| 51 | + |
| 52 | + # 2. Destroy any registration_payment associated with the wh record |
| 53 | + wh_record.registration_payment&.destroy! |
| 54 | + |
| 55 | + # 3. Destroy the wh record |
| 56 | + wh_record.reload.destroy! |
| 57 | + |
| 58 | + # Check whether the registration now has a positive balance |
| 59 | + negative_entry_fees << non_wh_record.registration_id unless non_wh_record.registration.reload.paid_entry_fees >= 0 |
| 60 | + end |
| 61 | + |
| 62 | + puts "Completed." |
| 63 | + puts "The following registrations still have negative paid entry fees - investigate: #{negative_entry_fees}" unless negative_entry_fees.empty? |
| 64 | + end |
| 65 | +end |
0 commit comments