Class: Api::V5::RestaurantsController

Inherits:
BaseController
  • Object
show all
Includes:
Concerns::Authorization, Concerns::GetRestaurantList, Concerns::InventoriesV4
Defined in:
app/controllers/api/v5/restaurants_controller.rb

Overview

Restaurants

Constant Summary

Constants inherited from BaseController

BaseController::CACHE_NAMESPACE, BaseController::INTERNAL_SERVER_ERROR_MESSAGE, BaseController::ResponseSchema

Instance Method Summary collapse

Methods inherited from BaseController

#identity_cache_memoization

Methods included from LogrageCustomLogger

#append_info_to_payload

Methods included from ResponseCacheConcern

#my_response_cache

Instance Method Details

#around_restaurantsObject



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'app/controllers/api/v5/restaurants_controller.rb', line 135

def around_restaurants
  restaurant = Restaurant.fetch params.require(:restaurant_id)
  cache_key = CityHash.hash32([self.class.to_s,
                               'around_restaurants',
                               restaurant.id,
                               Date.today,
                               MyLocaleManager.normalize_locale])
  if AdminSetting.enable_plumber.to_s == 'false'
    return render(json: { data: [], success: true, message: '' })
  end

  my_response_cache(cache_key, :json, public: true) do
    data = NearestRestaurant.find_by(restaurant_id: restaurant.id)

    collection = if data.present?
                   restaurant_ids = JSON.parse(data.nearest_restaurant_ids)
                   Restaurant.active.not_expired.where(id: restaurant_ids)
                 else
                   Restaurant.none
                 end

    filter = Api::V5::RestaurantsFilter.new(collection)

    options = {
      preview_mode: true,
      compact_mode: true,
    }

    filter.as_json(serialization_context, minor_version_param, options).merge(success: true, message: nil)
  rescue StandardError => e
    {
      success: false,
      message: "An error occurred: #{e.message}",
    }
  end
end

#available_dates_based_on_packagesObject



422
423
424
# File 'app/controllers/api/v5/restaurants_controller.rb', line 422

def available_dates_based_on_packages
  available_dates_based_on_packages_v4
end

#available_start_times_based_on_packagesObject



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'app/controllers/api/v5/restaurants_controller.rb', line 374

def available_start_times_based_on_packages
  return available_start_times_based_on_packages_v4 if minor_version_param == '4'
  if ENV['RAILS_ENV_REAL'] == 'staging' || Rails.env.development?
    raise 'This endpoint is not supported in this version'
  end

  restaurant = Restaurant.fetch params.require(:restaurant_id)
  adult = params.require(:adult).to_i
  kids = params.require(:kids).to_i
  date = params.require(:date)
  restaurant_package_ids = params.require(:restaurant_package_ids)

  inv_checker = create_inv_checker_instance(restaurant, restaurant_package_ids)

  invalid_date = false
  date_as_date = nil
  begin
    date_as_date = date.to_date
  rescue ArgumentError
    invalid_date = true
  end

  if invalid_date
    render json: { success: false, data: [], message: 'Invalid Date' }
  elsif date_as_date == Time.now_in_tz(restaurant.time_zone).to_date
    data = inv_checker.find_available_start_times(adult: adult, kids: kids, date: date)

    render json: {
      success: data.present?,
      data: data.sort,
      message: nil,
    }
  else
    cache_key = [self.class.to_s, action_name, restaurant.id, date,
                 adult, restaurant_package_ids, kids, for_dine_in?,
                 for_delivery?, order_now_param?].join(':')
    my_response_cache(cache_key, :json) do
      data = inv_checker.find_available_start_times(adult: adult, kids: kids, date: date)

      {
        success: data.present?,
        data: data.sort,
        message: nil,
      }.as_json
    end
  end
end

#blogger_reviewsObject



778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
# File 'app/controllers/api/v5/restaurants_controller.rb', line 778

def blogger_reviews
  resource = Restaurant.fetch params.require(:restaurant_id)

  cache_key = "#{CACHE_NAMESPACE}:#{self.class}:blogger_reviews:#{CityHash.hash32([I18n.locale, params,
                                                                                   resource.cache_key])}"
  my_response_cache cache_key, :json, public: true, public_expires_in: 24.hours do
    page_param = params.require(:page)
    per_page = page_param.fetch(:size, 100).to_i
    page = page_param.fetch(:number, 1).to_i

    reviews_filter = Api::V5::ReviewsFilter.new
    reviews_filter.restaurant_id = resource.id
    reviews_filter.scope_by_blogger(branch_id: resource.branch_id, restaurant_id: resource.id)
    reviews_filter.sort_by('priority asc')
    reviews_filter.page_number(page).per_page(per_page)
    options = { each_serializer: Api::V5::BloggerReviewSerializer, meta: false }
    reviews_filter.as_json(serialization_context, minor_version_param, options).merge(success: true, message: nil)
  end
rescue ActiveRecord::RecordNotFound
  raise RecordNotFoundButOk
end

#calc_delivery_feesObject



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
# File 'app/controllers/api/v5/restaurants_controller.rb', line 904

def calc_delivery_fees
  if AdminSetting.enable_restaurant_distance_check.to_s == 'true'
    begin
      restaurants = Restaurant.where(id: params[:restaurant_ids])
      destination = {
        lat: params.require(:lat),
        lng: params.require(:lng),
      }

      distance_calculator = DeliveryChannel::DistanceCalculator.new :matrix_google
      result = distance_calculator.find_distance_to_restaurant(destination, restaurants)

      render json: result
    rescue ActionController::ParameterMissing
      render json: {
        data: [],
        success: false,
        message: 'Please give location access',
      }
    end
  else
    render json: {
      data: [],
      success: true,
      message: '',
    }
  end
end

#calculate_package_priceObject



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
61
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
122
123
124
125
126
127
128
129
130
131
132
133
# File 'app/controllers/api/v5/restaurants_controller.rb', line 29

def calculate_package_price
  calculator = HhPackage::ReservationPackages::ChargeCalculator.new

  message = ''
  status = false
  data = {}

  if params.fetch(:guess, false)
    restaurant = Restaurant.fetch params.require(:restaurant_id)
    begin
      data = { delivery_fee: calculator.calculate_by_distance(params.fetch(:distance, 0.0), restaurant) }
      status = true
    rescue StandardError => e
      APMErrorHandler.report(e)
      HH_LOGGER.error('Error calculating delivery fee by distance', {
                        error: e.message,
                        restaurant_id: restaurant&.id,
                        distance: params.fetch(:distance, 0.0),
                      })
      message = INTERNAL_SERVER_ERROR_MESSAGE
    end
  else
    user = user_signed_in? ? current_user : nil
    restaurant = Restaurant.fetch(params[:restaurant_id]) if params.fetch(:restaurant_id, nil).present?
    adult = params.require(:adult).to_i
    kids = params.require(:kids).to_i
    distance = params.fetch(:distance, 0.0)
    is_accept_refund = params.fetch(:accept_refund_guarantee, false)

    # Use the PackageServices::Processor service for package processing
    params_package_bought = params.permit(package_bought: [:id, :quantity, {
                                            menu_sections: [:id, { menus: %i[id quantity] }],
                                            selected_special_menus: [:id, :quantity],
                                            group_sections: [:id, :quantity],
                                          }])

    processor = PackageServices::Processor.new(params_package_bought, restaurant, adult)
    package_bought, is_valid_mix_n_match = processor.process_packages

    params_add_on_bought = params.permit(add_on_bought: [:id, :quantity])
    add_on_processor = AddOnServices::Processor.new(params_add_on_bought, restaurant, adult)
    add_on_bought = add_on_processor.process_add_ons

    unless is_valid_mix_n_match
      return render json: { status: false, message: 'Invalid mix of packages' }
    end

    calculator.set_delivery_pricing_tiers(restaurant.delivery_pricing_tiers) if restaurant
    calculator.set_user(user&.id)
    calculator.accept_refund = is_accept_refund

    begin
      support_dynamic_pricing = true
      date = params[:reservation_date]
      if date.blank?
        HH_LOGGER.debug 'No reservation date provided', params: params
        date = Time.now_in_tz(restaurant.time_zone).to_date.tomorrow
        support_dynamic_pricing = false
      else
        date = date.to_date unless date.is_a?(Date)
      end

      calculator.use_dynamic_pricing = support_dynamic_pricing
      data = calculator.calculate(
        package_bought, adult, kids, distance, restaurant, date, add_on_bought
      )

      # Check if validation failed (e.g., minimum spending not met)
      # for DIY packages
      if data.is_a?(Hash) && data[:validation_error].present?
        # Return with success: false but include the validation message
        return render json: { status: false, message: data[:validation_error], data: data.except(:validation_error) }
      end

      # Remove unused charge_price_cents, total_price_cents, total_package_price_cents, and add_on_total_price_cents
      if data.present?
        data = data.except(
          :charge_price_cents, :total_price_cents, :total_package_price_cents,
          :add_on_total_price_cents, :total_refund_price_cents, :total_refundable_amount_cents
        )
      end

      status = true
    rescue StandardError => e
      raise e if Rails.env.development?

      APMErrorHandler.report(e)
      HH_LOGGER.error('Error calculating package price', {
                        error: e.message,
                        restaurant_id: restaurant&.id,
                        country_id: restaurant&.country_id,
                        currency: restaurant&.currency_code,
                        adult: adult,
                        kids: params[:kids],
                      })
      message = INTERNAL_SERVER_ERROR_MESSAGE
    end
  end

  render json: { status: status, message: message, data: data.merge(delivery_fee: data[:delivery_fee].to_s) }
rescue ActiveRecord::RecordNotFound
  raise RecordNotFoundButOk
rescue InvalidPackageData => e
  render json: { status: false, message: e.message, data: {} }
end

#check_availabilityObject



800
801
802
803
804
805
806
807
808
809
810
811
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
# File 'app/controllers/api/v5/restaurants_controller.rb', line 800

def check_availability
  restaurant = Restaurant.fetch params.require(:restaurant_id)
  date = nil
  begin
    date = Time.use_zone(restaurant.time_zone) { Time.zone.parse(params.require(:date)).to_date }
  rescue StandardError
    return render json: { success: false, message: 'Invalid date', data: [] }
  end

  cache_key = CityHash.hash32([self.class.to_s, 'check_availability', restaurant.cache_key, params, I18n.locale])

  my_response_cache cache_key, :json do
    inv_checker = InvCheckerFactory.new(restaurant.id, restaurant.time_zone).create_inv_checker_service
    inv_checker.is_order_now = order_now_param?
    inv_checker.for_dine_in = for_dine_in?
    inv_checker.for_delivery = for_delivery?

    inv_checker.skip_past_time_error = true
    adult = params.require(:adult).to_i
    kids = params.require(:kids).to_i
    result = []
    inv_checker.get_inv_by_date(date).select { |_start_time, inv| inv[:open] }.each_key do |start_time|
      seat_left = if inv_checker.bookable?(date: date, start_time: start_time, adult: adult, kids: kids)
                    # TODO use InvCheckerFactory#seat_lefts
                    inv_checker.seat_left(date, start_time)
                  else
                    0
                  end
      result.push time: start_time, seat_left: seat_left if seat_left.positive?
    end

    if result.blank?
      next_available_date = inv_checker.recommend_date(date, adult)
      if next_available_date.nil?
        next_available_date = inv_checker.recommend_date(Time.now_in_tz(restaurant.time_zone).to_date, adult)
      end
    end
    message = inv_checker.error_message if result.blank?
    { success: result.present?, data: result, message: message, next_available_date: next_available_date }
  end
end

#check_inObject

POST api/v5/restaurants/#slug/check-in-partner



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
# File 'app/controllers/api/v5/restaurants_controller.rb', line 1009

def check_in
  reservation = nil
  slug_param = params.require(:id)
  reservation_id_param = params.require(:reservation_id)
  skip_email = params[:skip_email]

  self_checkin_setting = SelfCheckinSetting.find_by(slug: slug_param)
  return render_error('Invalid slug') if self_checkin_setting.blank?

  reservation = Reservation.find_by(id: reservation_id_param)

  if reservation.nil? ||
      (reservation.restaurant_id &&
        !self_checkin_setting.self_checkin_restaurants.pluck(:restaurant_id).include?(reservation.restaurant_id))
    return render_error('Reservation not found')
  end

  if skip_email.to_s != 'true' && reservation.email != params[:email]
    return render_error('Invalid email')
  end

  reservation.touch if reservation.present?

  checkin_start_time, checkin_end_time = calculate_checkin_time(self_checkin_setting, reservation)

  restaurant_time_zone = reservation.restaurant.time_zone
  if checkin_time_valid?(checkin_start_time, checkin_end_time, reservation.reservation_time, restaurant_time_zone)
    render_checkin_response(reservation)
  end
rescue ActionController::ParameterMissing => e
  render json: {
    data: nil,
    success: false,
    message: e.message,
  }, status: :unprocessable_entity
end

#check_in_partnerObject

GET api/v5/restaurants/#slug/check-in-partner



998
999
1000
1001
1002
1003
1004
1005
1006
# File 'app/controllers/api/v5/restaurants_controller.rb', line 998

def check_in_partner
  slug = params.require(:id)
  self_checkin_setting = SelfCheckinSetting.find_by(slug: slug)
  render json: {
    success: true,
    data: self_checkin_setting,
    message: nil,
  }
end

#check_order_now_estimationObject



871
872
873
874
875
876
877
878
879
880
881
882
883
884
# File 'app/controllers/api/v5/restaurants_controller.rb', line 871

def check_order_now_estimation
  restaurant = Restaurant.fetch params.require(:restaurant_id)
  order_type = params.require(:order_type)
  destination = {
    lng: params.require(:destination).require(:lon),
    lat: params.require(:destination).require(:lat),
  }

  service = TimeEstimationService.new(order_type, restaurant: restaurant, destination: destination)
  service.set_cooking_estimation(restaurant.order_now&.cooking_time&.to_i || 0)
  result = service.result

  render json: result
end

#check_order_now_supportObject



426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'app/controllers/api/v5/restaurants_controller.rb', line 426

def check_order_now_support
  restaurant = Restaurant.fetch params.require(:restaurant_id)
  return render json: { success: false, data: [], message: nil } unless restaurant.support_order_now?

  date = params.require(:date).to_date
  start_time = params.require(:start_time)

  inv_checker = InvCheckerFactory.new(restaurant.id, restaurant.time_zone).create_inv_checker_service
  inv_checker.for_delivery = true
  inv_checker.for_dine_in = false
  inv_checker.is_order_now = true
  success = inv_checker.open?(date, start_time) == true
  render json: { success: success, data: [], message: nil }
end

#delivery_pricing_tiersObject

we don't use delivery feature anymore



887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
# File 'app/controllers/api/v5/restaurants_controller.rb', line 887

def delivery_pricing_tiers
  render json: { success: true, message: '', data: [] }
  # restaurant = Restaurant.fetch params.require(:restaurant_id)

  # cache_key = [self.class.to_s, action_name, restaurant.id, restaurant.cache_key]
  # my_response_cache(cache_key, :json, public: true) do
  #   delivery_pricing_tiers = restaurant.delivery_pricing_tiers.presence || DeliveryPricingTier.global_scope
  #   data = ActiveModelSerializers::SerializableResource.new(delivery_pricing_tiers,
  #                                                           { serialization_context: self,
  #                                                             serializer: ActiveModel::Serializer::CollectionSerializer,
  #                                                             each_serializer: Api::V5::DeliveryPricingTierSerializer,
  #                                                             adapter: :json_api }).as_json

  #   data.merge(success: data.present?, message: nil).as_json
  # end
end


531
532
533
534
535
536
537
538
539
540
541
542
# File 'app/controllers/api/v5/restaurants_controller.rb', line 531

def featured
  page_param = fix_params_filter.permit!.to_h.fetch(:page, {})
  per_page = page_param.fetch(:size, 9).to_i
  page = page_param.fetch(:number, 1).to_i
  filter = CompactRestaurantsFilter.new
  filter.filter_by_city_id(params[:city_id]) if params[:city_id].present?
  filter.featured_only.sort_by(:rank).page_number(page).per_page(per_page)
  cache_key = [self.class.to_s, action_name, page_param, filter.collections.cache_key, I18n.locale]
  my_response_cache cache_key, :json, public: true do
    filter.as_json(serialization_context, minor_version_param).merge(success: true, message: nil)
  end
end

#find_available_add_onsObject



481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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
# File 'app/controllers/api/v5/restaurants_controller.rb', line 481

def find_available_add_ons
  restaurant = Restaurant.fetch(params.require(:restaurant_id))
  date = params.require(:date)
  start_time = params.require(:start_time)
  restaurant_add_on_ids = params[:restaurant_add_on_ids] || []
  preview_mode = if params[:is_visible_for_staff].present?
                   params[:is_visible_for_staff].to_s == 'true'
                 else
                   false
                 end
  inv_checker = InvCheckerFactory.new(restaurant.id, restaurant.time_zone).create_inv_checker_service

  available_r_add_on_ids = inv_checker.available_add_ons(
    date: date.to_date, start_time: start_time, r_add_on_ids: restaurant_add_on_ids,
  )

  cache_key_params = [restaurant.id, restaurant.inv_cache_key, date, start_time, restaurant_add_on_ids, preview_mode]
  cache_key = "#{self.class.name}:restaurant_id:#{cache_key_params.join(':')}:#{I18n.locale}:#{available_r_add_on_ids}"

  my_response_cache cache_key, :json do
    rest_add_ons = if preview_mode
                     AddOns::Restaurant.where(id: available_r_add_on_ids)
                   else
                     AddOns::Restaurant.where(id: available_r_add_on_ids, is_visible_for_staff: false)
                   end

    data = ActiveModelSerializers::SerializableResource.new(
      rest_add_ons,
      { serialization_context: self,
        serializer: ActiveModel::Serializer::CollectionSerializer,
        each_serializer: Api::V5::AddOnPackageSerializer,
        adapter: :json_api,
        minor_version: minor_version_param },
    ).as_json

    data.merge(success: data.present?, message: nil).as_json
  end
rescue ActionController::ParameterMissing => e
  render json: { success: false, data: [], message: e.message }, status: :bad_request
rescue ActiveRecord::RecordNotFound
  render json: { success: false, data: [], message: 'Restaurant not found' }, status: :not_found
rescue StandardError => e
  if Rails.env.development?
    raise e
  end

  APMErrorHandler.report(e)
  render json: { success: false, data: [], message: INTERNAL_SERVER_ERROR_MESSAGE }, status: :internal_server_error
end

#find_available_datesObject

can't implement ETAG and cache response, because the response is depend on the current time when request is made



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'app/controllers/api/v5/restaurants_controller.rb', line 197

def find_available_dates
  use_old_system = params.fetch('ignore_end_date', true).to_s == 'true'

  return old_find_available_dates if use_old_system

  restaurant = Restaurant.fetch params.require(:restaurant_id)
  adult = params.require(:adult).to_i
  kids = params.require(:kids).to_i
  start_date = params.require(:start_date).to_date.to_s
  end_date = params.require(:end_date).to_date.to_s

  inv_checker = InvCheckerFactory.new(restaurant.id, restaurant.time_zone).create_inv_checker_service
  inv_checker.is_order_now = order_now_param?
  inv_checker.for_dine_in = for_dine_in?
  inv_checker.for_delivery = for_delivery?

  current_time = Time.now_in_tz(restaurant.time_zone)
  today = current_time.to_date

  error = false
  start_date = today.to_s if Date.parse(start_date) < today

  if Date.parse(end_date) > (Date.parse(start_date) + 19.days)
    error = true
    error_message = "range date can't be greater than 20 days"
  end

  if error
    return render json: {
      success: false,
      message: error_message,
    }
  end

  data = if restaurant.restaurant_packages.present?
           inv_checker.find_available_dates_without_start_time(adult: adult, kids: kids, start_date: start_date,
                                                               end_date: end_date)
         else # Inactive restaurant (widget page) doesnt work if using #find_available_dates_without_start_time
           start_date_is_today = Date.parse(start_date) == today
           dates_find_by_start_time = []

           if start_date_is_today
             service_type = for_delivery? ? 'delivery' : 'dine_in'
             find_by_start_time_end_date = (current_time + restaurant.determine_min_booking_time(service_type: service_type).minutes).to_date
             dates_find_by_start_time = if today == find_by_start_time_end_date
                                          [today]
                                        else
                                          [find_by_start_time_end_date]
                                        end
           end

           start_date = if start_date_is_today
                          (dates_find_by_start_time.last + 1.day).to_s
                        else
                          Date.parse(start_date).to_s
                        end
           available_dates = []

           dates_find_by_start_time.each do |date|
             available_today = inv_checker.find_available_start_times(adult: adult,
                                                                      kids: kids,
                                                                      date: date).map do |st|
               Time.use_zone(restaurant.time_zone) { Time.zone.parse(st) }
             end

             is_today_available = available_today.select do |st|
               st > current_time
             end.present?

             available_dates.push({
                                    date: date,
                                    availability: is_today_available,
                                    # hard code to make validation on FE app work
                                    seat_left: is_today_available ? 100 : 0,
                                    min_seat: 2,
                                    max_seat: 20,
                                    booked_seat: is_today_available ? 0 : 20,
                                  })
           end

           available_dates_except_today = inv_checker.find_available_dates(
             adult: adult, kids: kids, start_date: start_date, end_date: end_date,
           )

           available_dates.concat(available_dates_except_today)
         end

  render json: {
    success: data.present?,
    data: data,
    message: nil,
  }
end

#find_available_packagesObject



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'app/controllers/api/v5/restaurants_controller.rb', line 441

def find_available_packages
  preview = if params[:is_visible_for_staff].present?
              true
            else
              false
            end
  restaurant = Restaurant.fetch params.require(:restaurant_id)
  adult = params.require :adult
  kids = params.require :kids
  date = params.require(:date)
  start_time = params.require(:start_time)

  inv_checker = InvCheckerFactory.new(restaurant.id, restaurant.time_zone).create_inv_checker_service
  inv_checker.is_order_now = order_now_param?
  inv_checker.for_dine_in = for_dine_in?
  inv_checker.for_delivery = for_delivery?

  slugs = inv_checker.available_packages(date: date.to_date, start_time: start_time, adult: adult, kids: kids)

  cache_key = [self.class.to_s, action_name, restaurant.id,
               restaurant.inv_cache_key, adult, kids,
               date, start_time, for_delivery?, for_dine_in?, preview, slugs]

  my_response_cache(cache_key, :json) do
    rest_packs = if preview == true
                   HhPackage::RestaurantPackage.where(slug: slugs)
                 else
                   HhPackage::RestaurantPackage.where(slug: slugs, is_visible_for_staff: false)
                 end
    data = ActiveModelSerializers::SerializableResource.new(rest_packs,
                                                            { serialization_context: self,
                                                              serializer: ActiveModel::Serializer::CollectionSerializer,
                                                              each_serializer: Api::V5::RestaurantPackageSerializer,
                                                              adapter: :json_api,
                                                              minor_version: minor_version_param }).as_json

    data.merge(success: data.present?, message: nil, tag_line: package_tag_lines(restaurant)).as_json
  end
end

#find_available_start_timesObject

don't cache is date is today, otherwise user will get stale data



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'app/controllers/api/v5/restaurants_controller.rb', line 331

def find_available_start_times
  return find_available_start_times_v4 if minor_version_param == '4'

  restaurant = Restaurant.fetch params.require(:restaurant_id)
  adult = params.require(:adult).to_i
  kids = params.require(:kids).to_i
  date = params.require(:date)

  invalid_date = false
  date_as_date = nil
  begin
    date_as_date = date.to_date
  rescue ArgumentError
    invalid_date = true
  end

  if invalid_date
    render json: { success: false, data: [], message: 'Invalid Date' }
  elsif date_as_date == Time.now_in_tz(restaurant.time_zone).to_date
    data = _find_available_start_times(restaurant, date, adult, kids)

    render json: {
      success: data.present?,
      data: data,
      message: nil,
    }
  else
    cache_key = [
      self.class.to_s, action_name, restaurant.id, date,
      adult, kids, for_dine_in?, for_delivery?, order_now_param?
    ].join(':')
    my_response_cache(cache_key, :json) do
      data = _find_available_start_times(restaurant, date, adult, kids)

      {
        success: data.present?,
        data: data,
        message: nil,
      }.as_json
    end
  end
end

#find_visitor_distanceObject



842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
# File 'app/controllers/api/v5/restaurants_controller.rb', line 842

def find_visitor_distance
  restaurant_id = params.require(:restaurant_id)
  lat = params[:lat]
  lng = params[:lng]

  etag = CityHash.hash32([restaurant_id, lat, lng])
  return unless stale?(etag: etag, template: false)

  restaurant = Restaurant.fetch restaurant_id

  destination = {
    lat: lat,
    lng: lng,
  }

  calculator = DeliveryChannel::DistanceCalculator.new
  result = calculator.find_distance_to_restaurant(destination, restaurant)
  set_status_header(result.present?)

  render json: {
    success: result[:success],
    message: result[:message],
    data: {
      distance: result[:distance],
      min_distance: result[:min_distance],
    },
  }
end

#inactive_slugsObject

this api is used for updating robot.txt pegasus



1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'app/controllers/api/v5/restaurants_controller.rb', line 1047

def inactive_slugs
  today = Date.current_date

  named_cache_key = "#{CACHE_NAMESPACE}:#{self.class}|#{action_name}|#{today}"
  cache_key = CityHash.hash32([named_cache_key, params, I18n.locale])

  page = params.fetch(:page, {})

  my_response_cache(cache_key, :json) do
    inactive_restaurants = Restaurant.where('active = ? OR expiry_date < ?', false, today)

    slugs = FriendlyId::Slug.where(sluggable: inactive_restaurants).
      order(created_at: :desc).
      page(page.fetch(:number, 1)).
      per(page.fetch(:size, 10)).
      pluck(:slug)

    {
      success: true,
      data: slugs,
      message: nil,
    }.as_json
  end
end

#indexObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'app/controllers/api/v5/restaurants_controller.rb', line 12

def index
  params[:compact_mode] = true if minor_version_param == '3'
  if params[:restaurant_id].present?
    params[:id] = params[:restaurant_id]

    return show
  end

  type = params[:type]
  report_cache_key = if type.present?
                       Report.cached_all_cache_key
                     else
                       ''
                     end
  restaurant_list("#{CACHE_NAMESPACE}:#{self.class}:index_expiration:#{report_cache_key}", :default)
end

#inventory_summariesObject

for package sorting feature



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/api/v5/restaurants_controller.rb', line 934

def inventory_summaries
  restaurant_id = params.require(:restaurant_id)

  feature_setting = AdminSetting.enable_package_sort_feature.to_s
  if feature_setting == 'false'
    restaurant = Restaurant.fetch restaurant_id
    restaurant_packages_cache_key = restaurant.restaurant_packages.cache_key
    my_response_cache(
      "#{CACHE_NAMESPACE}:inventory_summaries:#{restaurant_id}:#{restaurant_packages_cache_key}:#{feature_setting}", :json
    ) do
      data = restaurant.restaurant_packages.pluck(:id).map do |id|
        {
          restaurant_package_id: id,
          total_seat_left_package: 100,
        }
      end
      { data: data, message: '', success: true }
    end

    return
  end

  inventory = Api::V5::InventorySummariesFilter.new(restaurant_id)
  cache_key = inventory.cache_key
  cache_key = "#{CACHE_NAMESPACE}:inventory_summaries:#{cache_key}"
  my_response_cache(cache_key, :json, public: true, public_expires_in: 24.hours) do
    inventory.as_json
  end
end

#json_ldObject



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

def json_ld
  RequestStore.store[:skip_host] = false
  id = params.require(:restaurant_id)
  resource = Restaurant.fetch(id)
  cache_key = CityHash.hash32([self.class.to_s, resource.view_cache_key, params, I18n.locale,
                               RequestStore.store[:skip_host]])
  my_response_cache("json_ld:#{cache_key}", :json, public: true) do
    jsonld = begin
      cell(:schema, resource.decorate).call(:restaurant_page)
    rescue StandardError => e
      APMErrorHandler.report(e)
      ''
    end
    Oj.load render_to_string(json: { data: jsonld, success: true, message: nil })
  end
end

#locationsObject



558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'app/controllers/api/v5/restaurants_controller.rb', line 558

def locations
  cache_key = "#{CACHE_NAMESPACE}:#{self.class}:locations:#{CityHash.hash32([I18n.locale, params,
                                                                             Restaurant.active.not_expired.cache_key])}"

  my_response_cache cache_key, :json, public: true do
    page_param = params.require(:page)
    per_page = page_param.fetch(:size, 100).to_i
    page = page_param.fetch(:number, 1).to_i

    filter = Api::V5::RestaurantsFilter.new
    filter.sort_by('top').use_default_collections
    filter.by_location_ids(params.require(:location_id)) if params[:location_id].present?
    filter.by_cuisine_ids(params.require(:cuisine_id)) if params[:cuisine_id].present?
    filter.page_number(page).per_page(per_page)

    options = { each_serializer: Api::V5::RestaurantLocationSerializer }
    filter.as_json(serialization_context, minor_version_param, options).merge(success: true, message: nil)
  end
end

#new_compactObject



544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'app/controllers/api/v5/restaurants_controller.rb', line 544

def new_compact
  page_param = fix_params_filter.permit!.to_h.fetch(:page, {})
  sort_by = fix_params_filter.fetch(:sort_by, 'new')
  per_page = page_param.fetch(:size, 9).to_i
  page = page_param.fetch(:number, 1).to_i
  filter = CompactRestaurantsFilter.new
  filter.filter_by_city_id(params[:city_id]) if params[:city_id].present?
  filter.sort_by(sort_by.to_sym).page_number(page).per_page(per_page)
  cache_key = [self.class.to_s, I18n.locale, action_name, page_param, sort_by, filter.collections.cache_key]
  my_response_cache cache_key, :json, public: true do
    filter.as_json(serialization_context, minor_version_param).merge(success: true, message: nil)
  end
end

#old_find_available_datesObject

used by Widget web



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
# File 'app/controllers/api/v5/restaurants_controller.rb', line 292

def old_find_available_dates
  restaurant = Restaurant.fetch params.require(:restaurant_id)
  adult = params.require(:adult).to_i
  kids = params.require(:kids).to_i

  inv_checker = InvCheckerFactory.new(restaurant.id, restaurant.time_zone).create_inv_checker_service
  inv_checker.is_order_now = order_now_param?
  inv_checker.for_dine_in = for_dine_in?
  inv_checker.for_delivery = for_delivery?

  current_time = Time.now_in_tz(restaurant.time_zone)
  today = current_time.to_date
  service_type = for_delivery? ? 'delivery' : 'dine_in'
  find_by_start_time_end_date = (current_time + restaurant.determine_min_booking_time(service_type: service_type).minutes).to_date
  dates_find_by_start_time = if today == find_by_start_time_end_date
                               [today]
                             else
                               (today..find_by_start_time_end_date).to_a
                             end
  end_date = if restaurant.id == 1590
               dates_find_by_start_time.last + restaurant.days_in_advance.days
             else
               dates_find_by_start_time.last + 30.days
             end

  start_date = dates_find_by_start_time.last.to_s
  end_date = end_date.to_s

  data = inv_checker.find_available_dates_without_start_time(adult: adult, kids: kids, start_date: start_date,
                                                             end_date: end_date)

  render json: {
    success: data.present?,
    data: data,
    message: nil,
  }
end

#recommendationObject



737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# File 'app/controllers/api/v5/restaurants_controller.rb', line 737

def recommendation
  if AdminSetting.enable_recommendation.to_s == 'true'
    RequestStore.store[:skip_host] = false

    params[:by_recommendation] = true
    cache_key = CityHash.hash32([self.class.to_s, Time.zone.today, Time.zone.now.hour, I18n.locale, params])
    restaurant_list("#{CACHE_NAMESPACE}:#{self.class}|#{cache_key}|recommendation")
  else
    render json: {
      data: [],
      links: {
        self: '/api/v5/restaurants/recommendation.json',
        first: '/api/v5/restaurants/recommendation.json',
        prev: nil,
        next: nil,
        last: '/api/v5/restaurants/recommendation.json',
      },
      success: true,
      message: nil,
      meta_data: {
        price_ranges: {},
        total_restaurants: 1,
      },
      ads: {
        data: [],
      },
    }
  end
end

#searchObject

Data refreshed for every hour if group landing page changed it will refresh the cache



769
770
771
772
773
774
775
776
# File 'app/controllers/api/v5/restaurants_controller.rb', line 769

def search
  RequestStore.store[:skip_host] = false
  glp_cache_key = GroupLandingPage.maximum(:updated_at)

  cache_key = CityHash.hash32([self.class.to_s, Time.zone.today, Time.zone.now.hour, I18n.locale, params,
                               glp_cache_key])
  restaurant_list("#{CACHE_NAMESPACE}:#{self.class}|#{cache_key}|search")
end

#search_optionsObject



964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
# File 'app/controllers/api/v5/restaurants_controller.rb', line 964

def search_options
  city = City.fetch(params[:city_id])
  return render json: { success: false, data: nil, message: 'Invalid City' } if city.blank?

  country = Country.fetch(city.country_id)
  if country.present?
    expires_in DEFAULT_HTTP_PUBLIC_CACHE_EXPIRATION, public: true
    cache_key = "#{CACHE_NAMESPACE}:search_options:#{country.cache_key}:#{I18n.locale}"
    data = Rails.cache.fetch(cache_key, expires_in: 5.minutes) do
      Api::V5::SearchOptionSerializer.new(country).as_json
    end
    render json: { success: true, data: data }
  else
    render json: { success: false, error: 'Invalid City or Country' }
  end
end

#showObject



677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
# File 'app/controllers/api/v5/restaurants_controller.rb', line 677

def show
  RequestStore.store[:skip_host] = false
  id = params.require(:id)
  resource = Restaurant.fetch(id)
  now = Time.now_in_tz(resource.time_zone)
  date = now.to_date
  hour = now.strftime('%H')
  minutes = Time.up_to_nearest_15(now.strftime('%M').to_i)
  cache_key = CityHash.hash32([self.class.to_s,
                               resource.view_cache_key,
                               params,
                               I18n.locale,
                               RequestStore.store[:skip_host],
                               date, hour, minutes])
  my_response_cache("show:#{cache_key}", :json, public: true) do
    resource = Restaurant.fetch(id).decorate
    includes = []
    includes.push('pictures') if params.key?(:include_pictures) && params[:include_pictures].to_s == 'true'
    includes.push('restaurant_packages') if params.key?(:include_packages) && params[:include_packages].to_s == 'true'
    if params.key?(:include_last_reviews) && params[:include_last_reviews].to_s == 'true'
      includes.push('last_reviews')
    end
    if params.key?(:include_blogger_reviews) && params[:include_blogger_reviews].to_s == 'true'
      includes.push('blogger_reviews')
    end
    options = {
      include: includes,
    }
    reviews_filter = Api::V5::ReviewsFilter.new
    reviews_filter.scope_by(branch_id: resource.branch_id, restaurant_id: resource.id)
    reviews_filter.use_default_order
    options[:meta] = {
      reviews: reviews_filter.meta,
      criteo_item: [{ id: resource.id, quantity: 1, price: resource.price_per_person(as_string: false) }],
    }
    resource_as_json(resource, restaurant_serializer, options).merge(success: true, message: nil)
  end
  set_status_header(true)
rescue ActiveRecord::RecordNotFound, Hashids::InputError
  set_status_header(false)
  render json: { success: false, data: [], message: 'Sorry we can not identify your requested restaurant' }
end

#similarObject



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'app/controllers/api/v5/restaurants_controller.rb', line 172

def similar
  # for temporary need to disable similar restaurant, return empty data
  render json: { data: [], success: true, message: nil }

  # restaurant = Restaurant.fetch params.require(:restaurant_id)
  # cache_key = CityHash.hash32([self.class.to_s, 'similar_restaurants', restaurant.view_cache_key,
  #                              MyLocaleManager.normalize_locale])
  # my_response_cache(cache_key, :json, public: true) do
  #   collection = if Figaro.bool_env! 'APP_USE_CLEVERTAP_SIMILAR_RESTAURANTS'
  #                  RestaurantSimilarity.find_cached(restaurant.id)
  #                else
  #                  Restaurant.active.not_expired
  #                end
  #   filter = Api::V5::RestaurantsFilter.new(collection)

  #   options = {
  #     preview_mode: true,
  #     compact_mode: true,
  #   }
  #   filter.as_json(serialization_context, minor_version_param, options).merge(success: true, message: nil)
  # end
end

#slugObject



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
606
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# File 'app/controllers/api/v5/restaurants_controller.rb', line 578

def slug
  resource = nil
  relevant_params_to_hash = nil

  dynamic_cache_key_name = ElasticAPM.with_span('setup-dynamic-cache-key-name', 'controller') do
    allowed_params = %i[restaurant_id include_pictures include_packages include_last_reviews include_blogger_reviews
                        write preview_mode minor_version client_type locale access_token].freeze
    excluded_params = %i[controller action format restaurant]
    invalid_params = params.keys.map(&:to_sym) - (allowed_params + excluded_params)

    if invalid_params.any?
      APMErrorHandler.report 'unknown cache key', params: params
    end

    RequestStore.store[:skip_host] = false
    slug = params.require(:restaurant_id)
    resource = find_encrypted_restaurant(slug).decorate

    # set default params
    relevant_params = {
      restaurant_id: nil,
      include_pictures: false,
      include_packages: false,
      include_last_reviews: false,
      include_blogger_reviews: false,
      preview_mode: false,
      minor_version: nil,
    }
    # update default params with the params from request
    # params.permit(:restaurant_id, :include_pictures, :include_packages, :include_last_reviews,
    #                               :include_blogger_reviews, :preview_mode, :minor_version)
    relevant_params = relevant_params.merge(params.permit(relevant_params.keys).to_h.map do |k, v|
                                              [k.to_sym, v]
                                            end.to_h)

    # client app send restaurant's slug as restaurant_id in the request, so we
    # need to update the relevant_params with the correct restaurant_id, to prevent
    # duplicate cache keys, because each restaurant could have multiple slugs
    relevant_params[:restaurant_id] = resource.id

    # map values to string to make sure the hash is consistent
    relevant_params_to_hash = relevant_params.to_h.map { |k, v| [k, v.to_s] }.to_h

    # This action receives a lot of different parameters, so we need to generate
    # few cache keys to cover all possible combinations
    # Include resource.view_cache_key to ensure cache is properly invalidated when the restaurant's UI cache is cleared or its view changes.
    hash = CityHash.hash32([resource.id, resource.view_cache_key, relevant_params_to_hash, I18n.locale])
    "#{CACHE_NAMESPACE}:#{self.class}:slug:#{resource.id}:#{hash}"
  end

  # we use sidekiq to warm up cache: app/workers/restaurants/slug_worker.rb
  by_sidekiq = params[:write]&.to_s == 'true'

  debug_params = {
    restaurant_id: resource.id,
    I18n_locale: I18n.locale,
    relevant_params: relevant_params_to_hash,
  }

  my_response_cache(dynamic_cache_key_name, :json, public: true,
                                                   expires_in: 1.month, public_expires_in: 5.minutes,
                                                   force_write: by_sidekiq, debug_params: debug_params) do
    includes = ['ticket_groups']

    ElasticAPM.with_span('setup-includes', 'controller') do
      includes.push('pictures') if params.key?(:include_pictures) && params[:include_pictures].to_s == 'true'
      includes.push('restaurant_packages') if params.key?(:include_packages) && params[:include_packages].to_s == 'true'
      if params.key?(:include_last_reviews) && params[:include_last_reviews].to_s == 'true'
        includes.push('last_reviews')
      end
      if params.key?(:include_blogger_reviews) && params[:include_blogger_reviews].to_s == 'true'
        includes.push('blogger_reviews')
      end
    end
    options = {
      include: includes,
    }
    reviews_filter = nil
    ElasticAPM.with_span('setup-reviews-filter', 'controller') do
      reviews_filter = Api::V5::ReviewsFilter.new
      reviews_filter.scope_by(branch_id: resource.branch_id, restaurant_id: resource.id)
      reviews_filter.use_default_order
      options[:meta] = {
        reviews: reviews_filter.meta,
        criteo_item: [{ id: resource.id, quantity: 1, price: resource.price_per_person(as_string: false) }],
      }
    end
    ElasticAPM.with_span('resource_as_json', 'controller') do
      resource_as_json(resource, restaurant_serializer, options).merge(success: true, message: nil)
    end
  end

  set_status_header(true)
rescue ActiveRecord::RecordNotFound, Hashids::InputError
  set_status_header(false)
  render json: { success: false, data: [], message: 'Sorry we can not identify your requested restaurant' }
end

#store_page_listObject



981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
# File 'app/controllers/api/v5/restaurants_controller.rb', line 981

def store_page_list
  now = Time.zone.now
  cache_key = "#{CACHE_NAMESPACE}:store_page_list:#{Date.today} #{now.hour}:#{now.min}"
  my_response_cache(cache_key, :json, expires_in: 1.minute, public: true, public_expires_in: 1.minute) do
    enable_store_page_actors = Flipper[:enable_store_page].gate_values.actors.to_a
    restaurant_slugs = Restaurant.where(id: enable_store_page_actors).pluck(:slug)

    {
      data: enable_store_page_actors,
      slugs: restaurant_slugs,
      success: true,
      message: nil,
    }
  end
end