Class: Dashboard::V2::ReservationsController

Inherits:
MainController show all
Includes:
MoneyRails::ActionViewExtension, ReservationHistory, ResponseCacheConcern
Defined in:
app/controllers/dashboard/v2/reservations_controller.rb

Direct Known Subclasses

Group::ReservationsController

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ReservationHistory

#history, #history_result

Methods included from ResponseCacheConcern

#my_response_cache

Methods inherited from MainController

#default_fallback_location, #default_url_options, #kiosque_callback

Methods included from LogrageCustomLogger

#append_info_to_payload

Methods included from Stimulus::TagController

#stimulus

Methods included from OwnerLoginMode

#current_owner, #group_owner_type?, #request_path_contain_group?, #single_owner_type?

Methods included from OwnerDashboardsHelper

#events_ajax_previous_link, #show_source

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 Attribute Details

#reservationObject (readonly)

Returns the value of attribute reservation.



19
20
21
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 19

def reservation
  @reservation
end

Instance Method Details

#apply_voucherObject



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
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 337

def apply_voucher
  action = params.require(:reservation).require(:action)

  reservation = Reservation.find(params.require(:reservation).require(:id))
  voucher_code = params.require(:reservation).require(:voucher_code)

  # cc_number = if reservation.payment_type_provider == 'credit_card'
  #               reservation.paid_charges.first&.cc_number
  #             end
  cc_number = nil

  voucher_param = {
    time_zone: reservation.restaurant.time_zone,
    voucher_code: voucher_code,
    user_id: reservation.user_id,
    restaurant_id: reservation.restaurant_id,
    phone: reservation.phone,
    email: reservation.email,
    date: reservation.date,
    cc_number: cc_number,
    adult: reservation.adult,
    kids: reservation.kids,
    distance_to_restaurant: reservation.distance_to_restaurant.to_f,
    service_type: reservation.service_type,
    client_type: reservation.medium,
  }

  form = VoucherForm::Apply.new(voucher_param, :restaurant_staff)

  if action.to_sym == :validate
    _validate_voucher(form)
  else
    _apply_voucher(reservation, form.vouchers)
  end
end

#cancelObject



272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 272

def cancel
  authorize @reservation
  service = CancelReservationService.new @reservation.id, :owner
  service.cancel_reason = "cancelled from owner dashboard. system didn't ask cancel reason"
  if service.execute
    redirect_to(
      current_owner.dashboard_v2_reservations_path,
      notice: 'Reservation canceled successfully',
    )
  else
    flash[:alert] = service.error_message_simple
    render :show
  end
end

#check_inventory_statusObject

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



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 375

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

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

#check_reservationObject



459
460
461
462
463
464
465
466
467
468
469
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 459

def check_reservation
  current_owner
  reservation = Reservation.find(params.require(:reservation_id))
  restaurant_ids = group_owner_type? ? current_owner.restaurant_ids : [current_owner.fetch_restaurant.id]
  valid = reservation.present? && restaurant_ids.include?(reservation.restaurant_id)
  if valid
    render json: { success: true, data: Dashboard::V2::ReservationSelfCheckinSerializer.new(reservation) }
  else
    render json: { success: false, message: 'reservation not found' }
  end
end

#confirmObject



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

def confirm
  service = ReservationConfirmationService.new(reservation.id, confirmed_by: :owner)
  message = ''

  success = if params[:confirm].to_s == 'true'
              message = 'Reservation confirmed successfully'
              service.accept
            else
              message = 'Reservation rejected successfully'
              service.reject
            end
  message = service.error_message_simple unless success
  reservation.reload
  data = ReservationForOwnerSerializer.new(reservation)
  render json: { success: success, message: message, data: data.as_json }
end

#createObject



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 207

def create
  restaurant = select_restaurant

  if restaurant.nil?
    respond_to do |format|
      format.json do
        render(json: { success: false, data: nil, errors: 'Invalid restaurant' })
      end
      format.html do
        flash[:alert] = 'Invalid restaurant'
        redirect_back fallback_location: back_fallback_location
      end
      return
    end
  end

  if restaurant.any_offers?
    create_package_reservation(restaurant)
  else
    create_normal_reservation(restaurant)
  end
end

#downloadObject



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
448
449
450
451
452
453
454
455
456
457
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 396

def download
  respond_to do |format|
    format.json do
      permitted_parameters = params.require(:reservation).permit(:start_date, :end_date, :date_type, :type,
                                                                 :restaurant_id, :start_time, :end_time, :date_filter_type, emails: [])
      date_filter_type = permitted_parameters[:date_filter_type]
      emails = (permitted_parameters[:emails].presence || []).to_set.add(current_user.email).to_a

      messages = []
      start_time = permitted_parameters[:start_time]
      end_time = permitted_parameters[:end_time]

      if permitted_parameters[:start_date].blank? || permitted_parameters[:end_date].blank?
        messages << 'Start date and End date must be present'
      end

      if permitted_parameters[:start_date].present? && permitted_parameters[:end_date].present? && permitted_parameters[:start_date].to_date > permitted_parameters[:end_date].to_date
        messages << 'Start date cannot be greater than end date.'
      end
      emails.each do |email|
        messages << "Email : #{email} is not valid" unless ::EmailValidator.valid?(email)
      end

      if date_filter_type == 'single' && (start_time.blank? || end_time.blank?)
        messages << "Start time or end time can't be blank"
      end

      if permitted_parameters[:end_date].to_date > permitted_parameters[:start_date].to_date.end_of_month
        messages << "End date can't be greater than end of month"
      end

      return render json: { status: 'failed', message: messages } if messages.present?

      restaurant = Restaurant.find Restaurant.decrypt_id(permitted_parameters[:restaurant_id])
      start_date = Time.use_zone(restaurant.time_zone) do
        Time.zone.parse permitted_parameters.require(:start_date)
      end
      end_date = Time.use_zone(restaurant.time_zone) do
        Time.zone.parse permitted_parameters.require(:end_date)
      end
      data_type = permitted_parameters.require(:type)
      NotificationWorkers::ReservationReport.fix_queue_perform_async(
        :owner_staff,
        {
          emails: emails,
          restaurant_id: restaurant.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,
          data_type: data_type,
        },
      )
      render json: { status: 'success', message: 'System will send you an email to download the report file' }
    end
    format.html do
      render layout: nil
    end
  end
end

#editObject



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
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 160

def edit
  set_meta_tags title: 'Edit Reservation'
  restaurant = select_restaurant
  @error_message = params[:error_message]
  @force_update = params[:force_update]
  if restaurant.any_offers?
    @operation = PackageBooking::Owners::Update.new(params.require(:id))
    authorize @reservation
    my_restaurant_packages = if @reservation.package.nil? || @reservation.package['package_data'].nil?
                               []
                             else
                               @reservation.package['package_data'].map do |r|
                                 pack = r.slice('id', 'type').tap do |rp|
                                   rp['package_type'] = rp.delete('type')
                                   rp['package_id'] = rp.delete('id')
                                 end
                                 HhPackage::RestaurantPackage.where(pack)
                               end
                             end
    @packages = packages(restaurant, my_restaurant_packages)
    @additional_info = if @reservation.vouchers.size.positive?
                         vouchers_amount = @reservation.reservation_vouchers.sum(&:amount).amount
                         vouchers_amount_v2 = if vouchers_amount % 1 == 0
                                                vouchers_amount.to_i
                                              else
                                                vouchers_amount.to_f.round(2)
                                              end
                         {
                           vouchers: @reservation.reservation_vouchers.map do |v|
                                       { name: v.voucher&.name, value: v.amount.amount.to_i }
                                     end,
                           vouchers_amount: vouchers_amount.to_i,
                           vouchers_amount_v2: vouchers_amount_v2,
                         }
                       end
    @custom_package_pricing = @reservation.custom_package_pricing if @reservation.custom_package_pricing?
    render :package_reservation_form
  else
    authorize @reservation
    render :edit_normal_reservation
  end
end

#email_owner_managerObject



392
393
394
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 392

def email_owner_manager
  render json: manager_emails(restaurant)
end

#indexObject



39
40
41
42
43
44
45
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 39

def index
  if Flipper.enabled? :owner_dashboard_v2, current_owner
    index_v2
  else
    index_v1
  end
end

#index_v1Object



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
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 47

def index_v1
  set_meta_tags title: 'Reservation List'
  klass = restaurant.any_offers? ? Dashboard::V2::RsvPackagesGrid : Dashboard::V2::ReservationsGrid
  upcoming = params[:upcoming].present? && params[:upcoming] == 'true'
  if upcoming && params[:dashboard_v2_reservations_grid].present? && params[:dashboard_v2_reservations_grid][:single_date].present?
    params[:dashboard_v2_reservations_grid][:single_date] = nil
  end

  order = default_params
  order = { order: :start_time, descending: false } if upcoming

  @grid = klass.new(order.merge(search_params.to_h)) do |scope|
    scope = scope.where(adjusted: false) if search_params.fetch(:id, nil).blank?

    if upcoming
      scope.where(restaurant_id: current_owner.fetch_restaurant.id).
        where(date: Date.current_date, arrived: false, no_show: false, active: true, ack: true).
        page(params[:page]).per(per_page)
    else
      scope.where(restaurant_id: current_owner.fetch_restaurant.id).
        page(params[:page]).per(per_page)
    end
  end
  @reservation_history_link = true

  now = Time.now_in_tz(current_owner.fetch_restaurant.time_zone)
  @pending_reservations = current_owner.fetch_restaurant.reservations.
    where('(date = ? AND start_time >= ?) OR (date > ?)',
          now.to_date,
          now.strftime('%H:%M'),
          now.to_date).
    where(active: true, confirmed_by: nil,
          ack: false, no_show: false).pluck(:id)
  if @pending_reservations.present?
    @pending_grid = klass.new(order.merge(search_params.to_h)) do |scope|
      scope.where(id: @pending_reservations).page(1).per(1000)
    end
    @pending_grid = nil if @pending_grid.assets.blank?
  end

  @pagy, = pagy_countless(@grid.assets)
  render 'index'
end

#index_v2Object



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
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 91

def index_v2
  set_meta_tags title: 'Reservation List'
  klass = restaurant.any_offers? ? Dashboard::V2::RsvPackagesGrid : Dashboard::V2::ReservationsGrid
  upcoming = params[:upcoming].present? && params[:upcoming] == 'true'
  if upcoming && params[:dashboard_v2_reservations_grid].present? && params[:dashboard_v2_reservations_grid][:single_date].present?
    params[:dashboard_v2_reservations_grid][:single_date] = nil
  end

  order = default_params
  order = { order: :start_time, descending: false } if upcoming

  @grid = klass.new(order.merge(search_params.to_h)) do |scope|
    scope = scope.where(adjusted: false) if search_params.fetch(:id, nil).blank?

    if upcoming
      scope.where(restaurant_id: current_owner.fetch_restaurant.id).
        where(date: Date.current_date, arrived: false, no_show: false, active: true, ack: true).
        page(params[:page]).per(per_page)
    else
      scope.where(restaurant_id: current_owner.fetch_restaurant.id).
        page(params[:page]).per(per_page)
    end
  end

  @reservations = @grid.assets

  unless params[:queries].present? && params.require(:queries).fetch(:id, nil).present?
    @reservations = @reservations.where(adjusted: false)
  end

  if params[:queries].present?
    id = params.require(:queries).fetch(:id, nil)
    filter_by_id(id) if id.present?
  end
  @reservations = @reservations.order('reservations.created_at DESC')

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

  now = Time.now_in_tz(current_owner.fetch_restaurant.time_zone)
  @pending_reservations = current_owner.fetch_restaurant.reservations.
    where('(date = ? AND start_time >= ?) OR (date > ?)',
          now.to_date,
          now.strftime('%H:%M'),
          now.to_date).
    where(active: true, ack: false, no_show: false).pluck(:id)
  if @pending_reservations.present?
    @pending_grid = klass.new(order.merge(search_params.to_h)) do |scope|
      scope.where(id: @pending_reservations).page(1).per(1000)
    end
    @pending_grid = nil if @pending_grid.assets.blank?
  end

  @reservations = @reservations.includes(:reward, :charges, :adv_reservation,
                                         :customer, :booking_channel,
                                         :vouchers, :property,
                                         :address, :driver,
                                         dining_occasion: :translations,
                                         restaurant: %i[owner translations delivery_pricing_tiers],
                                         menu_sections: [
                                           menus: [{ package_menu: :translations }, subsections: [
                                             menus: { package_menu: [:translations, { section: :translations }] },
                                           ]],
                                         ])
  @kind = 'owner'
  render 'index_v2', layout: 'dashboard_v2_new'
end

#newObject



230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 230

def new
  set_meta_tags title: 'Add New Reservation'
  restaurant = select_restaurant
  @operation = PackageBooking::Owners::Create.new(reservation: { restaurant_id: restaurant.id }, package: {})
  @reservation = @operation.reservation
  authorize @reservation
  if restaurant.any_offers?
    @packages = packages(restaurant)
    render :package_reservation_form
  else
    render :new_normal_reservation
  end
end

#request_more_bikeObject



330
331
332
333
334
335
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 330

def request_more_bike
  reservation = Reservation.find(params[:reservation_id])
  Workers::Reservations::SendRequestBikeSmsWorker.perform_async(reservation.id)

  render json: { success: true, message: 'Successfully send request to order additional motorbikes' }
end

#reservation_historyObject



487
488
489
490
491
492
493
494
495
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 487

def reservation_history
  reservation_id = params[:id]
  restaurant = Reservation.fetch(reservation_id).restaurant
  history(reservation_id)

  klass = restaurant.any_offers? ? Dashboard::V2::RsvPackagesGrid : Dashboard::V2::ReservationsGrid

  @grid = klass.new { |scope| scope.where(id: history_result.to_a) }
end

#self_checkinObject



471
472
473
474
475
476
477
478
479
480
481
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 471

def self_checkin
  current_owner # to define owner group
  MarkReservationArrivedService.new(@reservation.id).execute
  @reservation.reload

  if @reservation.arrived?
    render json: { success: true, message: @reservation }
  else
    render json: { success: false, message: agent.errors.full_messages.join(', ') }
  end
end

#self_checkin_formObject



483
484
485
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 483

def self_checkin_form
  current_owner # to define owner group
end

#send_custom_smsObject



300
301
302
303
304
305
306
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 300

def send_custom_sms
  ids = params.require(:reservation).require(:ids)
  message = params.require(:reservation).require(:message)
  Workers::Reservations::SendCustomSmsWorker.perform_async(ids, message)

  render json: { success: true, message: 'Hungry Hub system will send your custom SMS if never been sent before' }
end

#send_reminderObject



287
288
289
290
291
292
293
294
295
296
297
298
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 287

def send_reminder
  authorize @reservation, :be_reminded?

  reminder = BookingReminder::ManualQueue.new(@reservation.id)
  result = reminder.remind

  if result.success
    render json: { success: true, message: result.message }
  else
    render json: { success: false, message: result.message }
  end
end


308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 308

def send_review_link
  if reservation.is_past?
    if reservation.id.blank?
      APMErrorHandler.report('Nil reservation id detected before enqueuing rating reservation worker')
    else
      Workers::Reservations::RatingReservationWorker.perform_async(@reservation.id)
    end

    render json: {
      success: true,
      message: I18n.t('send_review_link_success'),
      data: @reservation,
    }
  else
    render json: {
      success: false,
      message: I18n.t('send_review_link_failed'),
      data: @reservation,
    }
  end
end

#showObject



203
204
205
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 203

def show
  authorize @reservation
end

#statisticObject



23
24
25
26
27
28
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 23

def statistic
  cache_key = [reservation.restaurant_id, reservation.cache_key]
  return unless stale? etag: [reservation.restaurant_id, reservation.cache_key], template: false

  user_reservation_statistic(cache_key, restaurant.id)
end

#summaryObject



30
31
32
33
34
35
36
37
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 30

def summary
  respond_to do |format|
    format.html # index.html.erb
    format.json do
      render json: @reservation.decorate.user_booking_summary(@reservation.user, @reservation.restaurant_id)
    end
  end
end

#table_numberObject



497
498
499
500
501
502
503
504
505
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 497

def table_number
  reservation = Reservation.find(params.require(:reservation).require(:id))
  table_number = params.dig(:reservation, :table_number)

  reservation.table = table_number
  reservation.save(validate: false)

  render json: { success: true, message: 'Success update table number' }
end

#updateObject



244
245
246
247
248
249
250
251
252
253
# File 'app/controllers/dashboard/v2/reservations_controller.rb', line 244

def update
  params[:reservation][:active] = false if parse_param(:cancel)

  restaurant = select_restaurant
  if restaurant.any_offers?
    update_package_booking
  else
    update_normal_booking
  end
end