Class: Admin::RestaurantsController

Inherits:
BaseController show all
Includes:
DefaultErrorContainer, PaginationParamConcern
Defined in:
app/controllers/admin/restaurants_controller.rb

Constant Summary collapse

CONNECTION_TIMEOUT_ERROR =
'Connection time out, Cannot Load Menu Service'

Constants inherited from BaseController

BaseController::INTERNAL_SERVER_ERROR_MESSAGE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from DefaultErrorContainer

#error, #error_message_simple, #merge_errors

Methods inherited from BaseController

#destroy_session, #identity_cache_memoization, #sign_in_page, #user_developer_session

Methods included from LogrageCustomLogger

#append_info_to_payload

Methods included from AdminHelper

#dynamic_pricings_formatter, #link_to_admin_reservations_path_by_id, #link_to_admin_restaurants_path_by_id, #link_to_log, #optional_locales, #optional_locales_with_labels, #staff_signed_in?

Methods included from UpdateLocaleConcern

#setup_locale

Methods inherited from ApplicationController

#after_sign_in_path_for, #after_sign_out_path_for, #default_url_options, #identity_cache_memoization, #render_not_found, #routing_error, search_params_key=

Methods included from ControllerHelpers

#check_boolean_param, #get_banners, #inventory_params, #reservation_params

Instance Attribute Details

#restaurantObject (readonly)

Returns the value of attribute restaurant.



23
24
25
# File 'app/controllers/admin/restaurants_controller.rb', line 23

def restaurant
  @restaurant
end

Instance Method Details

#award_tagsObject



720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# File 'app/controllers/admin/restaurants_controller.rb', line 720

def award_tags
  awards = RestaurantTag.where('title_en LIKE ? OR title_en LIKE ?', 'AwardBadge%', 'AwardType%').
    where('country_id = ? OR country_id IS NULL', get_country_id).
    order(title_en: :asc)

  last_award_ids = awards.pluck(:id).join
  etag = "#{self.class}:award_tags:#{get_country_id}:#{awards.cache_key}:#{last_award_ids}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(etag) do
    awards.map do |r|
      { id: r.id, name: r.title_format(:en), category: r.category }
    end
  end

  render json: json
end

#cached_dataObject



1195
1196
1197
# File 'app/controllers/admin/restaurants_controller.rb', line 1195

def cached_data
  @restaurant
end

#check_inventory_statusObject

this is an API end point to check whether restaurant blocked the inventory on that date, or when inventory is empty, seat is full



1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
# File 'app/controllers/admin/restaurants_controller.rb', line 1143

def check_inventory_status
  query = params.require(:reservation)
  date = query.require(:date)
  start_time = query.require(:start_time)
  adult = query.require(:adult)
  kids = query.fetch(:kids, 0)

  date = date.to_date unless date.is_a?(Date)

  restaurant = Restaurant.fetch params.require(:restaurant_id)
  inv_checker = InvCheckerFactory.new(restaurant.id, restaurant.time_zone).create_inv_checker_service
  if inv_checker.bookable?(date: date, start_time: start_time, adult: adult.to_i, kids: kids.to_i)
    render json: { available: true, message: nil }
  else
    message = inv_checker.check_unavailability_reason(date: date, start_time: start_time)
    render json: { available: false, message: message }
  end
end

#checked_award_tagsObject



739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
# File 'app/controllers/admin/restaurants_controller.rb', line 739

def checked_award_tags
  restaurant_id = params[:restaurant_id]

  awards = RestaurantTag.joins(:restaurant_tags_restaurants).
    where('restaurant_tags.title_en LIKE ? OR restaurant_tags.title_en LIKE ?', 'AwardBadge%', 'AwardType%').
    where(restaurant_tags_restaurants: { restaurant_id: restaurant_id }).
    order(title_en: :asc)

  last_award_ids = awards.pluck(:id).join
  etag = "#{self.class}:award_tags:#{restaurant_id}:#{awards.cache_key}:#{last_award_ids}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(etag) do
    awards.map do |r|
      { id: r.id, name: r.title_format(:en), category: r.category }
    end
  end

  render json: json
end

#checked_cuisine_tagsObject



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'app/controllers/admin/restaurants_controller.rb', line 388

def checked_cuisine_tags
  restaurant_id = params[:restaurant_id]

  cuisines = RestaurantTag.joins(:restaurant_tags_restaurants).
    where('restaurant_tags.title_en LIKE ?', 'Cuisine%').
    where(restaurant_tags_restaurants: { restaurant_id: restaurant_id }).
    order(title_en: :asc)

  last_cuisine_ids = cuisines.pluck(:id).join
  etag = "#{self.class}:cuisine_tags:#{cuisines.cache_key}:#{last_cuisine_ids}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(etag) do
    cuisines.map do |r|
      { id: r.id, name: r.title_format(:en) }
    end
  end

  render json: json
end

#checked_dining_style_tagsObject



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'app/controllers/admin/restaurants_controller.rb', line 427

def checked_dining_style_tags
  restaurant_id = params[:restaurant_id]
  dining_styles = RestaurantTag.joins(:restaurant_tags_restaurants).
    where('restaurant_tags.title_en LIKE ?', 'DiningStyle%').
    where(restaurant_tags_restaurants: { restaurant_id: restaurant_id }).
    order(title_en: :asc)

  last_dining_style_ids = dining_styles.pluck(:id).join
  etag = "#{self.class}:dining_style_tags:#{dining_styles.cache_key}:#{last_dining_style_ids}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(etag) do
    dining_styles.map { |r| { id: r.id, name: r.title_format(:en) } }
  end

  render json: json
end

#checked_facility_tagsObject



482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'app/controllers/admin/restaurants_controller.rb', line 482

def checked_facility_tags
  restaurant_id = params[:restaurant_id]
  facilities = RestaurantTag.joins(:restaurant_tags_restaurants).
    where('restaurant_tags.title_en LIKE ?', 'Facility%').
    where(restaurant_tags_restaurants: { restaurant_id: restaurant_id }).
    order(title_en: :asc)

  last_facility_ids = facilities.pluck(:id).join
  etag = "#{self.class}:facility_tags:#{facilities.cache_key}:#{last_facility_ids}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(etag) do
    facilities.map do |r|
      { id: r.id, name: r.title_format(:en) }
    end
  end

  render json: json
end

#checked_location_tagsObject



698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
# File 'app/controllers/admin/restaurants_controller.rb', line 698

def checked_location_tags
  restaurant_id = params[:restaurant_id]

  locations = RestaurantTag.joins(:restaurant_tags_restaurants).
    where('restaurant_tags.title_en LIKE ? OR restaurant_tags.title_en LIKE ? OR restaurant_tags.title_en LIKE ? OR restaurant_tags.title_en LIKE ? OR restaurant_tags.title_en LIKE ?', 'Location%', 'PopularZone%', 'ShoppingMall%', 'MrtRoute%', 'BtsRoute%').
    where(restaurant_tags_restaurants: { restaurant_id: restaurant_id }).
    order(title_en: :asc)

  last_location_ids = locations.pluck(:id).join
  etag = "#{self.class}:location_tags:#{locations.cache_key}:#{last_location_ids}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(etag) do
    locations.map do |r|
      { id: r.id, name: "#{r.title_format(:en)} - #{r.category}" }
    end
  end

  render json: json
end

#clear_compact_restaurant_cacheObject



1123
1124
1125
1126
1127
1128
# File 'app/controllers/admin/restaurants_controller.rb', line 1123

def clear_compact_restaurant_cache
  restaurant_id = params.require(:restaurant_id)
  Restaurant.find(restaurant_id).touch
  CleanCompactRestaurantCacheWorker.perform_async(restaurant_id)
  render json: { success: true }
end

#clear_restaurant_inventory_cacheObject



1118
1119
1120
1121
# File 'app/controllers/admin/restaurants_controller.rb', line 1118

def clear_restaurant_inventory_cache
  Restaurants::ClearInventoryCacheWorker.perform_async(params.require(:restaurant_id))
  render json: { success: true }
end

#clear_restaurant_ui_cacheObject



1113
1114
1115
1116
# File 'app/controllers/admin/restaurants_controller.rb', line 1113

def clear_restaurant_ui_cache
  Restaurants::ClearUiCacheWorker.perform_async(params.require(:restaurant_id), true)
  render json: { success: true }
end

#create_test_bookingObject



964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
# File 'app/controllers/admin/restaurants_controller.rb', line 964

def create_test_booking
  voucher_group = VoucherGroup.find_or_create_by!(name: 'Voucher Test')
  currency_code = restaurant.default_currency || Country::THAI_CURRENCY_CODE

  voucher = Voucher.create!(
    voucher_group: voucher_group,
    amount_cents: 20_00,
    amount_cap_currency: currency_code,
    amount_currency: currency_code,
    currency_code: currency_code,
    min_total_price_currency: currency_code,
    expiry_date: (Date.today + 30.days),
    name: "Voucher test for #{restaurant.name}",
    voucher_code: Voucher.generate_voucher_code,
    quota: 1,
    user_id: 72_408,
    restaurant_id: restaurant.id,
  )

  [
    {
      user_id: 72_408,
      special_request: [
        'กดปุ่ม Arrived (สถานะจาก Pending Arrival จะถูกเปลี่ยนเป็น Arrived)',
        'Scenario 1: When customers arrive at the restaurant',
        'Click “Arrived” button, then the booking status will be updated from “”Pending Arrival” to “Arrived”',
      ].join("\n"),
      start_time: Reservation::PERIODS[64..76].sample,
    },
    {
      user_id: 72_409,
      special_request: [
        'สถานการณ์ที่ 2 เมื่อลูกค้าไม่แสดงตัว',
        'กดปุ่ม No Show (สถานะจาก Pending Arrival จะถูกเปลี่ยนเป็น No Show)',
        'Scenario 2: When customers do not show up and does not inform the restaurant',
        'Click “No Show” button, then the booking status will update form “”Pending Arrival” to “No Show”',
      ].join("\n"),
      start_time: Reservation::PERIODS[64..76].sample,
    },
    {
      user_id: 72_410,
      special_request: [
        'สถานการณ์ที่ 3 เมื่อลูกค้าขอ Cancel',
        'กดปุ่มแก้ไข และเปลี่ยนสถานะจาก Pending Arrival เป็น Cancel เพื่อทำการยกเลิก',
        'Scenario 3: When customers call or email the restaurant to cancel their booking',
        'first click the “Edit” button, then select  “Cancel” in the drop down menu in the top right corner of the page. Then click “Update” the booking status will change to Cancel',
      ].join("\n"),
      start_time: Reservation::PERIODS[64..76].sample,
    },
    {
      user_id: 72_411,
      special_request: [
        'สถานการณ์ที่ 4 เมื่อลูกค้าขอเปลี่ยนเวลา',
        'กดปุ่มแก้ไข แล้วเปลี่ยนเวลาเป็น19.00 หลังจากนั้นกดปุ่ม update',
        'Scenario 4: When customers want to change the time of the booking',
        'Click “Edit” button and change the new customer arrival time for the customer then click “Update” the booking detail will change to 19.00',
      ].join("\n"),
      start_time: '18:00',
    },
    {
      user_id: 72_411,
      special_request: 'Scenario 5: Reservation with voucher',
      start_time: '18:00',
      vouchers: [voucher],
    },
  ].each do |data|
    reservation = Reservation.create! user_id: data[:user_id],
                                      restaurant_id: restaurant.id,
                                      date: Faker::Date.rand_in_range(Date.tomorrow, 1.month.from_now.to_date),
                                      start_time: data[:start_time],
                                      adult: Faker::Number.between(from: restaurant.min_party_size,
                                                                   to: restaurant.largest_table),
                                      kids: 0,
                                      special_request: data[:special_request],
                                      active: true,
                                      ack: true,
                                      channel: Channel.manual.first,
                                      created_by: :admin
     = HhPackage::ReservationPackages::Metadata.from_reservation(reservation)
    .package_params = [{ id: restaurant.restaurant_packages.sample.id, quantity: 1 }]
    reservation.property.package = .generate
    reservation.property.save!
    reservation.assign_charged_data
    reservation.save!
    next if data[:vouchers].blank?

    data[:vouchers].each do |voucher|
      reservation.vouchers << voucher
    end
  end
  msg = 'Reservations created successfully'
  redirect_back fallback_location: back_fallback_location, notice: msg
rescue StandardError => e
  APMErrorHandler.report(e)
  msg = 'Something went wrong, please try again. If this problem persist, just message tech team'
  redirect_back fallback_location: back_fallback_location, alert: msg
end

#cuisine_tagsObject



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'app/controllers/admin/restaurants_controller.rb', line 369

def cuisine_tags
  cuisines = RestaurantTag.where('title_en LIKE ?', 'Cuisine%').
    where('country_id = ? OR country_id IS NULL', get_country_id).
    order(title_en: :asc)

  last_cuisine_ids = cuisines.pluck(:id).join
  etag = "#{self.class}:cuisine_tags:#{cuisines.cache_key}:#{last_cuisine_ids}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(etag) do
    cuisines.map do |r|
      { id: r.id, name: r.title_format(:en) }
    end
  end

  render json: json
end

#delete_tncObject



1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
# File 'app/controllers/admin/restaurants_controller.rb', line 1130

def delete_tnc
  tnc_id = params[:tnc_id]

  tnc = Restaurants::Tc.find tnc_id

  tnc.destroy

  redirect_to edit_admin_restaurant_path(params[:restaurant_id]),
              notice: 'Restaurant tnc deleted'
end

#dining_style_tagsObject



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'app/controllers/admin/restaurants_controller.rb', line 410

def dining_style_tags
  dining_styles = RestaurantTag.where('title_en LIKE ?', 'DiningStyle%').
    where('country_id = ? OR country_id IS NULL', get_country_id).
    order(title_en: :asc)

  last_dining_style_ids = dining_styles.pluck(:id).join
  etag = "#{self.class}:dining_style_tags:#{dining_styles.cache_key}:#{last_dining_style_ids}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(etag) do
    dining_styles.map { |r| { id: r.id, name: r.title_format(:en) } }
  end

  render json: json
end

#downloadObject



268
269
270
271
272
273
# File 'app/controllers/admin/restaurants_controller.rb', line 268

def download
  user = current_user.presence || User.new(email: SAIQUL_EMAIL)
  RestaurantListWorker.perform_async([user.email])
  message = 'System is generating the excel file, please check your email within few minutes'
  redirect_back fallback_location: back_fallback_location, notice: message
end

#duplicateObject



1107
1108
1109
1110
1111
# File 'app/controllers/admin/restaurants_controller.rb', line 1107

def duplicate
  Restaurants::DuplicateServiceWorker.perform_async(params.require(:restaurant_id))
  render json: { success: true,
                 message: 'System is processing your request, please refresh in few minutes to see new generated restaurant' }
end

#editObject



865
866
867
868
869
870
871
872
873
874
875
876
877
# File 'app/controllers/admin/restaurants_controller.rb', line 865

def edit
  set_meta_tags title: "Edit #{@restaurant&.name_en}"
  @restaurant.build_restaurant_external if @restaurant.restaurant_external.blank?
  @restaurant.build_line if @restaurant.line.blank?
  @restaurant.build_tnc if @restaurant.tnc.blank?
  @restaurant.build_order_now if @restaurant.order_now.blank?
  @restaurant.build_google_review if @restaurant.google_review.blank?

  # check_menu_service(@restaurant) # moved to menu v3

  set_required_vars_to_edit_restaurant
  set_available_competitors
end

#export_catalogObject

for netcore team app.clickup.com/t/86cywmdbq



276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'app/controllers/admin/restaurants_controller.rb', line 276

def export_catalog
  attachment = Attachment.find_by(report_type: 'restaurants_catalog')

  unless attachment&.excel&.file&.exists?
    return render json: { message: 'Restaurants Catalog is missing' }
  end

  excel_url = attachment.excel_url
  excel_url = "#{Figaro.env.HH_HOST_URL!}#{excel_url}" unless excel_url.include? 'http'

  redirect_to excel_url
rescue StandardError
  render json: { error: 'Unexpected error occurred while exporting catalog.' }
end

#facility_tagsObject



446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'app/controllers/admin/restaurants_controller.rb', line 446

def facility_tags
  facilities = RestaurantTag.where('title_en LIKE ?', 'Facility%').
    where('country_id = ? OR country_id IS NULL', get_country_id).
    order(title_en: :asc)

  last_facility_ids = facilities.pluck(:id).join
  etag = "#{self.class}:facility_tags:#{facilities.cache_key}:#{last_facility_ids}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(etag) do
    facilities.map do |r|
      { id: r.id, name: r.title_format(:en) }
    end
  end

  render json: json
end

#force_update_supplier_inventoryObject



123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'app/controllers/admin/restaurants_controller.rb', line 123

def force_update_supplier_inventory
  if restaurant.use_third_party_inventory?
    inventory_source = restaurant.selected_inventory_model
    vendor_name = inventory_source.name.delete_prefix('Inventory').camelize
    worker_class_name = "Vendors::#{vendor_name}::RestaurantsInventorySyncSchedulerWorker"
    worker_class_name.constantize.perform_async(restaurant.id, params[:trigger_type])
  else
    return render json: { error: 'Unsupported inventory source' }, status: :bad_request
  end

  redirect_to admin_restaurant_inventories_path(restaurant.id),
              notice: "Force update worker triggered for #{inventory_source} restaurant with ID #{restaurant.id}."
end

#heat_mapObject



1162
1163
1164
1165
1166
# File 'app/controllers/admin/restaurants_controller.rb', line 1162

def heat_map
  @locations = Restaurant.active.not_expired.where.not(lat: nil, lng: nil).pluck(:lat, :lng)
  @title = 'Restaurant Location Heat Map'
  render 'admin/users/heat_map'
end

#indexObject



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
54
55
56
57
58
59
60
# File 'app/controllers/admin/restaurants_controller.rb', line 27

def index
  respond_to do |format|
    format.html do
      set_meta_tags title: 'Admin restaurant list'
      valid_users = %w[saiqulhaq ravi surasit]
      @show_clear_cache_btn = staff_signed_in? && valid_users.select do |email|
        current_user.email.include?(email)
      end.present?
      @users = User.where(is_account_manager: true).order('username ASC')
    end

    format.json do
      self.default_per_page = 100
      restaurants = Restaurant.includes(:translations, :user,
                                        :restaurant_info, :restaurant_tags,
                                        :primary_tags,
                                        owner: %i[managers],
                                        seo: %i[translations])

      restaurants = if params[:q].present?
                      apply_search(restaurants, page_param, per_page_param)
                    else
                      restaurants.page(page_param).per(per_page_param).order('id DESC')
                    end

      render json: restaurants,
             meta: {
               total_restaurants: Restaurant.count,
             },
             each_serializer: Restaurants::AdminSerializer,
             adapter: :json
    end
  end
end

#inventoriesObject



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
119
120
121
# File 'app/controllers/admin/restaurants_controller.rb', line 62

def inventories
  restaurant_id = params.require(:restaurant_id)

  # Eager load related data to avoid N+1 queries
  @restaurant = Restaurant.includes(
    :inventory_source,
    all_restaurant_packages: :package,
  ).find(restaurant_id)

  if params[:date].present?
    date = params[:date].to_date

    inv_class = @restaurant.selected_inventory_model

    if inv_class.present?
      # Fetch inventories in one query
      @package_inventory = {}

      @inventories = inv_class.where(date: date, restaurant_id: restaurant_id).default_order

      # Fetch take-away inventories if applicable
      @inventory_take_aways = if @restaurant.has_delivery_inventories?
                                InventoryTakeAway.where(date: date,
                                                        restaurant_id: restaurant_id).default_order
                              else
                                []
                              end

      # Initialize inventory checkers once
      inv_checker_service = InvCheckerFactory.new(@restaurant.id, @restaurant.time_zone)
      @inv_checker_for_dine_in = inv_checker_service.create_inv_checker_service.tap do |checker|
        checker.for_dine_in = true
        checker.for_delivery = false
      end

      @inv_checker_for_delivery = inv_checker_service.create_inv_checker_service.tap do |checker|
        checker.for_dine_in = false
        checker.for_delivery = true
      end

      # Preload package availability data for performance optimization
      @dine_in_packages = @restaurant.all_restaurant_packages.valid_to_have_agendas.select do |rp|
        rp.package.for_dine_in?
      end
      @take_away_packages = @restaurant.all_restaurant_packages.valid_to_have_agendas.select do |rp|
        rp.package.for_delivery?
      end
    end
  else
    # Restaurant overview
    inv_checker = Inventory::InvCheckerHungryHubService.new(@restaurant, 'Asia/Bangkok')
    inv_checker.for_dine_in = true
    inv_checker.for_delivery = false
    @inv_checker_dine_in_cache_keys = inv_checker.dine_in_cache_keys

    inv_checker.for_dine_in = false
    inv_checker.for_delivery = true
    @inv_checker_take_away_cache_keys = inv_checker.take_away_cache_keys
  end
end

#inventory_sourcesObject



465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'app/controllers/admin/restaurants_controller.rb', line 465

def inventory_sources
  inv_sources = InventorySource.all

  etag = "#{self.class}:inventory_sources:#{inv_sources.cache_key}"
  cache_key = "inventory_sources_list_#{etag}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(cache_key) do
    inv_sources.map do |r|
      { id: r.id, inv_source: r.inv_source }
    end
  end

  render json: json
end

#location_primary_tagsObject



663
664
665
666
667
668
669
670
671
672
673
674
675
# File 'app/controllers/admin/restaurants_controller.rb', line 663

def location_primary_tags
  locations = RestaurantTag.where(
    'title_en LIKE ? OR title_en LIKE ? OR title_en LIKE ? OR title_en LIKE ? OR title_en LIKE ?', 'Location%', 'PopularZone%', 'ShoppingMall%', 'MrtRoute%', 'BtsRoute%'
  )
  return unless stale_etag? locations, template: false

  json = Rails.cache.fetch("#{self.class}:location_tags:#{locations.cache_key}") do
    locations.map do |r|
      { id: r.id, name: "#{r.title_format(:en)} - #{r.category}" }
    end
  end
  render json: json
end

#location_tagsObject



677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# File 'app/controllers/admin/restaurants_controller.rb', line 677

def location_tags
  locations = RestaurantTag.where(
    'title_en LIKE ? OR title_en LIKE ? OR title_en LIKE ? OR title_en LIKE ? OR title_en LIKE ?', 'Location%', 'PopularZone%', 'ShoppingMall%', 'MrtRoute%', 'BtsRoute%'
  ).
    where('country_id = ? OR country_id IS NULL', get_country_id).
    order(title_en: :asc)

  last_location_ids = locations.pluck(:id).join
  etag = "#{self.class}:location_tags:#{locations.cache_key}:#{last_location_ids}"

  return unless stale?(etag: etag, template: false)

  json = Rails.cache.fetch(etag) do
    locations.map do |r|
      { id: r.id, name: "#{r.title_format(:en)} - #{r.category}" }
    end
  end

  render json: json
end

#loginObject



1087
1088
1089
1090
# File 'app/controllers/admin/restaurants_controller.rb', line 1087

def 
   :owner, Restaurant.find(params[:restaurant_id]).owner
  redirect_to 
end

#login_partnerObject



1097
1098
1099
1100
1101
1102
1103
1104
1105
# File 'app/controllers/admin/restaurants_controller.rb', line 1097

def 
  service = StaffService::TemporaryAccess.new(params.require(:restaurant_id))
  service.call
  if service.success?
    render json: { success: true, data: service.result }
  else
    render json: { success: false, message: service.errors.full_messages.uniq.to_sentence }
  end
end

#login_v2Object



1092
1093
1094
1095
# File 'app/controllers/admin/restaurants_controller.rb', line 1092

def 
   :dashboard_v2_owner, Restaurant.find(params[:restaurant_id]).owner
  redirect_to dashboard_v2_root_path
end

#namesObject



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'app/controllers/admin/restaurants_controller.rb', line 347

def names
  if params[:locale] == 'cn'
    params[:locale] = 'en'
    I18n.locale = :en
  end
  page = params[:page].to_i
  per_page = params[:per_page].to_i

  cache_key = "restaurant-names:#{Restaurant.maximum(:updated_at)}#{I18n.locale}:#{params[:country_id]}:#{page}:#{per_page}"
  restaurants = Rails.cache.fetch(cache_key) do
    data = if params[:country_id].blank? || params[:country_id] == 'null'
             Restaurant.all.page(page).per(per_page)
           else
             Restaurant.all.where(country_id: params[:country_id]).page(page).per(per_page)
           end
    data.includes(:translations).where(deleted_at: nil).find_each.map do |r|
      { id: r.id, value: r.id, label: r.name, name: r.name_en }
    end.as_json
  end
  render json: restaurants
end

#newObject



1062
1063
1064
1065
# File 'app/controllers/admin/restaurants_controller.rb', line 1062

def new
  @restaurant = Restaurant.new
  @account_managers = User.where(is_account_manager: true)
end

#primary_tags(restaurant_id, tag_id) ⇒ Object



659
660
661
# File 'app/controllers/admin/restaurants_controller.rb', line 659

def primary_tags(restaurant_id, tag_id)
  PrimaryTag.where(restaurant_id: restaurant_id, restaurant_tag_id: tag_id)
end

#restaurant_package_listObject

Returns all active restaurant packages with postpaid pricing models for Google Reserve. Used for Google Reserve package selection UI.



169
170
171
172
# File 'app/controllers/admin/restaurants_controller.rb', line 169

def restaurant_package_list
  data = VendorsService::GoogleReserve::PackageService.restaurant_package_lists(restaurant)
  render json: { success: true, data: data }
end

#restaurant_translation_statusObject

Check status of full restaurant translation job



1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
# File 'app/controllers/admin/restaurants_controller.rb', line 1378

def restaurant_translation_status
  translation_id = params[:translation_id]

  if translation_id.blank?
    render json: { success: false, message: 'Translation ID is required.' },
           status: :unprocessable_entity
    return
  end

  begin
    redis_key = "restaurant_translation:#{translation_id}"
    result_json = $persistent_redis.with { |redis| redis.get(redis_key) }

    if result_json.nil?
      # Job is still processing or ID is invalid
      render json: {
        success: true,
        status: 'processing',
        message: 'Translation is still in progress...',
      }, status: :ok
    else
      result = JSON.parse(result_json)

      if result['status'] == 'completed'
        render json: {
          success: true,
          status: 'completed',
          translations: result['translations'],
          message: result['message'],
          completed_at: result['completed_at'],
        }, status: :ok
      elsif result['status'] == 'failed'
        render json: {
          success: false,
          status: 'failed',
          error: result['error'],
          failed_at: result['failed_at'],
        }, status: :unprocessable_entity
      end
    end
  rescue StandardError => e
    APMErrorHandler.report(e, context: { translation_id: translation_id })
    render json: {
      success: false,
      message: "Failed to check translation status: #{e.message}",
    }, status: :internal_server_error
  end
end

#rwg_e2e_package_listsObject

Returns Google Reserve E2E package list for a restaurant. Responds with package data and meta info if Google Reserve is active for E2E.



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'app/controllers/admin/restaurants_controller.rb', line 141

def rwg_e2e_package_lists
  respond_to do |format|
    format.html
    format.json do
      if restaurant.google_reserve.blank?
        return render json: { success: false, message: 'google reserve restaurant not found', data: [],
                              meta: [] }
      end

      unless restaurant.google_reserve.e2e
        return render json: { success: false, message: 'google reserve restaurant not active for e2e', data: [],
                              meta: [] }
      end

      meta = [{ select_top3_package: restaurant.google_reserve.select_top3_package }]
      google_reserve_package_list = restaurant.google_reserve_packages
      return render json: { success: true, message: '', data: [], meta: meta } if google_reserve_package_list.blank?

      data = VendorsService::GoogleReserve::PackageService.google_reserve_package(google_reserve_package_list)&.compact
      render json: { success: true, data: data, meta: meta }
    end
  end
end

#rwg_e2e_package_saveObject

Saves Google Reserve E2E package selection for a restaurant. Handles both top-3 package selection and custom package data import. Validates input and delegates to service for business logic and persistence.



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
# File 'app/controllers/admin/restaurants_controller.rb', line 226

def rwg_e2e_package_save
  required_keys = %i[
    restaurant_package_id
    package_id
    package_type
    force_prepayment
  ]

  optional_keys = %i[
    custom_package_name
    custom_package_description
    ai_generated_package_description
  ]

  permit_keys = required_keys + optional_keys

  permitted = params.tap do |p|
    p.require(:select_top3_package)
  end.permit(:select_top3_package, data: permit_keys)

  is_select_top3_package = ActiveModel::Type::Boolean.new.cast(permitted[:select_top3_package])

  unless is_select_top3_package && permitted[:data].blank?
    # unless we have to generate top3 packages first time (for which data sent is empty array)
    params.require(:data).each { |item| required_keys.each { |k| item.require(k) } }
  end

  result = VendorsService::GoogleReserve::PackageService.save_google_reserve_packages(
    restaurant, is_select_top3_package, permitted[:data]
  )

  if result
    render json: { success: true, message: 'Google Reserve Package saved successfully' }
  else
    render json: { success: false,
                   message: 'Failed to save Google Reserve packages. Please check the data and try again.' }
  end
rescue StandardError => e
  APMErrorHandler.report('Failed to save Google Reserve Package', restaurant_id: restaurant.id, error: e)
  render json: { success: false, message: e.message }
end

#rwg_e2e_regenerate_pkg_desc_with_aiObject

Regenerates package description using AI for Google Reserve E2E packages. Returns AI-generated description or proper error response.



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
# File 'app/controllers/admin/restaurants_controller.rb', line 179

def rwg_e2e_regenerate_pkg_desc_with_ai
  restaurant_package_id = params.require(:restaurant_package_id)
  ai_result = VendorsService::GoogleReserve::DescriptionGeneratorService.new(restaurant_package_id).call

  if ai_result.success?
    ai_generated_description = ai_result.data&.dig(:description)

    if ai_generated_description.present?
      render json: {
        success: true,
        data: { description: ai_generated_description },
        message: 'AI description generated successfully',
      }
    else
      raise 'AI service returned empty description'
    end
  else
    error_details = ai_result.errors&.join(', ') || ai_result.message || 'Unknown error occurred'
    raise "Failed to generate AI description: #{error_details}"
  end
rescue StandardError => e
  error_message = 'AI description generation failed'
  error_context = {
    restaurant_id: restaurant.id,
    restaurant_package_id: params[:restaurant_package_id],
    error: e.message,
    error_class: e.class.name,
    backtrace: e.backtrace&.first(5),
  }

  BUSINESS_LOGGER.set_business_context({ restaurant_id: restaurant.id })
  BUSINESS_LOGGER.error(error_message, error_context)
  APMErrorHandler.report(error_message, error_context)

  render json: {
    success: false,
    data: nil,
    message: e.message,
  }, status: :unprocessable_entity
end

#seoObject



1168
1169
1170
1171
1172
1173
1174
1175
1176
# File 'app/controllers/admin/restaurants_controller.rb', line 1168

def seo
  if restaurant.seo.blank?
    restaurant.build_seo
    restaurant.seo.save!
  end

  render json: restaurant.seo,
         serializer: ::SeoCpt::Restaurants::AdminSerializer
end

#seo_import_csvObject



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
# File 'app/controllers/admin/restaurants_controller.rb', line 291

def seo_import_csv
  arg = params.require(:restaurant).permit(:import_csv)[:import_csv]

  not_found = []
  begin
    CSV.foreach(arg.tempfile,
                force_quotes: true, encoding: Encoding::UTF_8,
                headers: true, col_sep: "\t", liberal_parsing: true) do |row|
      restaurant_id = row['id']
      title_th = row['title_th']
      title_en = row['title_en']
      description_th = row['description_th']
      description_en = row['description_en']
      keywords_en = row['keywords_en']
      keywords_th = row['keywords_th']

      restaurant_description_th = row['restaurant_description_th']
      restaurant_description_en = row['restaurant_description_en']

      restaurant = Restaurant.find_by(id: restaurant_id)
      if restaurant.nil?
        not_found.push restaurant_id
        next
      end

      attributes = {
        title_th: title_th,
        title_en: title_en,
        description_en: description_en,
        description_th: description_th,
        keywords_th: keywords_th,
        keywords_en: keywords_en,
      }.select do |_key, value|
        value.present?
      end

      seo = restaurant.seo || restaurant.build_seo
      seo.update!(attributes) if attributes.present?

      restaurant_attributes = {
        misc_en: restaurant_description_en,
        misc_th: restaurant_description_th,
      }.select { |_key, value| value.present? }

      restaurant.update!(restaurant_attributes) if restaurant_attributes.present?

      Restaurants::ClearUiCacheWorker.perform_async(restaurant.id, true)
    end

    render json: { success: not_found.blank?, restaurant_not_found: not_found }
  rescue StandardError => e
    APMErrorHandler.report('Failed import restaurant TSV', e: e)
    render json: { success: false, restaurant_not_found: not_found, message: e.message }
  end
end

#translate_by_aiObject



1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
# File 'app/controllers/admin/restaurants_controller.rb', line 1211

def translate_by_ai
  restaurant = Restaurant.find_by(id: params[:restaurant_id])
  unless restaurant
    render json: { success: false, message: 'Restaurant not found.' }, status: :not_found
    return
  end

  source_language = params[:source_language] || 'en'
  target_languages = params[:target_languages] || []
  target_fields = params[:target_fields] || []
  only_blank_languages = params[:only_blank_languages] == true || params[:only_blank_languages] == 'true'
  only_blank_fields = params[:only_blank_fields] == true || params[:only_blank_fields] == 'true'

  # Only validate selections if blank field mode is NOT enabled
  if !only_blank_languages && target_languages.blank?
    render json: { success: false, message: 'Please select target languages or enable blank field detection.' },
           status: :unprocessable_entity
    return
  end

  if !only_blank_fields && target_fields.blank?
    render json: { success: false, message: 'Please select target fields or enable blank field detection.' },
           status: :unprocessable_entity
    return
  end

  begin
    # Generate unique translation ID for async processing
    translation_id = SecureRandom.uuid

    # Enqueue background job for async translation (prevents timeout for long text)
    Restaurants::AiTranslationWorker.perform_async(
      translation_id,
      restaurant.id,
      source_language,
      target_languages,
      target_fields,
      only_blank_languages,
      only_blank_fields,
    )

    # Return immediately with translation ID for status polling
    render json: {
      success: true,
      translation_id: translation_id,
      message: 'Translation job started. Use the translation_id to check status.',
    }, status: :accepted
  rescue StandardError => e
    APMErrorHandler.report(e, context: { restaurant_id: restaurant.id })
    render json: {
      success: false,
      message: "Failed to start translation: #{e.message}",
    }, status: :internal_server_error
  end
end

#translate_description_with_aiObject



1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
# File 'app/controllers/admin/restaurants_controller.rb', line 1199

def translate_description_with_ai
  restaurant = Restaurant.find_by(id: params[:restaurant_id])
  unless restaurant
    flash[:alert] = 'Restaurant not found.'
    redirect_to edit_admin_restaurant_path(restaurant.id)
    return
  end
  ::Restaurants::TranslateByAiWorker.perform_async(restaurant.id)
  flash[:notice] = "Generation AI for #{restaurant.name_en} has been initiated."
  redirect_to edit_admin_restaurant_path(restaurant.id)
end

#translate_field_by_aiObject

New method for per-field translation (doesn't save to database) Returns translated text only for filling form inputs



1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
# File 'app/controllers/admin/restaurants_controller.rb', line 1269

def translate_field_by_ai
  restaurant = Restaurant.find_by(id: params[:restaurant_id])
  unless restaurant
    render json: { success: false, message: 'Restaurant not found.' }, status: :not_found
    return
  end

  source_language = params[:source_language] || 'en'
  target_languages = params[:target_languages] || []
  field_name = params[:field_name]

  # Validate inputs
  if field_name.blank?
    render json: { success: false, message: 'Field name is required.' },
           status: :unprocessable_entity
    return
  end

  if target_languages.blank?
    render json: { success: false, message: 'Please select target languages.' },
           status: :unprocessable_entity
    return
  end

  # Get the source text from the request (not from database)
  source_text = params[:source_text]
  if source_text.blank?
    render json: { success: false, message: 'Source text is required.' },
           status: :unprocessable_entity
    return
  end

  begin
    # Generate unique translation ID
    translation_id = SecureRandom.uuid

    # Enqueue background job for async processing
    Restaurants::FieldTranslationWorker.perform_async(
      translation_id,
      source_text,
      field_name,
      source_language,
      target_languages,
    )

    # Return immediately with translation ID for status polling
    render json: {
      success: true,
      translation_id: translation_id,
      message: 'Translation job started. Use the translation_id to check status.',
    }, status: :accepted
  rescue StandardError => e
    APMErrorHandler.report(e, context: { restaurant_id: restaurant.id, field_name: field_name })
    render json: {
      success: false,
      message: "Failed to start translation: #{e.message}",
    }, status: :internal_server_error
  end
end

#translation_statusObject



1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
# File 'app/controllers/admin/restaurants_controller.rb', line 1329

def translation_status
  translation_id = params[:translation_id]

  if translation_id.blank?
    render json: { success: false, message: 'Translation ID is required.' },
           status: :unprocessable_entity
    return
  end

  begin
    redis_key = "field_translation:#{translation_id}"
    result_json = $persistent_redis.with { |redis| redis.get(redis_key) }

    if result_json.nil?
      # Job is still processing or ID is invalid
      render json: {
        success: true,
        status: 'processing',
        message: 'Translation is still in progress...',
      }, status: :ok
    else
      result = JSON.parse(result_json)

      if result['status'] == 'completed'
        render json: {
          success: true,
          status: 'completed',
          data: result['translations'],
          completed_at: result['completed_at'],
        }, status: :ok
      elsif result['status'] == 'failed'
        render json: {
          success: false,
          status: 'failed',
          error: result['error'],
          failed_at: result['failed_at'],
        }, status: :unprocessable_entity
      end
    end
  rescue StandardError => e
    APMErrorHandler.report(e, context: { translation_id: translation_id })
    render json: {
      success: false,
      message: "Failed to check translation status: #{e.message}",
    }, status: :internal_server_error
  end
end

#updateObject



879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
# File 'app/controllers/admin/restaurants_controller.rb', line 879

def update
  payload = params.require(:restaurant).permit!

  # if payload[:payment_provider_override].to_i == 0
  # means payment provider is not override, checkbox is unchecked
  # this related Override Global Level checkbox in edit restaurant page
  payload[:payment_provider] = nil if payload[:payment_provider_override].to_i == 0
  payload.delete(:payment_provider_override)

  # Deduplicate competitor_ids and remove blank values
  if payload[:competitor_ids].present?
    payload[:competitor_ids] = payload[:competitor_ids].reject(&:blank?).uniq
  end

  MyLocaleManager.available_locales.each do |locale|
    if payload[:"custom_text_#{locale}"].present?
      payload[:"custom_text_#{locale}"] = payload[:"custom_text_#{locale}"].to_s.upcase
    end
  end

  update_restaurant_google_reserve(payload)
  payload = google_reserve_params(payload)
  error_msg = []

  default_max_dine_in_booking_cutoff_time = AdminSetting.default_max_dine_in_booking_cutoff_time.to_i
  if payload[:dine_in_min_booking_time_in_advance].to_i < default_max_dine_in_booking_cutoff_time
    humanized_time = HungryHub::Time.human_readable_time(default_max_dine_in_booking_cutoff_time)
    error_msg.push("The maximum dine-in booking cutoff time is #{humanized_time} before the booking time.")
  end

  payload_inv_source = payload.require(:inventory_source).permit!

  restaurant_inventory_info = validate_restaurant_inventory_info(@restaurant, payload_inv_source)
  error_msg.push "Inventory Source Settings Error: #{restaurant_inventory_info.message}" unless restaurant_inventory_info.success?

  @restaurant.validate_commission_for_packages(payload[:commision])

  if @restaurant.errors.present?
    error_msg.push @restaurant.errors.full_messages
  end

  restaurant_operation = RestaurantCpt::Operations::SettingByOwner.call(payload.merge(id: @restaurant.id)) if error_msg.blank?
  if restaurant_operation&.success? && error_msg.blank?
    inv_source_operation = RestaurantCpt::Operations::SettingsInventorySource.call(payload_inv_source.merge(id: @restaurant.id))
    if !inv_source_operation.success?
      error_msg.push "Inventory source error: #{inv_source_operation['model']&.errors&.full_messages}"
    end

    if error_msg.present?
      return redirect_to edit_admin_restaurant_path(params[:id]), alert: error_msg.flatten.compact.uniq.to_sentence
    end

    unless params.key?(:seo)
      return redirect_to edit_admin_restaurant_path(params[:id]),
                         notice: 'Restaurant updated but missing SEO data'
    end

    # refresh restaurant view cache key
    @restaurant.refresh_view_cache_key

    payload_seo = params.require(:seo).permit!
    seo_operation = RestaurantCpt::Operations::SettingSeo.call(payload_seo.merge(id: @restaurant.seo.id))
    if seo_operation.success?
      return redirect_to edit_admin_restaurant_path(params[:id]), notice: 'Restaurant updated'
    else
      error_msg.push seo_operation['model']&.errors&.full_messages
      error_msg.push seo_operation['result.contract.default']&.errors&.full_messages
    end
  elsif restaurant_operation.present?
    error_msg.push restaurant_operation['model']&.errors&.full_messages
    error_msg.push restaurant_operation['error_message']
    error_msg.push restaurant_operation['result.contract.default']&.errors&.full_messages
  end

  payload['inventory_source'] = @restaurant.inventory_source

  flash.now[:alert] = error_msg.flatten.compact.uniq.to_sentence

  @restaurant.assign_attributes payload if error_msg.blank?
  # check_menu_service(@restaurant) # moved to menu v3
  set_required_vars_to_edit_restaurant
  set_available_competitors
  render 'edit'
end

#update_award_tagsObject



812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
# File 'app/controllers/admin/restaurants_controller.rb', line 812

def update_award_tags
  restaurant_id = params.require(:restaurant_id)
  award_tag_ids = params[:award_tag_ids]

  ActiveRecord::Base.transaction do
    tags_ids = award_tag_ids.reject(&:empty?)
    @restaurant.with_lock do
      exclude_tag_ids = @restaurant.restaurant_tags_restaurants.joins(:restaurant_tag).
        where('restaurant_tags.title_en LIKE ? OR restaurant_tags.title_en LIKE ?', 'AwardBadge%', 'AwardType%')

      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

    new_data = (tags_ids - primary_tags(restaurant_id, tags_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.bookable_and_not_expired?
    CleanCompactRestaurantCacheWorker.perform_async(@restaurant.id)

    EventDrivenWorkers::HhSearch::ProducerWorker.perform_async(
      EventDrivenClient::Constants::RESTAURANTS_TOPIC,
      EventDrivenClient::Constants::UPDATE_EVENT,
      @restaurant.id,
      { award_badges: {}, award_types: {} },
      { source: 'Admin::RestaurantsController#update_award_tags' },
    )
  end

  render json: {
    data: nil,
    message: 'Awards have been updated successfully',
    success: true,
  }, status: :accepted
rescue ActionController::ParameterMissing => e
  render json: { data: nil, message: e.message, success: false }
end

#update_cuisine_tagsObject



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
# File 'app/controllers/admin/restaurants_controller.rb', line 554

def update_cuisine_tags
  # Parameters: {"restaurant_id"=>"4619", "cuisine_tag_ids"=>["11"]}
  restaurant_id = params.require(:restaurant_id)
  cuisine_tag_ids = params[:cuisine_tag_ids]

  ActiveRecord::Base.transaction do
    tags_ids = cuisine_tag_ids.reject(&:empty?)
    @restaurant.with_lock do
      exclude_tag_ids = @restaurant.restaurant_tags_restaurants.joins(:restaurant_tag).
        where("restaurant_tags.title_en LIKE 'Cuisine:%'")

      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

    new_data = (tags_ids - primary_tags(restaurant_id, tags_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.bookable_and_not_expired?
    EventDrivenWorkers::HhSearch::ProducerWorker.perform_async(
      EventDrivenClient::Constants::RESTAURANTS_TOPIC,
      EventDrivenClient::Constants::UPDATE_EVENT,
      @restaurant.id,
      { cuisines: {} },
      { source: 'Admin::RestaurantsController#update_cuisine_tags' },
    )
  end

  render json: {
    data: nil,
    message: 'Sub Cuisines have been updated successfully',
    success: true,
  }, status: :accepted
rescue ActionController::ParameterMissing => e
  render json: { data: nil, message: e.message, success: false }
end

#update_dining_style_tagsObject



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
# File 'app/controllers/admin/restaurants_controller.rb', line 607

def update_dining_style_tags
  restaurant_id = params.require(:restaurant_id)
  dining_style_tag_ids = params[:dining_style_tag_ids]

  ActiveRecord::Base.transaction do
    tags_ids = dining_style_tag_ids.reject(&:empty?)
    @restaurant.with_lock do
      exclude_tag_ids = @restaurant.restaurant_tags_restaurants.joins(:restaurant_tag).
        where("restaurant_tags.title_en LIKE 'DiningStyle:%'")

      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

    new_data = (tags_ids - primary_tags(restaurant_id, tags_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.bookable_and_not_expired?
    EventDrivenWorkers::HhSearch::ProducerWorker.perform_async(
      EventDrivenClient::Constants::RESTAURANTS_TOPIC,
      EventDrivenClient::Constants::UPDATE_EVENT,
      @restaurant.id,
      { dining_styles: {} },
      { source: 'Admin::RestaurantsController#update_dining_style_tags' },
    )
  end

  render json: {
    data: nil,
    message: 'Sub Dining Styles have been updated successfully',
    success: true,
  }, status: :accepted
rescue ActionController::ParameterMissing => e
  render json: { data: nil, message: e.message, success: false }
end

#update_facility_tagsObject



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
# File 'app/controllers/admin/restaurants_controller.rb', line 503

def update_facility_tags
  restaurant_id = params.require(:restaurant_id)
  facility_tag_ids = params[:facility_tag_ids]

  ActiveRecord::Base.transaction do
    tags_ids = facility_tag_ids.reject(&:empty?)
    @restaurant.with_lock do
      exclude_tag_ids = @restaurant.restaurant_tags_restaurants.joins(:restaurant_tag).
        where("restaurant_tags.title_en LIKE 'Facility:%'")

      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

    new_data = (tags_ids - primary_tags(restaurant_id, tags_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.bookable_and_not_expired?
    EventDrivenWorkers::HhSearch::ProducerWorker.perform_async(
      EventDrivenClient::Constants::RESTAURANTS_TOPIC,
      EventDrivenClient::Constants::UPDATE_EVENT,
      @restaurant.id,
      { facilities: {} },
      { source: 'Admin::RestaurantsController#update_facility_tags' },
    )
  end

  render json: {
    data: nil,
    message: 'Facilities have been updated successfully',
    success: true,
  }, status: :accepted
rescue ActionController::ParameterMissing => e
  render json: { data: nil, message: e.message, success: false }
end

#update_field_translationsObject

Update only translation fields for a specific field



1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
# File 'app/controllers/admin/restaurants_controller.rb', line 1428

def update_field_translations
  restaurant = Restaurant.find_by(id: params[:restaurant_id])
  unless restaurant
    render json: { success: false, message: 'Restaurant not found.' }, status: :not_found
    return
  end

  translations = params[:translations] || {}

  if translations.blank?
    render json: { success: false, message: 'No translations provided.' },
           status: :unprocessable_entity
    return
  end

  begin
    # Update only the provided translation fields
    update_hash = {}
    translations.each do |field_key, value|
      # Validate field key format (e.g., "name_en", "misc_th")
      if field_key.match?(/\A[a-z_]+_(en|th|cn|zh|ru|ko|ja|ms|fr|de|es|id|vi|la|km)\z/)
        update_hash[field_key] = value
      end
    end

    if update_hash.blank?
      render json: { success: false, message: 'No valid translation fields provided.' },
             status: :unprocessable_entity
      return
    end

    # Update restaurant with only the translation fields
    restaurant.update!(update_hash)

    # Refresh view cache
    restaurant.refresh_view_cache_key

    # Clear UI cache
    Restaurants::ClearUiCacheWorker.perform_async(restaurant.id, true)

    render json: {
      success: true,
      message: "Successfully updated #{update_hash.keys.size} translation field(s)",
      updated_fields: update_hash.keys,
    }, status: :ok
  rescue ActiveRecord::RecordInvalid => e
    render json: {
      success: false,
      message: "Validation failed: #{e.message}",
    }, status: :unprocessable_entity
  rescue StandardError => e
    APMErrorHandler.report(e, context: { restaurant_id: restaurant.id, translations: translations })
    render json: {
      success: false,
      message: "Update failed: #{e.message}",
    }, status: :internal_server_error
  end
end

#update_location_tagsObject



761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
# File 'app/controllers/admin/restaurants_controller.rb', line 761

def update_location_tags
  restaurant_id = params.require(:restaurant_id)
  location_tag_ids = params[:location_tag_ids]

  ActiveRecord::Base.transaction do
    tags_ids = location_tag_ids.reject(&:empty?)
    @restaurant.with_lock do
      exclude_tag_ids = @restaurant.restaurant_tags_restaurants.joins(:restaurant_tag).
        where('restaurant_tags.title_en LIKE ? OR restaurant_tags.title_en LIKE ? OR restaurant_tags.title_en LIKE ? OR restaurant_tags.title_en LIKE ? OR restaurant_tags.title_en LIKE ?', 'Location%', 'PopularZone%', 'ShoppingMall%', 'MrtRoute%', 'BtsRoute%')

      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

    new_data = (tags_ids - primary_tags(restaurant_id, tags_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.bookable_and_not_expired?
    EventDrivenWorkers::HhSearch::ProducerWorker.perform_async(
      EventDrivenClient::Constants::RESTAURANTS_TOPIC,
      EventDrivenClient::Constants::UPDATE_EVENT,
      @restaurant.id,
      { locations: {} },
      { source: 'Admin::RestaurantsController#update_location_tags' },
    )
  end

  render json: {
    data: nil,
    message: 'Sub Places have been updated successfully',
    success: true,
  }, status: :accepted
rescue ActionController::ParameterMissing => e
  render json: { data: nil, message: e.message, success: false }
end

#update_primary_tagObject



1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
# File 'app/controllers/admin/restaurants_controller.rb', line 1067

def update_primary_tag
  tag_id = params.fetch(:restaurant_tag_id, 0).to_i

  # Check if the selected tag_id is for the empty field ("none" option)
  if tag_id.zero?
    # Remove all primary_tags with title_en LIKE "Cuisine:%"
    # @restaurant.primary_tags.joins(:restaurant_tag).where("title_en LIKE 'Cuisine:%'").delete_all
    @restaurant.touch
    render json: @restaurant, serializer: Restaurants::AdminSerializer
  else
    operation = PrimaryTagCpt::Operations::UpdateRelation.call(id: tag_id, restaurant_id: @restaurant.id)
    if operation.success?
      # @restaurant.restaurant_tags_restaurants.where(restaurant_id: @restaurant.id, restaurant_tag_id: tag_id).delete_all
      render json: operation['model.restaurant'], serializer: Restaurants::AdminSerializer
    else
      render json: { message: operation[OpCons::ERRORS].full_messages.to_sentence }
    end
  end
end

#update_skip_auto_tag_locationObject



1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
# File 'app/controllers/admin/restaurants_controller.rb', line 1178

def update_skip_auto_tag_location
  restaurant_id = params.require(:restaurant_id)
  is_skip_auto_tag_location = params.require(:is_skip_auto_tag_location)

  restaurant = Restaurant.find(restaurant_id)
  restaurant.update!(is_skip_auto_tag_location: is_skip_auto_tag_location)

  render json: { data: nil, message: 'Skip Auto Tag Location updated successfully', success: true }
rescue ActionController::ParameterMissing => e
  render json: { data: nil, message: e.message, success: false }
rescue ActiveRecord::RecordNotFound
  render json: { data: nil, message: 'Restaurant not found', success: false }
rescue StandardError => e
  APMErrorHandler.report e
  render json: { data: nil, message: 'Something went wrong', success: false }
end