Class: Merger::CustomerMerger

Inherits:
BasePartyMerger
  • Object
show all
Defined in:
app/services/merger/customer_merger.rb

Overview

This class is designed to merge two customers

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(customer_master, customer_duplicate, ignore_creation_date = false, options = {}) ⇒ CustomerMerger

Returns a new instance of CustomerMerger.



120
121
122
123
124
125
126
127
128
129
130
131
# File 'app/services/merger/customer_merger.rb', line 120

def initialize(customer_master, customer_duplicate, ignore_creation_date = false, options = {})
  @options = options || {}
  if ignore_creation_date or customer_master.created_at < customer_duplicate.created_at
    @customer_master = customer_master
    @customer_duplicate = customer_duplicate
  else
    @customer_master = customer_duplicate
    @customer_duplicate = customer_master
  end
  @results = []
  @warnings = []
end

Class Method Details

.batch_merge(customer_master, customer_duplicates, options = {}) {|1, 31, 'Analyzing surviving customer'| ... } ⇒ Object

Yields:

  • (1, 31, 'Analyzing surviving customer')


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'app/services/merger/customer_merger.rb', line 55

def self.batch_merge(customer_master, customer_duplicates, options = {})
  logger = options[:logger] || Rails.logger
  yield(1, 31, 'Analyzing surviving customer') if block_given?
  customer_master.orders.where('primary_sales_rep_id = secondary_sales_rep_id').update_all(secondary_sales_rep_id: nil)
  customer_master.invoices.where('primary_sales_rep_id = secondary_sales_rep_id').update_all(secondary_sales_rep_id: nil)
  errors_master = report_errors(customer_master)

  report = { customer_errors: [], execution_errors: [], successes: [] }
  if errors_master.empty?
    customer_duplicates.each do |customer_duplicate|
      logger.info "Verifying if customer #{customer_duplicate.reference_number} can be merged"
      yield(2, 31, 'Analyzing duplicate customer') if block_given?
      customer_duplicate.orders.where('primary_sales_rep_id = secondary_sales_rep_id').update_all(secondary_sales_rep_id: nil)
      customer_duplicate.invoices.where('primary_sales_rep_id = secondary_sales_rep_id').update_all(secondary_sales_rep_id: nil)
      errors_duplicate = report_errors(customer_duplicate)
      order_shipping_states = customer_duplicate.orders.where('orders.state IN (?)', Order::SHIPPING_STATES)
      # active_support_cases = customer_duplicate.support_cases.where('state not in (?)', 'closed')

      if order_shipping_states.present?
        order_shipping_states.each do |o|
          errors_duplicate << { record_type: 'Order', record_id: o.id, record_description: o.state, errors: ['Order is under shipping states'], record: nil }
        end
      end

      # if active_support_cases.present?
      #   active_support_cases.each do |asc|
      #     errors_duplicate << { record_type: 'Support Case', record_id: asc.id, record_description: asc.state, errors: ['Customer duplicated is still participant of an active support case'], record: nil }
      #   end
      # end

      if errors_duplicate.empty?
        previous_state = customer_duplicate.state
        begin
          merger = new(customer_master, customer_duplicate, true, options)
          merger.perform_merge! do |current_step, total_steps, message|
            yield(current_step, total_steps, message) if block_given?
          end
          customer_master.reload
          msg = "Merging #{customer_duplicate.reference_number} #{customer_duplicate.full_name} into #{customer_master.reference_number} #{customer_master.full_name}"
          report[:successes] << msg
          logger.info msg
        rescue StandardError => e
          cd = Customer.where(id: customer_duplicate.id).first
          customer_duplicate.update_column(:state, previous_state) if cd.present? # if there is an execution error, customer_duplicate gets its previous state
          msg = "Cannot merge #{customer_duplicate.reference_number} into #{customer_master.reference_number} due to errors: #{e}"
          report[:execution_errors] << msg
          logger.error msg
          ErrorReporting.error(e, msg)
        end
      else
        msg = "Cannot merge #{customer_duplicate.reference_number} into #{customer_master.reference_number} due to errors: #{errors_duplicate.inspect}"
        report[:customer_errors] << { customer_id: customer_duplicate.id, customer_name: customer_duplicate.full_name, errors_detail: errors_duplicate }
        logger.error msg
      end
    end
    customer_master.reload
    Customer::SalesRepAssigner.auto_assign(customer_master)
  else
    msg = "Customer master #{customer_master.reference_number} has errors. #{errors_master.inspect}"
    logger.error msg
    report[:customer_errors] << { customer_id: customer_master.id, customer_name: customer_master.full_name, errors_detail: errors_master }
  end
  report
end

.create_contact_from_customer(customer) ⇒ Object



678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'app/services/merger/customer_merger.rb', line 678

def self.create_contact_from_customer(customer)
  new_contact = customer.dup.becomes(Contact)
  new_contact.send(:type=, 'Contact')
  new_contact.id = nil
  new_contact.visit_id = nil
  new_contact.uuid = nil
  new_contact.customer = customer
  new_contact.save!

  # The dup above copies profile_image_id to the new contact. Detach the
  # image from the source customer so that when the customer is later
  # destroyed, dependent: :destroy doesn't cascade-delete the image that
  # now belongs to the new contact.
  if new_contact.profile_image_id.present?
    customer.update_column(:profile_image_id, nil)
  end

  customer.contact_points.each do |cp|
    cp.party = new_contact
    cp.save!
  end
  customer.opportunities.each do |opp|
    opp.contact = new_contact
    opp.save!
  end
  customer.reload
  new_contact
end

.inventory(customer) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'app/services/merger/customer_merger.rb', line 19

def self.inventory(customer)
  [
    customer,
    customer.contacts.map { |c| Merger::ContactMerger.inventory(c) },
    customer.,
    customer.addresses.to_a,
    customer.contact_points.to_a,
    customer.opportunities.to_a,
    customer.opportunities.map(&:room_configurations),
    customer.orders.to_a,
    customer.orders.map(&:deliveries),
    customer.orders.map(&:shipping_address),
    customer.quotes.to_a,
    customer.invoices.to_a,
    customer.credit_memos.to_a,
    customer.rmas.to_a,
    customer.purchase_orders.to_a,
    customer.credit_applications.to_a, # customer.activities.to_a,
    customer.child_organizations.to_a,
    customer.tax_exemptions.to_a,
    customer.credit_card_vaults.to_a,
    customer..to_a,
    customer.identification_numbers.to_a,
    customer.notification_channels.to_a,
    customer.survey_enrollments.to_a,
    customer.course_enrollments.to_a,
    customer.certifications.to_a,
    customer.liability_insurances.to_a,
    customer.quick_estimators.to_a,
    customer.preset_jobs.to_a,
    customer.room_plans.to_a,
    customer.payments.to_a,
    customer.statement_of_accounts.to_a
  ].flatten.compact.uniq
end

.report_errors(customers) ⇒ Object

Run the whole gamut of known validation to determine if the customer
can be merged



6
7
8
9
10
11
12
13
14
15
16
17
# File 'app/services/merger/customer_merger.rb', line 6

def self.report_errors(customers)
  customer_errors = []
  [customers].flatten.each do |customer|
    customer_inventory = inventory(customer)
    # Reject all valid records
    customer_inventory.reject(&:valid?).each do |r|
      customer_errors << { record_type: r.class.name, record_id: r.id, record_description: r.to_s, errors: r.errors.full_messages, record: r }
    end
    customer_errors << { record_type: 'Customer', record_id: customer.id, record_description: customer.state, errors: ['Unsuitable state for merging'], record: nil } unless customer.can_be_merged?
  end
  customer_errors
end

Instance Method Details

#perform_merge! {|31, 31, 'Removing Duplicate Contact Points'| ... } ⇒ Object

Yields:

  • (31, 31, 'Removing Duplicate Contact Points')


133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
# File 'app/services/merger/customer_merger.rb', line 133

def perform_merge!
  return false if @customer_master == @customer_duplicate
  raise 'Incompatible catalogs' if @customer_master.catalog_id != @customer_duplicate.catalog_id

  # Starting merge by blocking any change to duplicate customer
  # Customer passed as @customer_duplicate will be destroyed if the merge is successful
  previous_state = @customer_duplicate.state
  @customer_duplicate.merge_lock!

  Customer.transaction do
    address_remap = {}
    contact_point_remap = {}
    contact_remap = {}
    tax_exemptions_remap = {}
    contact_remap[@customer_duplicate.id] = @customer_master.id

    @customer_master.merged_from_ids ||= []
    @customer_master.merged_from_ids << @customer_duplicate.id

    # If customer master is an org and customer dupe is a person, dupe becomes a contact, contact points, addresses will get remapped first
    new_contact = nil
    if @customer_master.is_organization? && @customer_duplicate.is_person?
      new_contact = self.class.create_contact_from_customer(@customer_duplicate)
      @results << "#{@customer_duplicate} is a person, creating as contact of #{@customer_master}"
    end

    yield(3, 31, 'Merging Contacts') if block_given?
    @customer_duplicate.contacts.each do |contact|
      if detected_contact_dupe = @customer_master.contacts.detect { |cnt| cnt.name.upcase.strip == contact.name.upcase.strip }
        cnt_success, cnt_results = Merger::ContactMerger.new(detected_contact_dupe, contact).perform_merge!
        append_results cnt_results if cnt_success
        contact_remap[contact.id] = detected_contact_dupe.id
      else
        append_results "Contact #{contact.id} is being added to Customer id #{@customer_master.id} #{@customer_master.name}"
        contact_remap[contact.id] = contact.id
        contact.customer_id = @customer_master.id
        contact.save!
      end
    end

    yield(4, 31, 'Merging Adresses') if block_given?
    @customer_duplicate.addresses.each do |o|
      # Don't import duplicate address, store in map
      if found_address = @customer_master.addresses.detect { |a| a == o }
        @results << "Address #{o.id} will not be moved as it already exists in customer id #{@customer_master.id} as address id #{found_address.id}"
        address_remap[o.id] = found_address.id
        if o.jde_number
          if found_address.jde_number
            @warnings << "Address #{found_address.id} with jde number #{found_address.jde_number} cannot be merged with address #{o.id} with jde number #{o.jde_number}.  Manual intervention is required to evaluate the surviving jde number, update #{found_address.id} with the final jde number."
          else
            # Update the master's jde number
            append_results "Address #{found_address.id} will be updated with Address id #{o.id}'s jde number #{o.jde_number}"
            found_address.update_column(:jde_number, o.jde_number)
          end
        end
      else
        append_results "Address #{o.id} will be added to Customer #{@customer_master.id}"
        address_remap[o.id] = o.id
        o.update_column(:party_id, @customer_master.id)
      end
      # @customer_master.billing_address_id = address_remap[o.id] if @customer_duplicate.billing_address_id == o.id
      # @customer_master.shipping_address_id = address_remap[o.id] if @customer_duplicate.shipping_address_id == o.id
      # @customer_master.mailing_address_id = address_remap[o.id] if @customer_duplicate.mailing_address_id == o.id
    end

    # Add all of a customer master addresses to the remap just in case
    @customer_master.addresses.each do |address|
      address_remap[address.id] = address.id
    end

    yield(5, 31, 'Merging Contact Points') if block_given?
    @customer_duplicate.contact_points.each do |cp|
      if detected_dupe = @customer_master.contact_points.detect { |cp2| cp2.detail == cp.detail and cp2.category == cp.category }
        append_results "Contact Point #{cp.id} #{cp.category} #{cp.detail} will be ignored as it exists already in Customer #{@customer_master.id}"
        contact_point_remap[cp.id] = detected_dupe.id
      else
        append_results "Contact Point #{cp.id} #{cp.category} #{cp.detail} will be added to Customer #{@customer_master.id}"
        contact_point_remap[cp.id] = cp.id
        @customer_master.contact_points << cp
      end
    end

    yield(6, 31, 'Merging Opportunities') if block_given?
    @customer_duplicate.opportunities.each do |o|
      append_results "Opportunity #{o.id} #{o.name} will be moved to Customer #{@customer_master.id}"
      o.customer = @customer_master
      o.contact_id = contact_remap[o.contact_id]
      o.name = "#{o.name} (#{o.created_at.to_fs(:crm_default)})" if @customer_master.opportunities.where('name ILIKE ?', o.name).exists?
      raise "Cannot save opportunity id #{o.id}. #{o.errors_to_s}" unless o.save

      o.quotes.each do |q|
        freeze_quote = q.complete? || q.cancelled?
        @results << "Quote #{q.id} #{q.reference_number} will be moved to Customer #{@customer_master.id}"
        # address uses remap if one is defined or self.
        if q.shipping_address
          q.shipping_address_id = address_remap[q.shipping_address_id] if q.shipping_address.try(:party_id) # don't remap as it's a one-time shipping address
          q.shipping_address_id ||= @customer_master.shipping_address_id || @customer_master.main_address.try(:id)
          # Remap all delivery quotes
          q.deliveries.each do |dq|
            dq.update_column(:destination_address_id, q.shipping_address_id)
          end
          q.deliveries.reload # reloads
          q.do_not_set_totals = freeze_quote # completed or cancelled quote are not active don't need a reset
          raise "Cannot save quote ref #{q.reference_number}. #{q.errors_to_s}" unless q.save
        else
          q.deliveries.delete_all
        end
        q.do_not_detect_shipping = true
        q.fix_catalog
        q.reload
        q.do_not_detect_shipping = true
        q.do_not_set_totals = freeze_quote
        unless freeze_quote
          res = q.reset_discount
          raise "Cannot reset discount on quote ref #{q.reference_number}. #{q.errors_to_s}" unless res
        end
      end
    end

    yield(7, 31, 'Merging Tax Exemptions') if block_given?
    @customer_duplicate.tax_exemptions.each do |te|
      if master_tax_exemption = @customer_master.tax_exemptions.detect { |te2| te2.state_code == te.state_code && te2.tax_type == te.tax_type }
        # Detect which one has later exemption
        te.orders.each { |o| o.update_column(:tax_exemption_id, master_tax_exemption.id) }
      else # Straight move
        @customer_master.tax_exemptions << te
        tax_exemptions_remap[te.id] = te.id
      end
    end

    yield(8, 31, 'Merging Orders') if block_given?
    @customer_duplicate.orders.each do |o|
      append_results "Order #{o.id} #{o.reference_number} will be moved to Customer #{@customer_master.id}"
      freeze_order = !o.is_sales_order? || o.invoiced?
      o.customer = @customer_master
      o.contact_id = contact_remap[o.contact_id]
      o.spiff_rep_id = contact_remap[o.spiff_rep_id]
      o.shipping_address_id = address_remap[o.shipping_address_id] if o.shipping_address.try(:party_id)
      # Old accounts sometime don't have an address just assume its the shipping
      o.shipping_address_id ||= @customer_master.shipping_address_id || @customer_master.main_address.try(:id)
      o.do_not_detect_shipping = true
      o.non_commissionable = false if !o.invoiced? and @customer_master.primary_sales_rep.present?
      o.deliveries.each do |dq|
        dq.destination_address_id = o.shipping_address_id
        if dq.destination_address.reload and dq.valid?
          dq.save!
        else
          dq.destroy
        end
      end
      o.deliveries.reload # This reloads
      o.do_not_set_totals = true if freeze_order
      raise "Cannot save order ref #{o.reference_number}. #{o.errors_to_s}" unless o.save
    end

    # invoices
    yield(9, 31, 'Merging Invoices') if block_given?
    invoices = Invoice.where('customer_id = ? or billing_customer_id = ?', @customer_duplicate.id, @customer_duplicate.id)
    invoices.each do |i|
      append_results "Invoice #{i.id} will be moved to customer #{i.customer_id}"
      if i.billing_address.party_id == @customer_duplicate.id # Only remap the billing address if it belongs to the same customer being merged
        i.billing_address_id = address_remap[i.billing_address_id] if i.billing_address && i.billing_address.party_id # don't remap as it's a one-time billing address
        i.billing_customer_id = @customer_master.id
      end
      i.shipping_address_id = address_remap[i.shipping_address_id] if i.shipping_address && i.shipping_address.party_id # don't remap as it's a one-time shipping address
      i.customer_id = @customer_master.id
      i.do_not_set_totals = true
      i.save!
    end

    # credit memos
    yield(10, 31, 'Merging Credit Memos') if block_given?
    @customer_duplicate.credit_memos.each do |cm|
      if cm.billing_address.party_id == cm.customer_id # Only remap the billing address if it belongs to the same customer being merged
        cm.update_column(:billing_address_id, address_remap[cm.billing_address_id]) unless cm.billing_address.party_id.nil? # don't remap as it's a one-time billing address
      end
      cm.update_column(:billing_customer_id, @customer_master.id) if cm.customer_id == cm.billing_customer_id
      cm.update_column(:customer_id, @customer_master.id)

      cm.update_column(:shipping_address_id, address_remap[cm.shipping_address_id]) unless cm.shipping_address.party_id.nil? # don't remap as it's a one-time shipping address
    end

    # rmas
    yield(11, 31, 'Merging RMAs') if block_given?
    @customer_duplicate.rmas.each do |rma|
      rma.update_column(:customer_id, @customer_master.id)
      rma.update_column(:ship_from_address_id, address_remap[rma.ship_from_address_id]) unless rma.ship_from_address.party_id.nil? # don't remap as it's a one-time address
    end

    # Outgoing Payments
    yield(12, 30, 'Merging Outgoing Payments') if block_given?
    @customer_duplicate.outgoing_payments.each do |payment|
      payment.update_column(:supplier_id, @customer_master.id)
    end

    # vouchers
    yield(13, 31, 'Merging Vouchers') if block_given?
    @customer_duplicate.vouchers.each do |v|
      v.update_column(:supplier_id, @customer_master.id)
    end

    # receipts
    yield(14, 31, 'Merging Receipts') if block_given?
    @customer_duplicate.receipts.each do |r|
      r.update_column(:customer_id, @customer_master.id)
    end

    # purchase orders
    yield(15, 31, 'Merging Purchase Orders') if block_given?
    @customer_duplicate.purchase_orders.each do |po|
      po.update_column(:supplier_id, @customer_master.id)
    end

    # credit applications
    yield(16, 31, 'Merging Credit Applications') if block_given?
    @customer_duplicate.credit_applications.each do |ca|
      ca.update_column(:customer_id, @customer_master.id)
    end

    praises = Praise.where(originating_party_id: @customer_duplicate.id)
    praises.update_all(originating_party_id: @customer_master.id)

    # survey enrollments
    yield(18, 31, 'Merging Survey Enrollments') if block_given?
    @customer_duplicate.survey_enrollments.each do |se|
      se.update_column(:party_id, @customer_master.id)
      se.customer_topics.each do |ct|
        ct.update_column(:party_id, @customer_master.id)
      end
    end

    # courses, certification and liability insurance
    yield(19, 31, 'Merging Courses, Certification and Liability Insurance') if block_given?
    @customer_duplicate.course_enrollments.each do |ce|
      ce.update_column(:party_id, @customer_master.id)
      ce.customer_topics.each do |cet|
        cet.update_column(:party_id, @customer_master.id)
      end
    end
    @customer_duplicate.certifications.each do |cert|
      cert.update_column(:party_id, @customer_master.id)
    end
    @customer_duplicate.liability_insurances.each do |l|
      l.update_column(:customer_id, @customer_master.id)
    end

    # Support Case Participations
    yield(20, 31, 'Merging Support Case Participants') if block_given?
    @customer_duplicate.support_case_participants.each do |scp|
      old_party_id = scp.party_id
      role = SupportCaseParticipant::ROLES.detect { |k, v| v == @customer_master.profile_id && k != 'iso' && k != 'unknown' }&.first || 'unknown'

      if new_contact.present?
        scp.update_columns(party_id: new_contact.id)
        Communication.where(recipient_party_id: old_party_id).update_all(recipient_party_id: new_contact.id)
      elsif existing_scp = scp.support_case.support_case_participants.where(party_id: @customer_master.id).first
        # Master already participates on this case -- enrich its participant
        # with the duplicate's contact info, remap Communications, then
        # remove the duplicate row (unique index prevents both pointing at master).
        existing_scp.email ||= scp.email
        existing_scp.phone ||= scp.phone
        existing_scp.fax   ||= scp.fax
        existing_scp.save! if existing_scp.changed?
        existing_scp.update_column(:role, role)
        Communication.where(resource_type: 'SupportCaseParticipant', resource_id: scp.id).update_all(resource_id: existing_scp.id)
        Communication.where(recipient_party_id: old_party_id).update_all(recipient_party_id: existing_scp.party_id)
        scp.destroy
      else
        # Master is not on this case -- reassign the participant directly.
        # Uses update_columns to bypass validations/callbacks that could
        # silently fail, leaving the row on the duplicate and causing
        # cascade-deletion when the duplicate customer is destroyed.
        scp.update_columns(party_id: @customer_master.id, role: role)
        Communication.where(recipient_party_id: old_party_id).update_all(recipient_party_id: @customer_master.id)
      end
    end

    # Opportunity Participants
    yield(21, 31, 'Merging Opportunity Participants') if block_given?
    @customer_duplicate.opportunity_participants.update_all(party_id: @customer_master.id)

    yield(22, 31, 'Merging Activities') if block_given?
    Activity.where(party_id: contact_remap.keys).each do |a|
      append_results "Customer Activity #{a.id} will be moved to Customer #{@customer_master.id}"
      a.update(
          party_id: contact_remap[a.party_id],
          customer_id: @customer_master.id,
          notes: a.notes.presence || a.description || '-'
        )
    end
    # Look for activities where customer_id is misaligned
    customer_activities = Activity.where(customer_id: @customer_duplicate.id)
    customer_activities.update_all(customer_id: @customer_master.id)

    @customer_duplicate.child_organizations.each do |co|
      new_parent = nil
      new_parent = @customer_master.id if co.id != @customer_master.id
      co.update_column(:parent_id, new_parent)
      append_results "Child Org id #{co.id} will be moved to #{new_parent}"
    end

    # move stored cards from the duplicate to the master, and copy the stripe_customer_id
    # but only if the master doesn't already have any stored cards
    yield(23, 31, 'Merging Stored Cards') if block_given?
    if !@customer_master.credit_card_vaults.any? and @customer_duplicate.credit_card_vaults.any?
      @customer_master.stripe_customer_id = @customer_duplicate.stripe_customer_id
      @customer_duplicate.credit_card_vaults.each { |ccv| @customer_master.credit_card_vaults << ccv }
    end
    @customer_duplicate..each do |san|
      @customer_master. << san unless @customer_master..detect do |san2|
        san2. = san. and san2.carrier = san.carrier
      end
    end
    @customer_duplicate.identification_numbers.each { |idn| @customer_master.identification_numbers << idn unless @customer_master.identification_numbers.detect { |idn2| idn2.number == idn.number and idn2.category == idn.category } }
    @customer_duplicate.notification_channels.each do |nc|
      @customer_master.notification_channels << nc unless @customer_master.notification_channels.detect do |nc2|
        nc2.notification_type == nc.notification_type and nc2.contact_point_id == nc.contact_point_id
      end
    end
    @customer_duplicate.quick_estimators.each { |qe| @customer_master.quick_estimators << qe }

    @customer_master.data_import_row = @customer_duplicate.data_import_row

    # Merge accounts into master
    if @customer_duplicate.accounts.present?
      append_results "Accounts #{@customer_duplicate.} were relocated to customer id #{@customer_master.id}. "
      @customer_duplicate.accounts.update_all(party_id: @customer_master.id)
    end

    # if @customer_duplicate.account && @customer_master.account.nil?
    #   append_results "Account id #{@customer_duplicate.account.id} #{@customer_duplicate.account.email} was relocated to customer id #{@customer_master.id}, notifying parties for security."
    #   @customer_duplicate.account.update_column(:party_id, @customer_master.id)
    #   @customer_duplicate.account.account_created_notify_reps_and_master_account
    # elsif @customer_duplicate.account
    #   @warnings << "Account id #{@customer_duplicate.account.id} #{@customer_duplicate.account.email} will be ignored and destroyed since an account already exist in target customer"
    # end

    # Merge and copy all profiling data
    @customer_master.profile_id ||= @customer_duplicate.profile_id
    @customer_master.buying_group_id ||= @customer_duplicate.buying_group_id
    @customer_master.tier2_program_pricing = @customer_duplicate.tier2_program_pricing if @customer_duplicate.pricing_program_discount > @customer_master.pricing_program_discount

    # Parent handling, master inherits the duplicate's parent unless its the same account
    if @customer_master.parent_id.nil? && @customer_duplicate.parent_id && @customer_duplicate.parent_id != @customer_master.id
      @customer_master.parent_id = @customer_duplicate.parent_id
      if @customer_duplicate.billing_address.party == @customer_duplicate.parent_id
        # Inherit parent billing address id as well
        @customer_master.billing_address == @customer_duplicate.billing_address
      end
    else
      @customer_duplicate.parent_id = nil
    end

    # Merging payments
    yield(24, 31, 'Merging Payments') if block_given?
    @customer_duplicate.payments.each do |payment|
      payment.update_column(:customer_id, @customer_master.id)
    end

    # Merging customer drop events
    CustomerDropEvent.where(customer_id: @customer_duplicate).each do |customer_drop_event|
      customer_drop_event.update_column(:customer_id, @customer_master.id)
    end

    # Merging exported catalog item packets
    ExportedCatalogItemPacket.where(customer_id: @customer_duplicate).each do |exported_catalog_item_packet|
      exported_catalog_item_packet.update_column(:customer_id, @customer_master.id)
    end

    # Locator record
    yield(25, 31, 'Merging Locator Record') if block_given?
    if @customer_duplicate.locator_record && @customer_master.locator_record.nil?
      if @customer_duplicate.locator_record.confirmed?
        locator_record = @customer_duplicate.locator_record
        locator_record.customer = @customer_master
        locator_record.address_id = address_remap[@customer_master.locator_record.address_id]
        locator_record.save!
      else # don't bother
        @customer_duplicate.locator_record.destroy
      end
    end

    # Preset Jobs
    @customer_duplicate.preset_jobs.each do |pj|
      append_results "Preset Job #{pj.id} #{pj.name} will be moved to Customer #{@customer_master.id}"
      pj.customer = @customer_master
      pj.contact_id = contact_remap[pj.contact_id]
      pj.save!
    end

    # Merging locator black list
    LocatorBlackListParty.where(customer_id: @customer_duplicate).each do |locator_black_list_party|
      locator_black_list_party.update_column(:customer_id, @customer_master.id)
    end

    # Merging locator white list
    LocatorWhiteListParty.where(customer_id: @customer_duplicate).each do |locator_white_list_party|
      locator_white_list_party.update_column(:customer_id, @customer_master.id)
    end

    # Visits
    yield(26, 31, 'Merging Visits') if block_given?
    @customer_duplicate.visits.update_all(user_id: @customer_master.id)

    # Scheduler bookings reference party_id; Activity#set_linked_parties pulls those ids from
    # SchedulerBooking#link_party_ids. Without remapping, post-merge saves can INSERT a
    # destroyed party into activities_parties (AppSignal #3373).
    SchedulerBooking.where(party_id: @customer_duplicate.id).update_all(party_id: @customer_master.id)

    # Copy Feeds
    @customer_master.feeds += @customer_duplicate.feeds
    # Reload duplicate to pick up any DB-level changes (e.g., ON DELETE nullify
    # cascades that may have nullified FK references like profile_image_id during
    # contact merging). In-memory objects don't reflect these DB-level changes.
    @customer_duplicate.reload

    # Now we can do a mass assignments of anything undefined
    @customer_master.attributes = @customer_duplicate.attributes.merge(@customer_master.attributes) { |k, oldval, newval| newval.presence || oldval }
    # Exception being the source, we always take the latest source (original stays)
    # BUT preserve master's source if master has Google Ads attribution
    @customer_master.store_original_source
    if @customer_duplicate.source_id.present? && !@customer_duplicate.source.unknown_source?
      @customer_master.source = @customer_duplicate.source unless @customer_master.source_locked?
    end

    # Merge consent preferences - keep the most recent or most complete
    if @customer_duplicate.consent_preferences.present?
      if @customer_master.consent_preferences.blank?
        # Master has no consent, use duplicate's
        @customer_master.consent_preferences = @customer_duplicate.consent_preferences
        append_results 'Consent preferences copied from duplicate customer'
      elsif @customer_duplicate.consent_updated_at.present? &&
            (@customer_master.consent_updated_at.blank? || @customer_duplicate.consent_updated_at > @customer_master.consent_updated_at)
        # Duplicate has more recent consent, use that
        @customer_master.consent_preferences = @customer_duplicate.consent_preferences
        append_results 'Consent preferences updated from duplicate customer (more recent)'
      else
        append_results 'Consent preferences retained from master customer'
      end
    end

    if @customer_master.lead_qualify?
      @customer_master.state = 'lead' # this will allow the updating
    end

    yield(27, 31, 'Merging Sales Commissions') if block_given?
    # Merging sales commission net base details
    SalesCommissionNetBaseDetail.where(customer_id: @customer_duplicate).each do |sales_detail|
      sales_detail.update_columns(customer_id: @customer_master.id, customer_name: @customer_master.full_name)
    end

    # Merging sales commission details
    update_sales_commission_detail = <<-SQL
      update sales_commission_details set customer_id = #{@customer_master.id}, customer_name = (select full_name from parties where parties.id = #{@customer_master.id}) where customer_id = #{@customer_duplicate.id};
    SQL
    ActiveRecord::Base.connection.execute(update_sales_commission_detail)

    # Merging service jobs
    @customer_duplicate.service_jobs.update_all(customer_id: @customer_master.id)

    # Merging showcases
    @customer_duplicate.showcases.update_all(customer_id: @customer_master.id)

    # Merging statement of accounts
    @customer_duplicate.statement_of_accounts.update_all(customer_id: @customer_master.id)

    # Merging votes
    @customer_duplicate.votes.update_all(customer_id: @customer_master.id)

    # Subscriber data
    yield(28, 31, 'Merging Subscriber data') if block_given?
    # Subscriber.where(customer_id: @customer_duplicate.id).update_all(customer_id: @customer_master.id)
    duplicate_subscribers = Subscriber.where(customer_id: @customer_duplicate.id)
    duplicate_subscribers.each do |dsl|
      master_subscriber = Subscriber.where(customer_id: @customer_master.id).where(subscriber_list_id: dsl.subscriber_list_id)
      if master_subscriber.present?
        master_subscriber.update_all(active: dsl.active)
        dsl.destroy
      else
        dsl.update_column(:customer_id, @customer_master.id)
      end
    end

    # Room Plans
    yield(29, 31, 'Merging Room Plans') if block_given?
    @customer_duplicate.room_plans.update_all(party_id: @customer_master.id)

    append_results merge_destination_call_records(@customer_duplicate, @customer_master)
    append_results merge_origin_call_records(@customer_duplicate, @customer_master)
    append_results merge_origin_call_logs(@customer_duplicate, @customer_master)
    append_results merge_destination_call_logs(@customer_duplicate, @customer_master)
    append_results merge_queue_call_logs(@customer_duplicate, @customer_master)
    append_results merge_inbound_communications(@customer_duplicate, @customer_master)
    append_results merge_party_topics(@customer_duplicate, @customer_master)
    append_results merge_sms_messages(@customer_duplicate, @customer_master)

    append_results "Other changes: \n #{@customer_master.changes.to_yaml}"

    # Safety check: ensure profile_image still exists before saving.
    # The image may have been destroyed during contact merging via
    # dependent: :destroy on belongs_to :profile_image, leaving a stale
    # in-memory reference that would violate the FK constraint.
    if @customer_master.profile_image_id.present? && !Image.exists?(@customer_master.profile_image_id)
      @customer_master.profile_image_id = nil
    end

    @customer_master.save!
    @customer_master.reload
    Pricing::DiscountLevelChangedHandler.call_for(@customer_master)
    @customer_master.activities.create(new_note: "Customer Merge Results.\n#{@results.join('\n')}\n\nWarnings: #{@warnings.join('\n')}")
    @customer_duplicate.reload
    @customer_duplicate.activities.reload # This is somehow needed to prevent foreign key issue

    # Detach profile_image from the duplicate before destroying it.
    # The duplicate's image may have been transferred to the master (or a new
    # contact) via the mass attribute merge or create_contact_from_customer.
    # Without this, dependent: :destroy on belongs_to :profile_image would
    # cascade-delete the image that the master now references.
    detach_shared_profile_image(@customer_duplicate)

    raise "Could not complete merge, duplicate cannot be deleted: #{@customer_duplicate.errors_to_s}" unless @customer_duplicate.destroy

    # Re-evaluate any open activities and re-assign
    @customer_master.activities.open_activities.each do |a|
      a.auto_assign
      a.save!
    end
  end

  begin
    @customer_duplicate.update_column(:state, previous_state)
  rescue StandardError
    nil
  end # In case the customer duplicate still exists
  # Merging addresses
  yield(30, 31, 'Removing Duplicate Addresses') if block_given?
  am = Merger::AddressMerger.new(@customer_master.id)
  am.perform_merge!
  # Merging contact points
  yield(31, 31, 'Removing Duplicate Contact Points') if block_given?
  cpm = Merger::ContactPointMerge.new(@customer_master.id)
  cpm.perform_merge!
  @customer_master
end