Class: Api::Vendor::V1::RestaurantsController

Inherits:
BaseController
  • Object
show all
Includes:
Concerns::Authentication, Concerns::GetRestaurantList, Concerns::ReservationUtils
Defined in:
app/controllers/api/vendor/v1/restaurants_controller.rb

Constant Summary

Constants inherited from BaseController

BaseController::CACHE_NAMESPACE

Instance Attribute Summary

Attributes inherited from BaseController

#vendor

Instance Method Summary collapse

Methods included from LogrageCustomLogger

#append_info_to_payload

Methods included from ResponseCacheConcern

#my_response_cache

Instance Method Details

#calculate_package_priceObject



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
373
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
# File 'app/controllers/api/vendor/v1/restaurants_controller.rb', line 339

def calculate_package_price
  adult = params.require(:adult)
  kids = params.require(:kids)

  is_package_qty_adjustable = ::Channel.adjust_package_qty_for_vendor?(vendor.name)

  calculator = HhPackage::ReservationPackages::ChargeCalculator.new

  restaurant = Restaurant.active.not_expired.find_by(id: params.require(:restaurant_id))
  raise ApiVendorV1::Errors::RestaurantValidationError if restaurant.blank?

  params_package_bought = params.permit(package_bought: [:id, :quantity, {
                                          menu_sections: [:id, { menus: %i[id quantity] }],
                                        }])

  # Validate all restaurant_package IDs and collect invalid ones
  invalid_package_ids = []
  package_bought = params_package_bought[:package_bought].map do |param|
    id = param.delete :id
    rest_pack = restaurant.restaurant_packages.valid_to_have_agendas.find_by(id: id)
    if rest_pack.nil?
      invalid_package_ids << id
      next
    end
    param[:package] = rest_pack.package
    param[:restaurant_package_id] = id
    restaurant = rest_pack.restaurant if restaurant.nil?
    param[:quantity] = calculate_package_qty(rest_pack, adult, kids) if is_package_qty_adjustable
    param
  end.compact

  # If any invalid package IDs are found, raise an error and return a clear error response
  raise ApiVendorV1::Errors::RestaurantPackageValidationError if invalid_package_ids.any?

  support_dynamic_pricing = true
  reservation_date = params[:reservation_date].presence || begin
    support_dynamic_pricing = false
    HH_LOGGER.debug 'reservation_date is not provided', { caller: caller, params: params }
    nil
  end
  reservation_date = Date.parse(params[:reservation_date]) if reservation_date.present?
  calculator.use_dynamic_pricing = support_dynamic_pricing
  data = calculator.calculate(package_bought, adult, kids, params.fetch(:distance, 0.0),
                              restaurant, reservation_date)

  if data.present?
    data.except!(
      :delivery_fee, :original_delivery_fee, :delivery_fee_currency, :delivery_fee_in_baht,
      :delivery_fee_per_km_in_baht, :free_delivery_fee_threshold_in_baht, :delivery_radius
    )

    # TODO: we will remove these irrelevant keys from the response after some time
    data['charge_price'] = 0
    data['charge_price_v2'] = 0
    data['charge_price_cents'] = 0
    data['charge_amount_type'] = ''
    data['charge_percent'] = 0
    data['charge_type'] = ''
    data['total_point_earn'] = 0
  end

  response = { success: true, message: nil, data: data }
  render json: response
rescue ApiVendorV1::Errors::RestaurantValidationError
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_RESTAURANT_VALIDATION_ERROR)
rescue ActionController::ParameterMissing => e
  render_error_response(error_message: e.message)
rescue ApiVendorV1::Errors::RestaurantPackageValidationError
  render_error_response(error_message: "Invalid restaurant_package id(s): #{invalid_package_ids.join(', ')}")
rescue StandardError => e
  APMErrorHandler.report(e, params: params)
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_INTERNAL_SERVER_ERROR)
end

#find_available_datesObject



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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
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
# File 'app/controllers/api/vendor/v1/restaurants_controller.rb', line 159

def find_available_dates
  restaurant = Restaurant.active.not_expired.find_by(id: params.require(:restaurant_id))
  raise ApiVendorV1::Errors::RestaurantValidationError if restaurant.blank?

  # set adult and kids as zero because clients are not sent these params
  # 0 is minimum value for find available dates
  adult = 0
  kids = 0

  if params[:adult].present?
    adult = params[:adult].to_i
  end
  if params[:kids].present?
    kids = params[:kids].to_i
  end

  start_date = params.require(:start_date)
  end_date = params.require(:end_date)

  if Date.parse(start_date) > Date.parse(end_date)
    error = true
    error_message = 'end date must bigger than start date'
  end

  # Set start date as today date if the start date
  # from input params is less than today
  current_time = Time.now_in_tz(restaurant.time_zone)
  today = current_time.to_date
  start_date = today.to_s if Date.parse(start_date) < today

  if Date.parse(end_date) > (Date.parse(start_date) + 20.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,
      data: nil,
    }
  end

  restaurant_package_id = params.fetch(:restaurant_package_id, nil)

  if restaurant_package_id.present?
    restaurant_package = HhPackage::RestaurantPackage.valid_to_have_agendas_and_not_preview.find_by(id: restaurant_package_id)
    raise ApiVendorV1::Errors::RestaurantPackageValidationError if restaurant_package.blank?
  end

  inv_checker = create_inv_checker_instance(restaurant, restaurant_package_id)
  inv_checker.is_order_now = order_now_param?
  inv_checker.for_dine_in = for_dine_in?
  inv_checker.for_delivery = for_delivery?

  data = ElasticAPM.with_span 'find_available_dates_data' do
    if restaurant_package_id.present?
      ElasticAPM.with_span 'find_available_dates_with_package_id' do
        # to find available dates based on packages
        inv_checker.find_available_dates(adult: adult, kids: kids,
                                         start_date: start_date, end_date: end_date)
      end
    elsif restaurant.restaurant_packages.present?
      ElasticAPM.with_span 'find_available_dates_without_package_id' do
        inv_checker.find_available_dates_without_start_time(start_date: start_date,
                                                            end_date: end_date, adult: adult, kids: kids)
      end
    end
  end
  response = {
    success: data.present?,
    data: data,
    message: nil,
  }

  render json: response
rescue ApiVendorV1::Errors::RestaurantValidationError
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_RESTAURANT_VALIDATION_ERROR)
rescue ApiVendorV1::Errors::RestaurantPackageValidationError
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_RESTAURANT_PACKAGE_VALIDATION_ERROR)
rescue ActionController::ParameterMissing => e
  render_error_response(error_message: e.message)
rescue StandardError => e
  APMErrorHandler.report(e, params: params)
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_INTERNAL_SERVER_ERROR)
end

#find_available_packagesObject



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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'app/controllers/api/vendor/v1/restaurants_controller.rb', line 88

def find_available_packages
  preview = if params[:is_visible_for_staff].present?
              true
            else
              false
            end
  restaurant = Restaurant.active.not_expired.find_by(id: params.require(:restaurant_id))
  raise ApiVendorV1::Errors::RestaurantValidationError if restaurant.blank?

  adult = params[:adult]
  kids = params[:kids]
  date = params[:date]
  start_time = params[:start_time]
  package_type = params[:package_types]
  payment_type = params[:payment_type]
  time = Time.use_zone(restaurant.time_zone) do
    Time.zone.now
  end

  # return error if payment_type is not valid
  if payment_type.present? && ApiVendorV1::Constants::PACKAGE_PAYMENT_TYPES.exclude?(payment_type)
    return render json: { success: false, message: 'Invalid payment_type', data: nil }
  end

  cache_key = [self.class.to_s, action_name, restaurant.id,
               restaurant.inv_cache_key, adult, kids,
               date, start_time, preview, package_type, payment_type, MyLocaleManager.normalize_locale]

  my_response_cache(cache_key, :json) do
    packages = if adult.present? && kids.present? && date.present? && start_time.present?
                 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?

                 slugs = inv_checker.available_packages(date: date.to_date, start_time: start_time, adult: adult,
                                                        kids: kids)
                 # Excluding the Copper Beyond Buffet restaurant_package (ID: 45461) from third-party integrations
                 # (e.g., OpenRice, KKday) due to tier price limitations, which cause incorrect pricing.
                 restaurant.all_restaurant_packages.valid_to_have_agendas_and_not_preview.where(
                   slug: slugs, is_visible_for_staff: false,
                 ).where.not(id: 45461)
               elsif restaurant.expiry_date >= time.to_date
                 restaurant.all_restaurant_packages.valid_to_have_agendas_and_not_preview.where.not(id: 45461)
               end
    packages = HhPackage::RestaurantPackage.where('1 = 0') if packages.blank?

    packages = filter_packages_by_type(packages, package_type) if package_type.present?
    packages = filter_packages_by_payment_type(packages, payment_type) if payment_type.present?

    include_restaurant = params.key?('include_restaurant') && params['include_restaurant'].to_s == 'true'

    booking_channel = Channel.find_by oauth_application_id: vendor.id
    options = {
      include: include_restaurant ? ['restaurant'] : [],
      params: {
        support_dynamic_pricing: booking_channel&.support_dynamic_pricing,
      },
    }

    data = resource_as_json(packages, Api::Vendor::V1::RestaurantPackageSerializer, options)

    data.merge(success: data.present?, message: nil)
  end
rescue ApiVendorV1::Errors::RestaurantValidationError
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_RESTAURANT_VALIDATION_ERROR)
rescue StandardError => e
  APMErrorHandler.report(e, params: params)
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_INTERNAL_SERVER_ERROR)
end

#find_available_peopleObject



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'app/controllers/api/vendor/v1/restaurants_controller.rb', line 247

def find_available_people
  resource = Restaurant.active.not_expired.find_by(id: params.require(:restaurant_id))&.decorate
  raise ApiVendorV1::Errors::RestaurantValidationError if resource.blank?

  custom_seats = resource[:custom_seats].split(',').map(&:to_i)
  default_seats = (resource[:min_party_size]..resource[:largest_table]).to_a
  adult = custom_seats.presence || default_seats

  response = {
    success: true,
    data: {
      number_of_adult: adult,
      accept_kids: resource[:accept_kids],
    },
    message: nil,
  }
  render json: response
rescue ApiVendorV1::Errors::RestaurantValidationError
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_RESTAURANT_VALIDATION_ERROR)
rescue StandardError => e
  APMErrorHandler.report(e, params: params)
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_INTERNAL_SERVER_ERROR)
end

#find_available_start_timesObject



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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
# File 'app/controllers/api/vendor/v1/restaurants_controller.rb', line 272

def find_available_start_times
  adult = params.require(:adult)
  kids = params.require(:kids)
  date = params.require(:date)

  restaurant = Restaurant.active.not_expired.find_by(id: params.require(:restaurant_id))
  raise ApiVendorV1::Errors::RestaurantValidationError if restaurant.blank?

  restaurant_package_id = params.fetch(:restaurant_package_id, nil)
  if restaurant_package_id.present?
    restaurant_package = HhPackage::RestaurantPackage.valid_to_have_agendas_and_not_preview.find_by(id: restaurant_package_id)
    raise ApiVendorV1::Errors::RestaurantPackageValidationError if restaurant_package.blank?
  end

  error = false
  if date.blank?
    error = true
    error_message = 'date is required'
  end

  if adult.blank?
    error = true
    error_message = 'adult is required'
  end

  if error
    response = {
      success: false,
      message: error_message,
      data: nil,
    }
    return render json: response
  end

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

  response = { success: false, message: 'invalid date', data: nil }
  return render json: response if invalid_date

  data = if minor_version_param == '4'
           _find_available_start_times_v4(restaurant, restaurant_package_id, date, adult.to_i, kids.to_i)
         else
           _find_available_start_times(restaurant, restaurant_package_id, date, adult.to_i, kids.to_i)
         end

  response = {
    success: data.present?,
    data: data,
    message: nil,
  }

  render json: response
rescue ApiVendorV1::Errors::RestaurantValidationError
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_RESTAURANT_VALIDATION_ERROR)
rescue ApiVendorV1::Errors::RestaurantPackageValidationError
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_RESTAURANT_PACKAGE_VALIDATION_ERROR)
rescue StandardError => e
  APMErrorHandler.report(e, params: params)
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_INTERNAL_SERVER_ERROR)
end

#indexObject



7
8
9
10
11
12
13
# File 'app/controllers/api/vendor/v1/restaurants_controller.rb', line 7

def index
  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}|index")
rescue StandardError => e
  APMErrorHandler.report(e, params: params)
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_INTERNAL_SERVER_ERROR)
end

#picturesObject



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

def pictures
  restaurant_id = params.require(:restaurant_id)
  restaurant = Restaurant.active.not_expired.find_by(id: restaurant_id)
  raise ApiVendorV1::Errors::RestaurantValidationError if restaurant.blank?

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

  page_number = page[:number].presence || 1
  page_size = (page[:size].presence || 10).to_i.clamp(1, 50)

  # Count all restaurant pictures on specific restaurant
  pictures = restaurant.pictures.includes(:translations).order_by_priority
  pictures_cache_key = pictures.cache_key
  pagy, pictures = pagy_array(pictures, page: page_number.to_i, items: page_size.to_i, overflow: :last_page)
  cache_key = "#{self.class}:#{restaurant_id}:pictures:#{pictures_cache_key}:#{MyLocaleManager.normalize_locale}:#{page}"

  my_response_cache cache_key, :json, public: true do
    meta_options = { restaurants_pictures: pictures.count }
    Api::Vendor::V1::RestaurantPictureSerializer.new(pictures, set_options(pagy, meta_options)).as_json
  end
rescue ApiVendorV1::Errors::RestaurantValidationError
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_RESTAURANT_VALIDATION_ERROR)
rescue StandardError => e
  APMErrorHandler.report(e, params: params)
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_INTERNAL_SERVER_ERROR)
end

#searchObject



15
16
17
18
19
20
21
# File 'app/controllers/api/vendor/v1/restaurants_controller.rb', line 15

def search
  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}|search")
rescue StandardError => e
  APMErrorHandler.report(e, params: params)
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_INTERNAL_SERVER_ERROR)
end

#showObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'app/controllers/api/vendor/v1/restaurants_controller.rb', line 23

def show
  id = params.require(:id)
  resource = Restaurant.active.not_expired.find_by(id: id)&.decorate
  raise ApiVendorV1::Errors::RestaurantValidationError if resource.blank?

  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,
                               date, hour, minutes])
  my_response_cache("show:#{cache_key}", :json, public: true) do
    includes = []
    includes.push('pictures') if params.key?(:include_pictures) && params[:include_pictures].to_s == 'true'
    if params.key?(:include_packages) && params[:include_packages].to_s == 'true'
      includes.push('restaurant_packages')
    end

    package_types = params[:package_types]&.split(',') if params[:package_types].present?

    options = {
      include: includes,
      user: user_signed_in? ? current_user : nil,
      params: { package_types: package_types },
    }

    resource_as_json(resource, Api::Vendor::V1::RestaurantSerializer, options).merge(success: true, message: nil)
  end
rescue ApiVendorV1::Errors::RestaurantValidationError
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_RESTAURANT_VALIDATION_ERROR)
rescue StandardError => e
  APMErrorHandler.report(e, params: params)
  render_error_response(error_message: ApiVendorV1::Constants::VENDOR_INTERNAL_SERVER_ERROR)
end