Class: Api::V5::ReservationsController

Inherits:
BaseController
  • Object
show all
Includes:
Concerns::Authorization, Concerns::PaginationParam, Concerns::TmpReservation, EncryptableHelper
Defined in:
app/controllers/api/v5/reservations_controller.rb

Constant Summary

Constants inherited from BaseController

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

Instance Method Summary collapse

Methods included from EncryptableHelper

#decrypt, #encrypt, #generate_signature

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

#claim_refundObject



542
543
544
545
546
547
548
549
550
551
552
553
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
# File 'app/controllers/api/v5/reservations_controller.rb', line 542

def claim_refund
  reservation = Reservation.fetch(params.require(:reservation_id))
  if reservation.user_id != current_user.id
    return render json: {
      success: false,
      message: 'You are not authorized to access this reservation',
      data: nil,
    }, status: :forbidden
  end

  service = CancelReservationService.new(reservation.id, :user, { require_reason: true, claim_refund: true })
  service.cancel_reason = ReservationRefundGuarantee::CANCEL_REASON
  if service.execute
    render json: {
      success: true,
      data: nil,
      message: I18n.t('actions.reservation.refund_claimed'),
    }
  else
    render json: {
      success: false,
      data: nil,
      message: service.error_message_simple,
    }, status: :unprocessable_entity
  end
rescue ActiveRecord::RecordNotFound, ActionController::ParameterMissing
  render json: {
    success: false,
    message: 'Reservation not found',
    data: nil,
  }, status: :not_found
rescue StandardError => e
  APMErrorHandler.report(e, context: {
                           reservation_id: params[:reservation_id],
                           user_id: current_user&.id,
                           action: 'claim_refund',
                           timestamp: Time.current,
                         })

  BUSINESS_LOGGER.error(
    'Failed to process refund guarantee claim',
    {
      reservation_id: params[:reservation_id],
      user_id: current_user&.id,
      error_class: e.class.name,
      error_message: e.message,
      backtrace: e.backtrace&.first(5),
    },
  )

  render json: {
    success: false,
    message: 'Sorry, something went wrong',
    data: nil,
  }, status: :internal_server_error
end

#createObject



16
17
18
19
20
21
22
23
24
25
# File 'app/controllers/api/v5/reservations_controller.rb', line 16

def create
  ActiveRecord::Base.connection.stick_to_master! if ActiveRecord::Base.connection.respond_to?(:stick_to_master!)

  reservation_id = params[:tmp_reservation_id]
  if reservation_id.present?
    create_v2
  else
    create_v1
  end
end

#create_v1Object



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

def create_v1
  is_group_booking = params.fetch(:big_group, false)
  restaurant_packages_params = if params[:packages].present?
                                 params.permit(packages: [:id, :quantity, {
                                                 menu_sections: [:id, :quantity,
                                                                 { menus: [:id, :quantity, { subsections: [box: [:id, { menus: %i[id quantity] }]] }] }],
                                                 group_sections: [:id, :quantity],
                                               }])[:packages]
                               else
                                 []
                               end
  we_travel_together_params = if params[:we_travel_together].present?
                                params.require(:we_travel_together).permit(:wtt_id_card, :wtt_phone)
                              else
                                {}
                              end

  nested_package_params = restaurant_packages_params.map(&:to_h)
  nested_package_params.map do |package|
    next if package[:menu_sections].blank?

    package[:menu_sections].map do |ms|
      temp_menus = ms.delete :menus
      ms[:menus] = []
      temp_menus.map do |menu|
        if menu[:subsections].present?
          temp_subsections = menu.delete :subsections

          temp_subsections.map do |subsection|
            # re create and duplicate box as menus
            menu[:quantity] = 1
            new_menus = menu.merge(subsections: subsection[:box])

            ms[:menus] << new_menus
          end
        else
          ms[:menus] << menu
        end
      end
    end
  end

  reservation_param = params.require(:reservation).permit(
    :date,
    :start_time,
    :adult,
    :kids,
    :service_type,
    :delivery_address,
    :distance_to_restaurant,
    :special_request,
    :dining_occasion_id,
    :restaurant_id,
    :promo_code,
    :is_order_now,
    :click_id,
    :adv_partner,
    :pay_now,
    :redeemed_amount,
    :accept_we_travel_together,
    :accept_refund_guarantee,
  ).tap do |param|
    param[:restaurant_id] = if restaurant_packages_params.present?
                              package = HhPackage::RestaurantPackage.fetch(restaurant_packages_params.first[:id])
                              package.restaurant_id
                            else
                              param[:restaurant_id]
                            end
    param[:date] = Date.parse(param[:date]).to_s if param[:date].present?
  end

  fb_conversion_params = if params.key?(:fb_conversion)
                           params.require(:fb_conversion).permit(:fbp, :fbc).merge({
                                                                                     ip_address: request.remote_ip,
                                                                                     user_agent: browser.ua,
                                                                                     event_source_url: request.referrer,
                                                                                     action_source: parse_medium_source,
                                                                                     event_time: Time.zone.now.to_i,
                                                                                   })
                         else
                           {}
                         end

  if params[:reservation][:pay_now].present?
    pay_now = params[:reservation][:pay_now]
    reservation_param[:pay_now] = pay_now.to_s == 'true'
  else
    reservation_param[:pay_now] = false
  end

  create_reservation_params = {
    is_load_test: params.fetch(:is_load_test, false),
    line_id: (params.key?(:guest_user) && params[:guest_user].key?(:line_id) && params[:guest_user][:line_id]) || nil,
    reservation: reservation_param,
    address: params.fetch(:address, {})&.permit(:detail, :lat, :lon, :name, :note_for_driver, :phone) || {},
    user_id: params.key?(:access_token) && params.key?(:provider) && authorize! && user_signed_in? ? current_user.id : nil,
    address_id: params.fetch(:address_id, nil),
    guest_user: params.key?(:guest_user) ? params.require(:guest_user).permit(:name, :email, :phone) : nil,
    channel: parse_channel_source,
    medium: parse_medium_source,
    created_by: :user,
    group_booking: is_group_booking,
    business_booking: false,
    omise_token: params.fetch(:omise_token, ''),
    omise_payment_type: params.fetch(:omise_payment_type, nil),
    payment_type: params.fetch(:payment_type, nil),
    gb_primepay_card: params.fetch(:gb_primepay_card, {}),
    restaurant_packages: nested_package_params,
    voucher_code: params.require(:reservation).fetch(:voucher_code, nil),
    guests_attributes: params.key?(:guests_attributes) && params.permit(guests_attributes: %i[name
                                                                                              phone])[:guests_attributes],
    reservation_we_travel_together_attributes: we_travel_together_params,
    fb_conversion_params: fb_conversion_params,
    corporate_event_id: params[:corporate_event_id],
    redeemed_points: params[:redeemed_points],
  }.tap do |param|
    param.each do |key, value|
      param[key] = value.permit!.to_h if value.is_a?(ActionController::Parameters)
    end
  end

  async_booking = params.fetch(:async_booking, false)
  if async_booking
    form = ReservationService::FormFactory.new(create_reservation_params).create_form_service
    success = false

    if form.validate
      date = Date.today
      time = Time.zone.now.strftime('%H:%M')
      code = SecureRandom.hex(5).downcase
      reservation_tracking_key = "reservation_tracking/date-#{date}/time-#{time}/random-#{code}"
      firebase = MyFirebase.new
      response = firebase.update(reservation_tracking_key, { status: :loading })

      if response.success?
        create_reservation_params.tap do |h|
          h[:guest_user] = h[:guest_user].present? && h[:guest_user].to_h
          h[:reservation] = h[:reservation].to_h
          h[:address] = h[:address].to_h
          h[:gb_primepay_card] = h[:gb_primepay_card].to_h
          h[:guests_attributes] = h[:guests_attributes].is_a?(Array) && h[:guests_attributes].map(&:to_h)
        end
        Workers::Reservations::CompleteWorker.perform_async(create_reservation_params, reservation_tracking_key)

        success = true
      else
        form.errors.add(:base, 'failed to create reservation')
        success = false
      end
    end

    if success
      set_status_header(true)
      render json: {
        success: true,
        firebase_key: reservation_tracking_key,
      }
    else
      set_status_header(false)
      render json: { success: false, message: form.error_message_simple, data: nil }
    end
  else
    service = ReservationService::Create.new(create_reservation_params)
    if service.execute
      set_status_header(true)
      options = {
        include: DEFAULT_INCLUDE,
      }
      render json: resource_as_json(service.outcome, Api::V5::ReservationSerializer, options).merge(
        success: true,
        message: I18n.t('actions.reservation.created'),
        meta: {
          misc: misc(service.outcome),
        },
      )
    else
      set_status_header(false)
      render json: { success: false, message: service.error_message_simple, data: nil }
    end
  end
rescue StandardError => e
  if Rails.env.production?
    APMErrorHandler.report(e)
    render json: { success: false, message: 'Sorry, something went wrong', data: nil }
  else
    raise e
  end
end

#detailObject



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

def detail
  reservation = Reservation.fetch(Reservation.decrypt_id(params.require(:reservation_id)))
  reservation_start_time = Time.zone.parse("#{reservation.date} #{reservation.start_time}").in_time_zone(reservation.restaurant.time_zone)
  now = Time.current.in_time_zone(reservation.restaurant.time_zone)

  if reservation.is_order_now?
    raise ApiV5::Errors::AuthenticationError if (reservation.reservation_time + 24.hours).past?
  elsif reservation.is_past? && (reservation.restaurant.dine_in_min_booking_time_in_advance > 0 || reservation_start_time <= now - 24.hours)
    raise ApiV5::Errors::AuthenticationError
  end

  qr_code_expiry_at = (reservation.created_at + AdminSetting.prompt_pay_count_down_in_minute.to_i.minute + 30.seconds)
  if reservation.promptpay_provider.present? && reservation.paid_at.blank? && qr_code_expiry_at <= Time.zone.now
    raise ApiV5::Errors::AuthenticationError
  end

  cache_key = "#{self.class}:detail:#{reservation.cache_key}:#{MyLocaleManager.normalize_locale}"
  my_response_cache cache_key, :json do
    JSON.parse(
      render_to_string(
        json: reservation,
        serializer: Api::V5::ReservationSerializer,
        adapter: :json_api,
        include: DEFAULT_INCLUDE,
      ),
    ).merge(success: true)
  end
rescue ActiveRecord::RecordNotFound
  render json: {
    success: false,
    message: 'Reservation not found',
    data: nil,
  }
end

#indexObject



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

def index
  set_status_header(true)
  filter = Api::V5::ReservationsFilter.new
  filter.init_default(current_user)

  section_type = params.fetch(:section_type, '')
  if section_type.present?
    case section_type
    when 'upcoming'
      filter.dining_time(Time.thai_time, 'gte').
        active_only(true).
        not_pending(true)
    when 'pending'
      filter.dining_time(Time.thai_time, 'gte').
        active_only(true).
        pending(true)
    when 'past'
      filter.dining_time(Time.thai_time, 'lt')
    when 'big_group'
      filter.dining_time(Time.thai_time, 'gte').
        active_only(true).
        pending_confirmation(true).
        group_booking(true)
    else
      set_status_header(false)
      return render json: { success: false, data: nil, message: 'Invalid section_type value' }
    end
  end

  filter.exclude_no_package(params.fetch(:exclude_no_package, false)).
    order_by(params.fetch(:order_by, nil)).
    page_number(page_number_param).
    per_page(page_size_param)

  options = { include: DEFAULT_INCLUDE }
  render json: filter.as_json(serialization_context, minor_version_param, options).merge(success: true, message: nil)
end

#need_reviewObject



270
271
272
273
274
275
276
277
278
279
280
# File 'app/controllers/api/v5/reservations_controller.rb', line 270

def need_review
  set_status_header(true)
  filter = Api::V5::ReservationsFilter.new
  filter.init_default(current_user).
    order_by(params.fetch(:order_by, nil)).
    page_number(page_number_param).
    per_page(page_size_param).
    need_review(true)
  options = { include: DEFAULT_INCLUDE }
  render json: filter.as_json(serialization_context, minor_version_param, options).merge(success: true, message: nil)
end

#packagesObject



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
480
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
530
531
532
533
534
535
536
537
538
539
540
# File 'app/controllers/api/v5/reservations_controller.rb', line 449

def packages
  id_param = params.require(:reservation_id)
  reservation = Reservation.find_by(id: id_param)
  if reservation.nil?
    vendor_reservation = VendorReservation.find_by(reference_id: id_param)
    reservation = vendor_reservation&.reservation
  end

  if reservation.nil?
    return render json: {
      success: false,
      message: 'invalid booking id',
      data: nil,
    }, status: :not_found
  end

  # Traverse the chain of modified reservations to find the most recent booking.
  # When a reservation is modified, the old one is marked as adjusted=true and
  # new_reservation_id points to the newly created reservation.
  # This ensures QR codes with old reservation IDs still work by redirecting to the current booking.
  original_reservation_id = reservation.id

  if reservation.new_reservation_id.present?
    modified_chain = reservation.modified_reservations
    last_modified_reservation = modified_chain.last

    if last_modified_reservation.present?
      if last_modified_reservation.active?
        # Use the last active reservation in the chain
        reservation = last_modified_reservation

        # Log reservation chain traversal for debugging
        if modified_chain.size > 1
          BUSINESS_LOGGER.set_business_context(
            original_reservation_id: original_reservation_id,
            final_reservation_id: reservation.id,
            restaurant_id: reservation.restaurant_id,
            traversal_count: modified_chain.size - 1,
          )
          BUSINESS_LOGGER.info('Modified reservation chain traversed in packages endpoint')
        end
      else
        # Last reservation in chain is inactive (cancelled), return error
        return render json: {
          success: false,
          message: 'booking has been cancelled',
          data: nil,
        }, status: :unprocessable_entity
      end
    end
  end

  # Check if reservation is past booking or booking status is not valid
  restaurant = reservation&.restaurant
  unless restaurant
    return render json: { success: false, message: 'invalid booking id', data: nil }, status: :not_found
  end

  time_zone = restaurant.time_zone
  if (reservation.reservation_time < Time.now_in_tz(time_zone) - 24.hours) ||
      [:pending_arrival, :arrived].exclude?(reservation.status_as_symbol)
    return render json: {
      success: false,
      message: 'past booking detected or booking status is not valid',
      data: nil,
    }, status: :unprocessable_entity
  end

  cache_key = "#{self.class}:packages:#{reservation.cache_key}:#{MyLocaleManager.normalize_locale}"
  my_response_cache cache_key, :json do
    JSON.parse(
      render_to_string(
        json: reservation,
        serializer: Api::V5::Reservations::PackagesSerializer,
        adapter: :json_api,
        include: [],
      ),
    ).merge(success: true, message: nil)
  end
rescue ActionController::ParameterMissing => e
  render json: {
    success: false,
    message: e.message,
    data: nil,
  }, status: :unprocessable_entity
rescue StandardError => e
  render json: {
    success: false,
    message: e.message,
    data: nil,
  }, status: :internal_server_error
end

#reservation_checkinObject

POST api/v5/reservations/:reservation_id/check-in



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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'app/controllers/api/v5/reservations_controller.rb', line 371

def reservation_checkin
  reservation_id_param = params.require(:reservation_id)
  skip_email = params[:skip_email]

  reservation = Reservation.find_by(id: reservation_id_param)

  if reservation.nil?
    return render json: {
      success: false,
      message: 'Reservation not found',
      data: nil,
    }
  end

  kiosque_checkin = ::Kiosque::Checkin.new(reservation.id)

  # Refresh token if it's expired
  kiosque_checkin.refresh_authorization_if_expired('token')

  if skip_email.to_s != 'true' && (reservation.email != params[:email])
    return render json: {
      success: false,
      message: 'Invalid email',
      data: nil,
    }, status: :ok
  end

  valid_table_number = kiosque_checkin.validate_table_number
  unless valid_table_number
    return render json: {
      success: false,
      message: 'The table number is required.',
      data: nil,
    }, status: :ok
  end

  custom_menu_id_is_valid = kiosque_checkin.custom_menu_id_is_valid
  if !custom_menu_id_is_valid && Flipper.enabled?(:kiosque, reservation.restaurant)
    return render json: {
      success: false,
      message: 'Custom Menu ID is required.',
      data: nil,
    }, status: :ok
  end

  if reservation.present?
    if Flipper.enabled?(:kiosque,
                        reservation.restaurant) && reservation.kiosque_reservation.nil? && reservation.table.present?
      hh_checkin = kiosque_checkin.hh_checkin
    else
      hh_checkin = nil
    end

    if hh_checkin.to_s == 'true' || hh_checkin.nil?
      MarkReservationArrivedService.new(reservation.id).execute
      reservation.reload
      reservation.touch
    end
  end

  my_response_cache reservation.cache_key, :json do
    JSON.parse(
      render_to_string(
        json: reservation,
        serializer: Api::V5::ReservationSerializer,
        adapter: :json_api,
        include: DEFAULT_INCLUDE,
      ),
    ).merge(success: true)
  end
rescue ActionController::ParameterMissing => e
  render json: {
    data: nil,
    success: false,
    message: e.message,
  }, status: :unprocessable_entity
end

#showObject



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'app/controllers/api/v5/reservations_controller.rb', line 313

def show
  reservation = nil
  id_param = params.require(:id)
  begin
    reservation = Reservation.fetch(id_param)
  rescue ActiveRecord::RecordNotFound
    reservation = Reservation.fetch(Reservation.decrypt_id(id_param))
  end
  raise ApiV5::Errors::AuthenticationError if reservation.user_id != current_user.id

  my_response_cache reservation.cache_key, :json do
    JSON.parse(
      render_to_string(
        json: reservation,
        serializer: Api::V5::ReservationSerializer,
        adapter: :json_api,
        include: DEFAULT_INCLUDE,
      ),
    ).merge(success: true)
  end
end

#skip_reviewObject



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

def skip_review
  reservation = Reservation.fetch(params.require(:reservation_id))

  if reservation.user_id != current_user.id
    set_status_header(false)
    render json: { success: false, message: 'You are not authorized to access this reservation', data: nil }
    return
  end

  property = reservation.property || reservation.build_property

  if property.skip_review
    set_status_header(false)
    return render json: { success: false, message: 'Your reservation already marked to skip review', data: nil }
  end

  property.skip_review = true

  if property.valid? && property.save
    set_status_header(true)
    render json: {
      success: true,
      message: nil,
      data: nil,
    }
  else
    set_status_header(false)
    render json: { success: false, message: property.errors.full_messages.to_sentence, data: nil }
  end
end

#updateObject

Only support cancel for now



255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'app/controllers/api/v5/reservations_controller.rb', line 255

def update
  permitted_params = params.require(:reservation).permit(:active)
  unless permitted_params[:active].to_s == false.to_s
    return render json: { success: false, data: nil, message: 'Unsupported action' }
  end

  service = CancelReservationService.new params.require(:id), :user
  service.cancel_reason = 'Payment cancelled'
  if service.execute
    render json: { success: true, data: nil, message: I18n.t('actions.reservation.cancelled') }
  else
    render json: { success: false, data: nil, message: service.error_message_simple }
  end
end