Class: Admin::ReservationsController

Inherits:
BaseController show all
Includes:
Modules::Reservations::AddOns, Modules::Reservations::Packages, ReservationHistory
Defined in:
app/controllers/admin/reservations_controller.rb

Constant Summary

Constants inherited from BaseController

BaseController::INTERNAL_SERVER_ERROR_MESSAGE

Instance Method Summary collapse

Methods included from ReservationHistory

#history, #history_result

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

Instance Method Details

#add_on_paramsObject



742
743
744
745
746
747
748
749
# File 'app/controllers/admin/reservations_controller.rb', line 742

def add_on_params
  return [] if params[:add_ons].blank?

  params.permit![:add_ons][:add_ons]
rescue StandardError => e
  APMErrorHandler.report(e)
  []
end

#audit_dataObject



15
16
17
# File 'app/controllers/admin/reservations_controller.rb', line 15

def audit_data
  @reservation = Reservation.fetch params.require :reservation_id
end

#bulk_sms_recipientsObject



126
127
128
129
130
131
132
133
# File 'app/controllers/admin/reservations_controller.rb', line 126

def bulk_sms_recipients
  render json: {
    success: true,
    data: {
      total_recipients: @reservations.size,
    },
  }
end

#bulk_updateObject



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

def bulk_update
  ids = params.fetch(:ids, []).map(&:to_i)
  result = false

  ActiveRecord::Base.transaction do
    Reservation.where(id: ids).each do |reservation|
      permitted_param = params.require(:reservation).permit!.dup
      permitted_param.each do |k, v|
        next unless k.to_s.include?('attributes')

        attr = k.to_s.split('_attributes').first.to_sym
        obj = reservation.send(attr)
        v['id'] = obj.id
      end
      reservation.update! permitted_param
      reservation.touch
      begin
        reservation.trigger_summary_sync
      rescue StandardError => e
        APMErrorHandler.report('Failed to sync reservation after admin update', {
                                 reservation_id: reservation.id,
                                 error_message: e.message,
                                 exception: e,
                               })
      end
    end
    result = true
  end
  if result
    render json: { success: true }
  else
    render json: { success: false }
  end
end

#calculate_package_priceObject



328
329
330
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
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
# File 'app/controllers/admin/reservations_controller.rb', line 328

def calculate_package_price
  # Initialize the calculator and response variables
  calculator = HhPackage::ReservationPackages::ChargeCalculator.new
  success = false
  message = ''
  data = {}
  reservation_param = params[:reservation]

  # Fetch reservation, user, and restaurant
  reservation = Reservation.find_by(id: reservation_param[:id])
  user = reservation&.user
  restaurant = Restaurant.fetch(reservation_param[:restaurant_id])

  # Permit and process packages parameters
  params_package_bought = params.require(:reservation).permit(
    packages: [
      :id,
      :quantity,
      {
        menu_sections: [
          :id,
          { menus: %i[id quantity] },
        ],
        selected_special_menus: [:id, :quantity],
        group_sections: [:id, :quantity],
      },
    ],
  )

  # Permit and process add-ons parameters
  params_add_on_bought = params.require(:reservation).permit(
    add_ons: [
      :id,
      :quantity,
    ],
  )

  # Process the packages
  package_processor = PackageServices::Processor.new(params_package_bought, restaurant, reservation_param[:adult])
  package_bought, is_valid_mix_n_match = package_processor.process_packages

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

  # Process the add-ons
  add_on_processor = AddOnServices::Processor.new(params_add_on_bought, restaurant, reservation_param[:adult])
  add_on_bought = add_on_processor.process_add_ons

  # Set up the calculator
  calculator.set_delivery_pricing_tiers(restaurant.delivery_pricing_tiers)
  calculator.set_user(user&.id)

  # Set refund guarantee if specified
  accept_refund = reservation_param[:accept_refund].to_s == 'true'
  calculator.accept_refund = accept_refund

  # Set custom refund fee if provided by admin
  custom_refund_fee_cents = reservation_param[:custom_refund_fee_cents].to_i
  if custom_refund_fee_cents > 0
    calculator.custom_refund_fee_cents = custom_refund_fee_cents
  end

  # Calculate the package price (including add-ons)
  begin
    date = reservation_param[:date].present? ? reservation_param[:date].to_date : Time.now_in_tz(restaurant.time_zone).to_date.tomorrow
    calculator.use_dynamic_pricing = date == reservation_param[:date].present?

    data = calculator.calculate(
      package_bought,
      reservation_param[:adult],
      reservation_param[:kids],
      0.0,
      restaurant,
      date,
      add_on_bought,
    )
    success = true
  rescue StandardError => e
    raise e if Rails.env.development?

    APMErrorHandler.report(e)
    Rails.logger.error e
    message = INTERNAL_SERVER_ERROR_MESSAGE
  end

  render json: { success: success, message: message, data: data }
rescue ActiveRecord::RecordNotFound
  raise RecordNotFoundButOk
rescue InvalidPackageData => e
  render json: { success: false, message: e.message, data: {} }
end

#cancelObject



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

def cancel
  cancellation_params = params.require(:cancellation).permit(:reservation_id, :reason, :other_reason)
  reason = if cancellation_params[:reason] == 'other' && cancellation_params[:other_reason].present?
             cancellation_params[:other_reason]
           else
             cancellation_params[:reason]
           end
  is_claim_refund = reason == ReservationRefundGuarantee::CANCEL_REASON

  service = CancelReservationService.new(
    cancellation_params[:reservation_id],
    :admin,
    { require_reason: true, claim_refund: is_claim_refund },
  )
  service.cancel_reason = reason
  result = service.execute
  if result && is_claim_refund
    flash[:notice] = 'Booking cancelled and refund guarantee claimed successfully'
  elsif result
    flash[:notice] = 'Booking cancelled successfully'
  else
    flash[:error] = service.error_message_simple
  end
  redirect_to admin_reservations_path
end

#chargeObject



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

def charge
  reservation = Reservation.find(params[:reservation_id])
  redirect_to(admin_reservation_path, alert: 'Charge amount is empty') && return if params[:charge_amount].blank?

  token = case reservation.cc_provider.to_s.to_sym
          when :omise
            reservation&.customer&.customer_id
          when :gb_primepay
            card = reservation&.gb_primepay_card
            { 'token' => card.token } if card.present?
          else
            false
          end

  return redirect_to(admin_reservations_path, alert: 'Token not found') if token.blank?

  gateway = MyActiveMerchants::Gateway.new reservation.cc_provider
  gateway.store_card(token)
  gateway.reservation = reservation
  gateway.user = reservation.user if reservation.user.present?
  money_amount = Money.from_amount(params[:charge_amount], reservation.restaurant.default_currency)

  if gateway.charge(money_amount, use_3d_secure: false)
    reservation.save
    redirect_to(admin_reservations_path, notice: 'Charged successfully')
  else
    error_message = gateway.error_message_simple
    error_message = I18n.t('errors.use_different_card') if error_message.include?('fraud')
    redirect_to(admin_reservations_path, alert: error_message)
  end
end

#confirmObject



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

def confirm
  service = ReservationConfirmationService.new(params[:reservation_id], confirmed_by: :admin)

  type = params.require(:confirm_type)
  success = false
  message = case type
            when 'accept'
              success = service.accept
              (success ? 'Booking confirmed' : service.error_message_simple)
            when 'reject'
              success = service.reject
              (success ? 'Booking rejected' : service.error_message_simple)
            else
              INTERNAL_SERVER_ERROR_MESSAGE
            end

  respond_to do |format|
    format.html do
      redirect_back fallback_location: back_fallback_location, notice: message
    end
    format.json do
      render json: { message: message, success: success }
    end
  end
end

#createObject



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

def create
  res_params = reservation_params
  channel = Channel.find_by(channel_id: res_params[:channel])
  custom_refund_fee_cents = params.dig(:reservation, :custom_refund_fee_cents).to_i

  create_reservation_params = {
    reservation: res_params,
    guest_user: nil,
    user_id: res_params[:user_id],
    created_by: :admin,
    group_booking: false,
    business_booking: false,
    omise_token: '',
    channel: res_params[:channel],
    ack: res_params[:ack],
    voucher_code: params.dig(:reservation, :vouchers),
    medium: 'Web',
    restaurant_packages: package_params,
    vendor_name: channel&.oauth_application&.name,
    restaurant_add_ons: add_on_params,
    custom_refund_fee_cents: custom_refund_fee_cents,
  }

  service = ReservationService::Create.new(create_reservation_params.merge(user_params))
  if service.execute
    render json: { success: true, message: 'Reservation created successfully', data: service.reservation.id }
  else
    render json: { success: false, message: service.error_message_simple, data: nil }
  end
end

#deliveriesObject

rubocop:disable Metrics/AbcSize, Metrics/MethodLength



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/controllers/admin/reservations_controller.rb', line 20

def deliveries
  # rubocop:enable Metrics/AbcSize, Metrics/MethodLength
  reservations = Reservation.active_and_show_scope.
    exclude_temporary.
    includes(:user, :property, :driver,
             :address,
             :corporate_event,
             :delivery_channel,
             restaurant: [:translations, :order_now]).
    where(service_type: :delivery).
    left_joins(address: :driver)

  reservations = filter_deliveries(reservations)

  reservation_params = params.fetch(:reservation, {})

  if params.fetch(:upcoming, false).to_s == 'true' && params.fetch(:no_driver, false).to_s == 'true'
    reservations = reservations.where(date: Time.thai_time.to_date).
      where('start_time >= ?', Time.thai_time.strftime('%H:%M')).
      where("#{Reservation.table_name}.delivery_channel_id IS NULL").
      where("#{Driver.table_name}.id IS NULL")
  end

  sort_by = reservation_params.fetch(:sort_by, 'reservations.created_at DESC')
  reservations = reservations.order(sort_by) unless sort_by.nil?
  reservations = reservations.group('reservations.id')

  items = reservation_params.fetch(:items, 20).to_i
  items = 100 if items > 100
  @pagy, @reservations = pagy(reservations, items: items)
  @page_title = 'Booking Deliveries'
end

#delivery_trackingObject



53
54
55
56
57
# File 'app/controllers/admin/reservations_controller.rb', line 53

def delivery_tracking
  db_audit = DbAudit::DeliveryLogs::Query.new
  id = params.require(:reservation_id)
  @delivery_logs = db_audit.reservation_id_eq(id)['list']
end

#downloadObject



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
675
676
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
# File 'app/controllers/admin/reservations_controller.rb', line 620

def download
  if params['reservation'].present?
    permitted_parameters = params.require(:reservation).permit(
      :start_date, :end_date, :restaurant_id, :date_type, :start_time,
      :end_time, :date_filter_type, :restaurant_group_id, :pick_reservation,
      :restaurant_delivery_id, :start_date_delivery, :end_date_delivery,
      :country_id
    )

    if permitted_parameters[:pick_reservation] == 'raw'
      date_filter_type = permitted_parameters[:date_filter_type]
      start_time = permitted_parameters[:start_time]
      end_time = permitted_parameters[:end_time]
      restaurant_id = permitted_parameters[:restaurant_id]
      restaurant_group_id = permitted_parameters[:restaurant_group_id]
      country_ids = Array.wrap(permitted_parameters[:country_id].to_s.presence || nil)
      restaurant_id = nil if restaurant_group_id.present?

      if permitted_parameters[:date_type].blank?
        render json: { message: "Date type can't be blank" }
        return
      end

      if date_filter_type != 'single' && (permitted_parameters[:start_date].blank? || permitted_parameters[:end_date].blank?)
        render json: { message: 'Start date and End date must be present' }
        return
      end

      if date_filter_type == 'single' && (start_time.blank? || end_time.blank?)
        render json: { message: "Start time or end time can't be blank" }
        return
      end

      start_date = Date.strptime(permitted_parameters.require(:start_date), '%m/%d/%Y')
      end_date = if date_filter_type == 'single'
                   start_date
                 else
                   Date.strptime(
                     permitted_parameters.require(:end_date), '%m/%d/%Y'
                   )
                 end

      emails = if Rails.env.development?
                 [SUPPORT_EMAIL]
               else
                 [current_user&.email].compact
               end

      NotificationWorkers::ReservationReport.fix_queue_perform_async(
        :hh_staff,
        {
          emails: emails,
          restaurant_id: restaurant_id,
          restaurant_group_id: restaurant_group_id,
          start_date: start_date,
          end_date: end_date,
          date_type: permitted_parameters[:date_type],
          start_time: start_time,
          end_time: end_time,
          date_filter_type: date_filter_type,
          country_ids: country_ids,
        },
      )

      render json: { message: 'System will send you an email to download the report file' }
    else
      render json: { message: 'This feature is disabled now' }
    end
  else
    thailand = Country.find_thailand
    singapore = Country.find_singapore
    malaysia = Country.find_malaysia

    @countries = [
      ['All', nil],
      [thailand.name, thailand.id],
      [singapore.name, singapore.id],
      [malaysia.name, malaysia.id],
    ]
    render layout: nil
  end
end

#download_invoiceObject



703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'app/controllers/admin/reservations_controller.rb', line 703

def download_invoice
  if params['reservation'].present?
    permitted_parameters = params.require(:reservation).permit(:restaurant_id, :month)

    begin
      month = Date.parse(permitted_parameters[:month])
    rescue ArgumentError
      redirect_to(admin_reservations_path, alert: 'Please provide a valid month format') && (return)
    end
    start_date = month.beginning_of_month
    end_date = month.end_of_month

    NotificationWorkers::ReservationReport.fix_queue_perform_async(
      :restaurant_managers, {
        restaurant_id: permitted_parameters[:restaurant_id],
        start_date: start_date,
        to_hh_team_only: true,
        end_date: end_date,
        date_type: :date,
        emails: [SUPPORT_EMAIL, SUPPORT_EMAIL_SLACK,
                 current_user&.email].compact,
      }
    )

    redirect_to admin_reservations_path, notice: 'System will send you an email to download the report file'
  else
    render layout: nil
  end
end

#editObject



554
555
556
557
558
559
560
# File 'app/controllers/admin/reservations_controller.rb', line 554

def edit
  set_meta_tags title: 'Edit Booking'
  @reservation = Reservation.find(params[:id])
  @restaurants = Restaurant.all
  @custom_package_pricing = @reservation.custom_package_pricing.to_json if @reservation.custom_package_pricing?
  @force_update = params[:force_update]
end

#force_update_paramsObject



751
752
753
# File 'app/controllers/admin/reservations_controller.rb', line 751

def force_update_params
  params.permit(:force_update)
end

#group_sections_from_reservation(reservation) ⇒ Object



898
899
900
# File 'app/controllers/admin/reservations_controller.rb', line 898

def group_sections_from_reservation(reservation)
  SectionTrees.build_group_sections_from_reservation(reservation)
end

#indexObject



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

def index
  if params[:queries].blank?
    today = Time.now_in_tz('Asia/Bangkok').to_date
    redirect_to admin_reservations_path(queries: {
                                          start_date: today.beginning_of_month.strftime('%Y-%m-%d'),
                                          end_date: today.end_of_month.strftime('%Y-%m-%d'),
                                        })
    return
  end

  set_meta_tags title: 'Reservation List'
  translation_table_name = Restaurant::Translation.table_name
  @restaurants = Restaurant.includes(:translations).order("#{translation_table_name}.name ASC")
  @channels = Channel.all.order(:channel_id)
  @dining_occasion = Dimension.includes(:translations).occasion_scope.order('order_number asc')
  @corporate_events = ::Corporates::Event.all

  @reservations = if params[:queries].present? && params.require(:queries).fetch(:id, nil).present?
                    Reservation.order("#{Reservation.table_name}.id DESC")
                  else
                    Reservation.where(for_locking_system: false,
                                      adjusted: false).order("#{Reservation.table_name}.id DESC")
                  end

  if params[:queries].present?
    id = params.require(:queries).fetch(:id, nil)
    filter_by_id(id) if id.present?
    filter_by_vendor_reservation_id
    filter_by_status
    filter_normal_queries
    filter_mixed_queries
    filter_date_queries
    filter_time_queries
    filter_by_package_type
    filter_by_corporate_event
    filter_by_country_id
    sort_by
  end

  return '' if @reservations.nil?

  per_page = params[:perPage].present? ? params[:perPage].to_i : 20
  @pagy, @reservations = pagy @reservations, items: per_page
  @reservation_history_link = true

  return unless stale? @reservations

  @reservations = @reservations.includes(:user, :driver, :property,
                                         :booking_channel, :active_reservation_vouchers,
                                         :corporate_event,
                                         :active_vouchers, :charges, :menu_sections,
                                         restaurant: :translations,
                                         address: %i[driver delivery_channel])
end

#mark_as_arrivedObject



59
60
61
62
63
64
65
66
67
# File 'app/controllers/admin/reservations_controller.rb', line 59

def mark_as_arrived
  reservation = Reservation.find(params[:reservation_id])
  service = MarkReservationArrivedService.new(reservation.id)
  if service.execute
    render json: { success: true }
  else
    render json: { success: false, message: service.error_message_simple }
  end
end

#newObject



124
# File 'app/controllers/admin/reservations_controller.rb', line 124

def new; end

#package_paramsObject



733
734
735
736
737
738
739
740
# File 'app/controllers/admin/reservations_controller.rb', line 733

def package_params
  return [] if params[:packages].blank?

  params.permit![:packages][:packages]
rescue StandardError => e
  APMErrorHandler.report(e)
  []
end

#populate_seedObject



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
841
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
# File 'app/controllers/admin/reservations_controller.rb', line 804

def populate_seed
  seed_cache_key = [
    'admin/reservations',
    I18n.locale,
    Restaurant.count,
    Restaurant::Translation.maximum(:updated_at),
    Channel.maximum(:updated_at),
  ]
  seed = Rails.cache.fetch(CityHash.hash64(seed_cache_key.join('/')), expires_in: CacheFlow.new.generate_expiry) do
    {
      restaurant_list: Restaurant.includes(:translations).find_each.map { |r| { label: r.name.to_s, value: r.id } },
      channel_list: Channel.all.map { |c| { label: "#{c.name} (#{c.channel_id})", value: c.channel_id } },
    }
  end
  if params[:id].present?
    r = Reservation.fetch(params[:id])
    property = r.property.presence || r.build_property
    supplier_reservation = r.vendor_reservation&.supplier_reservation_id.present?
    supplier_name = 'HungryHub'
    if r.vendor_reservation.present?
      vendor_booking_id = r.vendor_reservation&.reference_id
      supplier_name = if r.by_tablecheck?
                        'TableCheck'
                      elsif r.by_seven_rooms?
                        'SevenRooms'
                      elsif r.by_weeloy?
                        'Weeloy'
                      elsif r.by_bistrochat?
                        'BistroChat'
                      elsif r.by_mymenu?
                        'MyMenu'
                      else
                        supplier_name
                      end
    end

    seed[:reservation] = {
      id: r.id,
      restaurant_id: r.restaurant_id,
      date: r.date,
      start_time: r.start_time_format,
      user_id: r.user_id,
      name: r.name,
      email: r.email,
      phone: r.phone,
      adult: r.adult,
      kids: r.kids,
      special_request: r.special_request,
      note: r.note,
      channel: r.channel,
      is_temporary: r.is_temporary?,
      for_locking_system: r.for_locking_system?,
      ack: r.ack,
      active: r.active,
      arrived: r.arrived,
      no_show: r.no_show,
      vendor_booking_id: vendor_booking_id,
      voucher_code: r.voucher&.voucher_code,
      is_prepayment: property.is_prepayment,
      prepayment_cents: property.prepayment_cents.presence || 0,
      prepayment_currency: property.prepayment_currency.presence || r.restaurant&.currency_code || 'THB',
      covered_by_hh: property.covered_by_hh?,
      service_type: r.service_type,
      group_booking: r.group_booking,
      self_pickup_ack: r.self_pickup_ack,
      address: {
        id: r.address&.id,
        detail: r.address&.detail,
        lon: r.address&.lon,
        lat: r.address&.lat,
        note_for_driver: r.address&.note_for_driver,
      },
      guests: r.guests,
      vouchers: r.vouchers.map(&:voucher_code),
      is_supplier_reservation: supplier_reservation,
      force_update_alert_message: I18n.t('reservation.force_update_alert', supplier_name: supplier_name),
    }
    seed[:reservation][:packages] = selected_packages(r) if r.package.present?
    seed[:reservation][:package_type] = property.package[:package_type]
    seed[:reservation][:add_ons] = selected_add_ons(r) if r.add_on.present?
    seed[:reservation][:group_sections] = group_sections_from_reservation(r) if r.group_sections.present?

    # Add refund guarantee data
    refund_guarantee = r.refund_guarantee
    seed[:reservation][:accept_refund] = refund_guarantee.present?
    seed[:reservation][:custom_refund_fee_amount] =
      if refund_guarantee&.refund_fee_cents
        refund_amount = HhMoney.new(refund_guarantee.refund_fee_cents, refund_guarantee.refund_currency).amount
        refund_amount % 1 == 0 ? refund_amount.to_i : refund_amount
      end
  end
  @seed = seed.to_json
end

#refundObject



541
542
543
544
545
546
547
548
549
550
551
552
# File 'app/controllers/admin/reservations_controller.rb', line 541

def refund
  reservation = Reservation.find(params[:reservation_id])

  service = ShopeePayService::RefundInvoice.new(reservation)
  if service.execute
    flash[:notice] = 'Booking refund successfully'
  else
    flash[:error] = reservation.errors.full_messages.to_sentence
  end

  redirect_to admin_reservations_path
end

#reservation_historyObject



917
918
919
920
921
922
923
924
# File 'app/controllers/admin/reservations_controller.rb', line 917

def reservation_history
  reservation_id = params[:id]
  history(reservation_id)
  @reservations = Reservation.where(id: history_result.to_a)
  @allow_reservation_history = true
  per_page = params[:perPage].present? ? params[:perPage].to_i : 100
  @pagy, @reservations = pagy @reservations, items: per_page
end

#reservation_paramsObject



755
756
757
758
759
760
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
# File 'app/controllers/admin/reservations_controller.rb', line 755

def reservation_params
  attributes = %I[restaurant_id date start_time user_id name email phone
                  adult kids special_request note service_type is_temporary
                  for_locking_system self_pickup_ack channel ack active
                  arrived no_show address_attributes]
  par = params[:reservation].permit(*attributes)

  par[:property_attributes] =
    params.require(:reservation).permit(
      :is_prepayment, :prepayment_cents, :prepayment_currency, :covered_by_hh, :accept_refund
    )
  par[:property_attributes][:custom_refund_fee_cents] = params.dig(:reservation, :custom_refund_fee_cents).to_i

  address_attributes = params.require(:reservation).fetch(:address, {}).permit(:id, :lon, :lat, :detail,
                                                                               :note_for_driver)
  if address_attributes.values.compact.present?
    par[:address_attributes] = address_attributes.tap do |address|
      address[:name] = 'default'
    end.permit!
  end

  guests_attributes = params.require(:reservation).permit(guests: %i[id phone name created_by _destroy]).fetch(
    :guests, []
  ).compact
  if guests_attributes.present?
    par[:guests_attributes] = guests_attributes.tap do |guests|
      guests.each do |guest|
        guest[:created_by] = :admin
      end
    end
  end

  if params[:reservation][:vendor_booking_id].present?
    par[:vendor_booking_id] = params[:reservation][:vendor_booking_id]
  end

  par
end

#section_trees(reservation = Reservation.find_by(id: params[:reservation_id])) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/MethodLength



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

def section_trees(reservation = Reservation.find_by(id: params[:reservation_id]))
  # rubocop:enable Metrics/AbcSize, Metrics/MethodLength
  restaurant_package_id = params[:pack_id]
  if restaurant_package_id.blank?
    return render json: { data: [] }
  end

  restaurant_package = HhPackage::RestaurantPackage.find(restaurant_package_id)
  menu_sections = HhPackage::Package::MenuSection.includes(:translations,
                                                           menus: %i[subsections
                                                                     translations]).
    where(package: restaurant_package.package).map do |section|
    reservation_section = reservation&.menu_sections&.find_by(package_menu_section_id: section.id)
    mapped_menus = section.menus.map do |menu|
      reservation_menu = reservation_section&.menus&.find_by(package_menu_id: menu.id)
      subsections = menu.subsections.map do |subsection|
        reservation_subsection = reservation_menu&.subsections&.find_by(package_menu_section_id: subsection.id)
        submenus = subsection.menus.map do |submenu|
          reservation_submenu = reservation_subsection&.menus&.find_by(package_menu_id: submenu.id)
          # section submenu
          {
            id: submenu.id,
            name: submenu.name,
            quantity: reservation_submenu&.quantity || 0,
          }
        end
        {
          id: subsection.id,
          quantity_limit: subsection.quantity_limit,
          name: subsection.name,
          menus: submenus,
        }
      end

      # section menu
      {
        id: menu.id,
        name: menu.name,
        quantity: reservation_menu&.quantity || 0,
        subsections: subsections,
      }
    end
    { name: section.name, id: section.id, quantity_limit: section.quantity_limit, menus: mapped_menus }
  end

  render json: {
    data: menu_sections,
  }
end

#send_bulk_sms_recipientsObject



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'app/controllers/admin/reservations_controller.rb', line 135

def send_bulk_sms_recipients
  message = params[:msg]

  phones = Set.new
  @reservations.includes(:user).find_each do |r|
    phone = r.phone
    next if phone.nil?

    phones << phone
  end

  phones.each do |phone|
    SmsWorker.perform_async(message, phone)
  end

  render json: {
    success: true,
    message: 'send broadcast message successfully',
  }
end

#send_notificationObject



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

def send_notification
  confirm_type = params.require(:confirm_type).to_s.to_sym
  id = params.require(:reservation_id)
  receivers = params.fetch(:receivers, :all).to_s.to_sym

  case confirm_type
  when :create
    case receivers
    when :restaurant
      notification = NotificationWorkers::Reservation.new
      notification.reservation = Reservation.find id
      notification.state = :create
      notification.ack_has_offers_notif_confirmed_by_email({ receiver: ['owner'] })
      notification.ack_has_offers_notif_confirmed_by_sms({ receiver: ['owner'] })
    when :user
      notification = NotificationWorkers::Reservation.new
      notification.reservation = Reservation.find id
      notification.state = :create
      notification.ack_has_offers_notif_confirmed_by_email({ receiver: ['user'] })
      notification.ack_has_offers_notif_confirmed_by_sms({ receiver: ['user'] })
    else
      NotificationWorkers::Reservation.perform_async(id, :create)
    end
    render json: { success: true }
  else
    raise NotImplementedError
  end
end

#send_smsObject



902
903
904
905
906
907
908
909
910
911
912
913
914
915
# File 'app/controllers/admin/reservations_controller.rb', line 902

def send_sms
  permitted_param = params.require(:sms).permit(:reservation_id, :message)
  reservation_id = permitted_param[:reservation_id]
  phone = Reservation.fetch(reservation_id).phone

  message = permitted_param[:message]

  if message.to_s.strip.blank?
    render json: { success: false }, status: :unprocessable_entity
  else
    SmsWorker.perform_async(message, phone, reservation_id)
    render json: { success: true }
  end
end

#trigger_aoa_webhookObject



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

def trigger_aoa_webhook
  reservation = Reservation.fetch(params[:reservation_id])
  time_zone = reservation.restaurant.time_zone || 'Asia/Bangkok'
  current_time = Time.current.in_time_zone(time_zone)
  twenty_four_hours_later = reservation.reservation_time.twenty_four_hours_later

  status = if current_time > twenty_four_hours_later
             :arrived
           else
             reservation.status_as_symbol
           end

  BUSINESS_LOGGER.set_business_context({ reservation_id: reservation.id, status: status })
  BUSINESS_LOGGER.info(
    "#{self.class}: Aoa::WebhookWorker called from trigger_aoa_webhook method with status #{status}", status: status
  )
  Aoa::WebhookWorker.perform_async(reservation.id, status)

  render json: { success: true }
rescue ActiveRecord::RecordNotFound => e
  render json: { success: false, message: "Reservation not found: #{e.message}" }, status: :not_found
rescue StandardError => e
  APMErrorHandler.report(e)
  render json: { success: false, message: 'Webhook worker failed' }, status: :unprocessable_entity
end

#updateObject



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

def update
  # Handle mark as paid separately
  if params.require(:reservation).fetch(:mark_as_paid, false).to_s == 'true'
    update_reservation_as_paid
    return
  end

  channel = Channel.find_by(channel_id: reservation_params[:channel])
  if reservation_params[:vendor_booking_id].present? && channel&.oauth_application.blank?
    message = 'Please select the correct channel for 3rd party partner booking'
    return render json: { success: false, message: message }
  elsif reservation_params[:vendor_booking_id].blank? && channel&.oauth_application.present? &&
      !channel.oauth_application.name.include?(ApiVendorV1::Constants::GOOGLE_RESERVE_VENDOR_NAME)
    message = '3rd party partner booking id can not be blank'
    return render json: { success: false, message: message }
  end

  voucher_codes = params.dig(:reservation, :vouchers)
  covered_by_hh = params.require(:reservation).fetch(:covered_by_hh, false)

  update_operation = Agents::UpdateForAdmin.new(
    params[:id], reservation_params, force_update_params[:force_update], current_user
  )
  update_operation.assign_vouchers(voucher_codes)
  update_operation.build_section_trees(package_params)
  update_operation.build_group_section_trees(package_params)

  # Handle packages: preserve existing if none provided, update if provided
  current_reservation = update_operation.reservation

  if package_params.present?
    unless update_operation.assign_packages(package_params, reservation_params, covered_by_hh)
      message = "Can not update packages. #{update_operation.error_message}"
      return render json: { success: false, message: message }
    end
  elsif current_reservation.property&.package.present?
    # Preserve existing packages if no new packages provided
    begin
      update_operation.assign_existing_packages
    rescue StandardError => e
      APMErrorHandler.report(e, context: {
                               reservation_id: current_reservation.id,
                               error_message: 'Failed to preserve existing packages during admin update',
                             })
    end
  end

  # Handle add-ons: preserve existing if none provided, update if provided
  if add_on_params.present?
    unless update_operation.assign_add_ons(add_on_params, reservation_params)
      message = "Can not update add-ons. #{update_operation.error_message}"
      return render json: { success: false, message: message }
    end
  elsif current_reservation.property&.add_on.present?
    # Preserve existing add-ons if no new add-ons provided
    begin
      update_operation.assign_existing_add_ons
    rescue StandardError => e
      APMErrorHandler.report(e, context: {
                               reservation_id: current_reservation.id,
                               error_message: 'Failed to preserve existing add-ons during admin update',
                             })
      message = 'Failed to preserve existing add-ons. Please try again or contact support.'
      respond_to do |format|
        format.json do
          render json: { success: false, message: message }
        end
        format.html do
          redirect_back(fallback_location: admin_reservations_path, alert: message)
        end
      end
      return
    end
  end

  if update_operation.update_booking
    respond_to do |format|
      format.json do
        render json: { success: true }
      end
      format.html do
        redirect_back(fallback_location: admin_reservations_path, notice: 'success')
      end
    end
  else
    respond_to do |format|
      format.json do
        render json: { success: false, message: update_operation.error_message }
      end
      format.html do
        redirect_back(fallback_location: admin_reservations_path, alert: update_operation.error_message)
      end
    end
  end
end

#user_paramsObject



794
795
796
797
798
799
800
801
802
# File 'app/controllers/admin/reservations_controller.rb', line 794

def user_params
  user_par = {}
  if reservation_params[:user_id].nil?
    user_par[:guest_user] = params.require(:reservation).permit(:name, :email, :phone)
  else
    user_par[:user_id] = reservation_params[:user_id]
  end
  user_par
end