Class: RestaurantService::UpdateTags

Inherits:
ApplicationService show all
Defined in:
app/services/restaurant_service/update_tags.rb

Instance Attribute Summary collapse

Attributes inherited from ApplicationService

#object

Instance Method Summary collapse

Methods inherited from ApplicationService

#execute

Constructor Details

#initialize(restaurant, tag_ids, tag_type) ⇒ UpdateTags

Returns a new instance of UpdateTags.



7
8
9
10
11
# File 'app/services/restaurant_service/update_tags.rb', line 7

def initialize(restaurant, tag_ids, tag_type)
  @restaurant = restaurant
  @tag_ids = tag_ids || []
  @tag_type = tag_type
end

Instance Attribute Details

#restaurantObject (readonly)

Returns the value of attribute restaurant.



5
6
7
# File 'app/services/restaurant_service/update_tags.rb', line 5

def restaurant
  @restaurant
end

#tag_idsObject (readonly)

Returns the value of attribute tag_ids.



5
6
7
# File 'app/services/restaurant_service/update_tags.rb', line 5

def tag_ids
  @tag_ids
end

#tag_typeObject (readonly)

Returns the value of attribute tag_type.



5
6
7
# File 'app/services/restaurant_service/update_tags.rb', line 5

def tag_type
  @tag_type
end

Instance Method Details

#execute!Object



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
43
44
45
46
47
48
49
50
51
52
# File 'app/services/restaurant_service/update_tags.rb', line 13

def execute!
  ActiveRecord::Base.transaction do
    tags_ids = tag_ids.reject(&:empty?)
    restaurant.with_lock do
      exclude_tag_ids = restaurant.restaurant_tags_restaurants.joins(:restaurant_tag).
        where('restaurant_tags.title_en LIKE ?', "#{tag_type}:%")

      exclude_tag_ids = exclude_tag_ids.where.not(restaurant_tag_id: tags_ids) if tags_ids.present?
      exclude_tag_ids = exclude_tag_ids.pluck(:restaurant_tag_id)

      if exclude_tag_ids.present?
        tags = RestaurantTagsRestaurant.where(restaurant_tag_id: exclude_tag_ids, restaurant_id: restaurant.id)
        tags.each do |rtr|
          rtr.restaurant&.refresh_view_cache_key
        end
        tags.delete_all if tags.count > 0
      end
    end

    primary_tag_ids = primary_tags(restaurant.id, tags_ids)
    new_data = (tags_ids - primary_tag_ids).map do |tag|
      restaurant.refresh_view_cache_key
      RestaurantTagsRestaurant.new(restaurant_tag_id: tag, restaurant_id: restaurant.id)
    end

    RestaurantTagsRestaurant.import! new_data, on_duplicate_key_update: %i[restaurant_id restaurant_tag_id],
                                               raise_error: true
  end

  restaurant.touch

  if restaurant.active_and_not_expired?
    trigger_search_update
  end

  ServiceResult.new(success: true, message: "#{tag_type.humanize} tags updated successfully")
rescue StandardError => e
  APMErrorHandler.report(e, restaurant_id: restaurant.id, tag_type: tag_type)
  ServiceResult.new(success: false, message: 'Failed to update tags', errors: [e.message])
end