Class: Maintenance::CustomerMaintenance

Inherits:
BaseService show all
Defined in:
app/services/maintenance/customer_maintenance.rb

Instance Method Summary collapse

Methods inherited from BaseService

#initialize, #log_debug, #log_error, #log_info, #log_warning, #logger, #options, #tagged_logger

Constructor Details

This class inherits a constructor from BaseService

Instance Method Details

#clear_expired_credit_cardsObject



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'app/services/maintenance/customer_maintenance.rb', line 123

def clear_expired_credit_cards
  @logger.info 'Vault cleanup starting'
  expired_cards = CreditCardVault.expired.size
  total_count = expired_cards.size
  count = 0
  CreditCardVault.expired.find_each do |c|
    count += 1
    @logger.info "[#{count}/#{total_count}] Card Vault ID #{c.id} expired, destroying"
    begin
      c.destroy
    rescue StandardError => e
      @logger.error "Error destroying card #{c.id}: #{e.message}"
      ErrorReporting.error(e, { credit_card_vault_id: c.id })
    end
  end
  @logger.info 'Vault cleanup completed'
end

#clear_guests(older_than: 30.days.ago, batch_size: 1) ⇒ Object



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
# File 'app/services/maintenance/customer_maintenance.rb', line 69

def clear_guests(older_than: 30.days.ago, batch_size: 1)
  @logger.info 'Initiating clear guests routine'
  abandoned_guest_ids = Customer.where(state: :guest)
                                .where(Customer[:created_at].lteq(older_than))
                                .where.not('EXISTS(select 1 from orders ord where ord.customer_id = parties.id)') # we have already removed cart so we can check only for the presence of an order
                                .where.not('EXISTS(select 1 from room_configurations rc inner join opportunities opp on rc.opportunity_id = opp.id and opp.customer_id = parties.id)')
                                .where.not('EXISTS(select 1 from activities act where act.activity_result_type_id IS NULL AND (act.party_id = parties.id OR act.customer_id = parties.id))')
                                .where.not('EXISTS(select 1 from communications cm where cm.recipient_party_id = parties.id OR cm.sender_party_id = parties.id)')
                                .where.not('EXISTS(select 1 from support_case_participants scp where scp.party_id = parties.id)')
                                .where.not('EXISTS(select 1 from accounts ac where ac.party_id = parties.id)').pluck(:id) # same, we already cleared old rooms, let it just detect presence of a room

  total_guests = abandoned_guest_ids.size

  @logger.info "Destroying #{total_guests} guest records"
  counter = 0
  abandoned_guest_ids.each_slice(batch_size) do |ids|
    counter += ids.size
    @logger.info "[#{counter}/#{total_guests}] Deleting #{ids.size} guests: [#{ids.join(',')}]"
    begin
      Customer.where(id: ids).delete_all
    rescue StandardError => e
      msg = "Exception while deleting records [#{ids.join(',')}].  Exception is #{e}.  Skipping over this batch"
      @logger.error msg
      ErrorReporting.error(e, msg)
    end
  end

  @logger.info "Clear Guest Routine completed with #{counter} records purged."
  counter
end

#find_missing_state_code_for_partiesObject



115
116
117
118
119
120
121
# File 'app/services/maintenance/customer_maintenance.rb', line 115

def find_missing_state_code_for_parties
  sql = "UPDATE parties set state_code = coalesce((select a.state_code from addresses a where a.id = parties.shipping_address_id),(select a.state_code from addresses a where a.id = parties.billing_address_id),(select a.state_code from addresses a where a.id = parties.mailing_address_id))
  where state_code is null and coalesce((select a.state_code from addresses a where a.id = parties.shipping_address_id),(select a.state_code from addresses a where a.id = parties.billing_address_id),(select a.state_code from addresses a where a.id = parties.mailing_address_id)) is not null
  and length(coalesce((select a.state_code from addresses a where a.id = parties.shipping_address_id),(select a.state_code from addresses a where a.id = parties.billing_address_id),(select a.state_code from addresses a where a.id = parties.mailing_address_id))) < 3"
  ActiveRecord::Base.connection.execute(sql)
  @logger.info 'Missing state_code on parties cleanup completed'
end

#fix_bad_sales_repObject



100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'app/services/maintenance/customer_maintenance.rb', line 100

def fix_bad_sales_rep
  # Fix bad primary sales rep
  sql1 = "update parties set primary_sales_rep_id = null where primary_sales_rep_id IS NOT NULL AND NOT EXISTS(select 1 from parties emp where type = 'Employee' and emp.id = parties.primary_sales_rep_id);"
  sql2 = "update parties set secondary_sales_rep_id = null where secondary_sales_rep_id IS NOT NULL AND NOT EXISTS(select 1 from parties emp where type = 'Employee' and emp.id = parties.secondary_sales_rep_id);"
  sql3 = "update parties set local_sales_rep_id = null where local_sales_rep_id IS NOT NULL AND NOT EXISTS(select 1 from parties emp where type = 'Employee' and emp.id = parties.local_sales_rep_id);"

  @logger.info 'Fixing invalid rep data, accounts whose rep id is set to an invalid employee'
  [sql1, sql2, sql3].each_with_index do |sql, i|
    res = ActiveRecord::Base.connection.execute(sql)
    @logger.info "(#{i}) Completed, result status: #{res.cmd_tuples}"
  end
  @logger.info 'Fixing invalid rep data completed.'
  true
end

#match_user_id_to_visitsObject



141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'app/services/maintenance/customer_maintenance.rb', line 141

def match_user_id_to_visits
  @logger.info 'Starting visit matchup party to visits'
  sql = %(
    update visits
      set user_id  = p.id
      from parties p
      where
      p.visit_id = visits.id
      and visits.user_id IS NULL
      and p.visit_id IS NOT NULL
  )
  r = ActiveRecord::Base.connection.execute sql
  @logger.info "Visit matchup completed, #{r.ntuples} party matched"
end

#merge_duplicate_addressesObject



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'app/services/maintenance/customer_maintenance.rb', line 156

def merge_duplicate_addresses
  @logger.info 'Starting checking if there are duplicate addresses'
  da = Customer.duplicate_addresses
  if da.present?
    da.each do |k, _v|
      # Merging addresses

      am = Merger::AddressMerger.new(k.to_i)
      am.perform_merge!
    rescue StandardError => e
      @logger.error "Error merging addresses #{k}: #{e.message}"
      ErrorReporting.error(e)
    end
  end
  @logger.info "Addresses merged from #{da.count} customers."
end

#merge_duplicate_contact_pointsObject



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'app/services/maintenance/customer_maintenance.rb', line 173

def merge_duplicate_contact_points
  @logger.info 'Starting checking if there are duplicate contact points'
  dc = Customer.duplicate_contact_points
  if dc.present?
    dc.each do |k, _v|
      # Merging contact points

      cpm = Merger::ContactPointMerge.new(k.to_i)
      cpm.perform_merge!
    rescue StandardError => e
      @logger.error "Error merging contact points #{k}: #{e.message}"
      ErrorReporting.error(e)
    end
  end
  @logger.info "Contact points merged from #{dc.count} customers."
end

#processObject



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'app/services/maintenance/customer_maintenance.rb', line 2

def process
  PaperTrail.request(whodunnit: 'Maintenance::CustomerMaintenance') do
    fix_bad_sales_rep
    clear_expired_credit_cards
    remove_old_carts
    remove_empty_carts
    remove_old_guest_instant_rooms
    remove_old_guest_empty_opportunities
    remove_old_guest_accounts
    clear_guests
    find_missing_state_code_for_parties
    match_user_id_to_visits
    merge_duplicate_addresses
    merge_duplicate_contact_points
    # remove_duplicate_contact_points
  end
end

#remove_empty_carts(older_than: 1.day.ago) ⇒ Object



28
29
30
31
32
33
34
# File 'app/services/maintenance/customer_maintenance.rb', line 28

def remove_empty_carts(older_than: 1.day.ago)
  @logger.info "Found #{Order.carts.where(line_total: 0).where(Order[:created_at].lteq(older_than)).count} empty carts"
  Order.carts.where(line_total: 0).where(Order[:created_at].lteq(older_than)).in_batches(of: 100).each_with_index do |relation, batch_index|
    @logger.info "Removing empty carts batch of 100 index #{batch_index}"
    relation.delete_all
  end
end

#remove_old_carts(older_than: 30.days.ago) ⇒ Object



20
21
22
23
24
25
26
# File 'app/services/maintenance/customer_maintenance.rb', line 20

def remove_old_carts(older_than: 30.days.ago)
  @logger.info "Found #{Order.carts.where(Order[:created_at].lteq(older_than)).count} old carts"
  Order.where(state: %w[cart in_shipping_estimate]).where(Order[:created_at].lteq(older_than)).in_batches(of: 100).each_with_index do |relation, batch_index|
    @logger.info "Removing old carts batch of 100 index #{batch_index}"
    relation.delete_all
  end
end

#remove_old_guest_accounts(older_than: 3.months.ago) ⇒ Object

They're guest accounts, they have a login but it's ancient.



63
64
65
66
67
# File 'app/services/maintenance/customer_maintenance.rb', line 63

def remove_old_guest_accounts(older_than: 3.months.ago)
  stale_accounts = Account.joins(:party).where(Party[:type].eq('Customer')).where(Party[:created_at].lteq(older_than)).where(Party[:state].eq('guest')).where(Account[:last_sign_in_at].lteq(older_than))
  @logger.info "Found #{stale_accounts.size} stale guest accounts with no recent login activity"
  stale_accounts.delete_all
end

#remove_old_guest_empty_opportunities(older_than: 30.days.ago) ⇒ Object

In this step we remove old empty opportunities in instant quoting



49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/services/maintenance/customer_maintenance.rb', line 49

def remove_old_guest_empty_opportunities(older_than: 30.days.ago)
  all_stale_opps = Opportunity.joins(:customer).where(state: %w[instant_quoting
                                                                abandoned]).where(Opportunity[:created_at].lteq(older_than)).where(Customer[:state].eq('guest')).where('NOT EXISTS(select 1 from room_configurations where room_configurations.opportunity_id = opportunities.id)').pluck(:id)
  total_stale_opps = all_stale_opps.size
  @logger.info "Found #{total_stale_opps} old empty opportunities of guest"
  counter = 0
  all_stale_opps.each_slice(100) do |opportunity_ids|
    counter += opportunity_ids.size
    @logger.info "[#{counter}/#{total_stale_opps}] Removing batch of #{opportunity_ids.size} stale empty opportunities in instant quoting belonging to guests"
    Opportunity.where(id: opportunity_ids).delete_all
  end
end

#remove_old_guest_instant_rooms(older_than: 30.days.ago) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'app/services/maintenance/customer_maintenance.rb', line 36

def remove_old_guest_instant_rooms(older_than: 30.days.ago)
  all_stale_room_configuration_ids = RoomConfiguration.joins(opportunity: :customer).where(state: %w[draft cancelled]).where(RoomConfiguration[:created_at].lteq(older_than)).where(Customer[:state].eq('guest')).where(Opportunity[:state].eq('abandoned')).pluck(:id)
  total_stale_rooms = all_stale_room_configuration_ids.size
  @logger.info "Found #{total_stale_rooms} old instant quotes of guest"
  counter = 0
  all_stale_room_configuration_ids.each_slice(100) do |room_configuration_ids|
    counter += room_configuration_ids.size
    @logger.info "[#{counter}/#{total_stale_rooms}] Removing batch of #{room_configuration_ids.size} stale instant quoted rooms, abandoned, belonging to guests"
    RoomConfiguration.where(id: room_configuration_ids).delete_all
  end
end