Class: Tagging::SyncRestaurantTagsTotalsTableWorker

Inherits:
ApplicationWorker show all
Defined in:
app/workers/tagging/sync_restaurant_tags_totals_table_worker.rb

Instance Method Summary collapse

Methods inherited from ApplicationWorker

unlimited_retry

Instance Method Details

#perform(restaurant_ids = [], restaurant_tag_ids = []) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/workers/tagging/sync_restaurant_tags_totals_table_worker.rb', line 8

def perform(restaurant_ids = [], restaurant_tag_ids = [])
  Restaurant.where(filter_query_for_restaurant_ids(restaurant_ids)).distinct.pluck(:city_id).compact.each do |city_id|
    rtr_subquery = RestaurantTagsRestaurant.joins(:restaurant).
      where("restaurants.expiry_date > DATE(CONVERT_TZ(NOW(), 'UTC', restaurants.time_zone))").
      where("restaurants.active = 1 AND restaurants.city_id = #{city_id}").
      where(filter_query_for_tag_ids_rtr(restaurant_tag_ids)).
      group(:restaurant_tag_id).
      select('restaurant_tag_id, COUNT(DISTINCT restaurant_id) AS rtr_count').to_sql

    pt_subquery = PrimaryTag.joins(:restaurant).
      where("restaurants.expiry_date > DATE(CONVERT_TZ(NOW(), 'UTC', restaurants.time_zone))").
      where("restaurants.active = 1 AND restaurants.city_id = #{city_id}").
      where(filter_query_for_tag_ids_pt(restaurant_tag_ids)).
      group(:restaurant_tag_id).
      select('restaurant_tag_id, COUNT(DISTINCT restaurant_id) AS pt_count').to_sql

    records = RestaurantTag.select('restaurant_tags.*, (COALESCE(rtr_subquery.rtr_count, 0) +
                                                        COALESCE(pt_subquery.pt_count, 0)) AS total_restaurants').
      joins("LEFT JOIN (#{rtr_subquery}) AS rtr_subquery ON restaurant_tags.id = rtr_subquery.restaurant_tag_id").
      joins("LEFT JOIN (#{pt_subquery}) AS pt_subquery ON restaurant_tags.id = pt_subquery.restaurant_tag_id").
      where(filter_query_for_tag_ids(restaurant_tag_ids)).
      order('total_restaurants DESC')

    new_data = records.map do |record|
      RestaurantTagsTotal.new(city_id: city_id, restaurant_tag_id: record.id,
                              total_restaurants: record.total_restaurants)
    end
    Retriable.retriable on: [ActiveRecord::Deadlocked], tries: 10 do
      RestaurantTagsTotal.import! new_data, on_duplicate_key_update: %i[total_restaurants], raise_error: true
    end
  end
rescue StandardError => e
  APMErrorHandler.report e
  raise e
end