Class: Maintenance::CustomerMaintenance

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

Overview

Service object: customer maintenance.

Instance Attribute Summary

Attributes inherited from BaseService

#options

Instance Method Summary collapse

Methods inherited from BaseService

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

Constructor Details

This class inherits a constructor from BaseService

Instance Method Details

#clear_expired_credit_cardsObject



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

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



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

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)').ids # 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.delete_by(id: ids)
    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



118
119
120
121
122
123
124
# File 'app/services/maintenance/customer_maintenance.rb', line 118

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.lease_connection.execute(sql)
  @logger.info 'Missing state_code on parties cleanup completed'
end

#fix_bad_sales_repObject



103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'app/services/maintenance/customer_maintenance.rb', line 103

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.lease_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



144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'app/services/maintenance/customer_maintenance.rb', line 144

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.lease_connection.execute sql
  @logger.info "Visit matchup completed, #{r.ntuples} party matched"
end

#merge_duplicate_addressesObject



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

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



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

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



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

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



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

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



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

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.



66
67
68
69
70
# File 'app/services/maintenance/customer_maintenance.rb', line 66

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



52
53
54
55
56
57
58
59
60
61
62
63
# File 'app/services/maintenance/customer_maintenance.rb', line 52

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)').ids
  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.delete_by(id: opportunity_ids)
  end
end

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



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

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')).ids
  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.delete_by(id: room_configuration_ids)
  end
end