Class: Api::Dashboard::ReservationsController

Inherits:
BaseController
  • Object
show all
Includes:
MoneyRails::ActionViewExtension, ReservationHistory, ResponseCacheConcern
Defined in:
app/controllers/api/dashboard/reservations_controller.rb

Instance Method Summary collapse

Methods included from ReservationHistory

#history, #history_result

Methods included from ResponseCacheConcern

#my_response_cache

Methods inherited from BaseController

#current_user, #identity_cache_memoization, #restaurants, #set_options

Methods included from LogrageCustomLogger

#append_info_to_payload

Methods included from ControllerHelpers

#check_boolean_param, #get_banners, #inventory_params

Instance Method Details

#_action_for(action) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 196

def _action_for(action)
  service = ReservationConfirmationService.new(@reservation.id, confirmed_by: :owner)
  success = if action == 'confirm'
              service.accept
            else
              service.reject
            end
  if success
    render json: Api::Dashboard::ReservationSerializer.new(@reservation).as_json, status: :ok
  else
    render_error(service, :unprocessable_entity)
  end
end

#add_onsObject



144
145
146
147
148
149
150
151
152
153
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 144

def add_ons
  restaurant = select_restaurant
  add_ons = restaurant.restaurant_add_ons

  render json: {
    success: true,
    data: ActiveModel::Serializer::CollectionSerializer.new(add_ons,
                                                            serializer: Api::Dashboard::RestaurantAddOnSerializer),
  }
end

#apply_voucherObject



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 388

def apply_voucher
  action = params_attributes.require(:action)
  voucher_code = params_attributes.require(:voucher_code)

  # cc_number = if @reservation.payment_type_provider == 'credit_card'
  #               params_attributes.require(: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,
    adult: @reservation.adult,
    kids: @reservation.kids,
    distance_to_restaurant: @reservation.distance_to_restaurant.to_f,
    service_type: @reservation.service_type,
    client_type: @reservation.medium,
    cc_number: cc_number,
  }

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

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

#arrivedObject



86
87
88
89
90
91
92
93
94
95
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 86

def arrived
  MarkReservationArrivedService.new(@reservation.id).execute
  @reservation.reload

  if @reservation.arrived?
    render json: Api::Dashboard::ReservationSerializer.new(@reservation).as_json, status: :ok
  else
    render_error(@reservation, :unprocessable_entity)
  end
end

#cancelObject



210
211
212
213
214
215
216
217
218
219
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 210

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
    render json: Api::Dashboard::ReservationSerializer.new(@reservation).as_json, status: :ok
  else
    render_error(service, :unprocessable_entity)
  end
end

#cancel_preparingObject



107
108
109
110
111
112
113
114
115
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 107

def cancel_preparing
  @reservation.cancel_preparing!

  if @reservation.save! validate: false
    render json: Api::Dashboard::ReservationSerializer.new(@reservation).as_json, status: :ok
  else
    render_error(@reservation, :unprocessable_entity)
  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



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 157

def check_inventory_status
  query = params
  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(select_restaurant.id, select_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



348
349
350
351
352
353
354
355
356
357
358
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 348

def check_reservation
  restaurant_ids = Array.wrap(restaurants.ids)
  valid = @reservation.present? && restaurant_ids.include?(@reservation.restaurant_id)
  if valid
    options = { include: params.fetch(:include, '').split(',') || [] }
    render json: Api::Dashboard::ReservationSerializer.new(@reservation, fix_include_options(options)).as_json,
           status: :ok
  else
    render json: { success: false, message: 'reservation not found' }
  end
end

#confirmObject



188
189
190
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 188

def confirm
  _action_for('confirm')
end

#createObject



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 54

def create
  create_reservation_params = {
    reservation: format_reservation_params,
    created_by: :owner,
    user_id: reservation_params.key?(:user_id) ? reservation_params.require(:user_id) : nil,
    guest_user: if reservation_params.key?(:guest_user)
                  reservation_params.require(:guest_user).permit(:name,
                                                                 :email, :phone)
                end,
    channel: parse_channel_source,
    medium: 'Dashboard',
    omise_token: '',
    group_booking: false,
    business_booking: false,
    restaurant_packages: format_packages_params,
  }

  service = ReservationService::Create.new create_reservation_params
  if service.execute
    render json: Api::Dashboard::ReservationSerializer.new(service.outcome).as_json, status: :created
  else
    render_error(service, :unprocessable_entity)
  end
end

#exportObject



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

def export
  permitted_parameters = params_attributes.permit(:start_date, :end_date, :date_type, :restaurant_id, emails: [])

  emails = (permitted_parameters[:emails].presence || []).to_set.add(current_staff.email).to_a

  messages = []

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

  emails.each do |email|
    messages << "Email : #{email} is not valid" unless ::EmailValidator.valid?(email)
  end

  return render json: { success: false, message: messages } if messages.present?

  restaurants.each do |restaurant|
    begin
      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

      # Validate that start_date is before end_date
      if start_date.to_date > end_date.to_date
        return render json: {
          success: false,
          message: [I18n.t('partner.errors.reservations.start_date_must_be_before_end_date')],
          count: 0,
        }
      end

      # Validate that reservations exist for the criteria before scheduling worker
      # Use shared method to build export parameters consistently
      export_params = PartnerService::Reservations::Exports::ValidationService.build_export_params(
        permitted_parameters.merge(date_filter_type: 'range'), start_date, end_date
      )

      validation_service = PartnerService::Reservations::Exports::ValidationService.new(restaurant, export_params)
      validation_result = validation_service.validate_data_availability

      unless validation_result[:valid]
        return render json: {
          success: false,
          message: [validation_result[:message]],
          count: validation_result[:count],
        }
      end
    rescue ArgumentError, Date::Error => e
      return render json: { success: false, message: [e.message], count: 0 }
    end
    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],
      },
    )
  end

  render json: {
    success: true,
    message: I18n.t('partner.reservations.export_booking'),
    count: validation_result[:count],
  }
end

#indexObject



15
16
17
18
19
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
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 15

def index
  reservations = Reservation.joins(:restaurant).
    includes(:user, :customer, :property, :charges,
             :booking_channel, :reward,
             restaurant: :translations).
    where(restaurant_id: restaurants.ids).
    exclude_cancel_scope.exclude_temporary

  filter_params = params.fetch(:filter, {})

  order_params = params.fetch(:order, '').split(',') || []

  filter = Api::Dashboard::ReservationsFilter.new(reservations)
  filter.order_by(order_params)
  filter.filter(filter_params) if filter_params.present?
  filter.build_collections

  reservations = nil

  begin
    pagy, reservations = pagy(filter.collections)
  rescue Pagy::OverflowError
    params[:page] = 1
    pagy, reservations = pagy(Reservation.where('1 = 0'))
  rescue ActiveModel::RangeError
    return error('Invalid Reservation ID.', :bad_request)
  rescue ActiveRecord::RecordNotFound
    return error('Record not found', :bad_request)
  end

  render json: filter.as_json(reservations, set_options(pagy))
end

#packagesObject



132
133
134
135
136
137
138
139
140
141
142
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 132

def packages
  restaurant = select_restaurant
  rest_packs = restaurant.restaurant_packages.to_a
  rest_packs = HhPackage::RestaurantPackage.where(id: rest_packs.flatten.map(&:id).uniq)

  render json: {
    success: true,
    data: ActiveModel::Serializer::CollectionSerializer.new(rest_packs,
                                                            serializer: Websites::RestaurantPackageSerializer),
  }
end

#preparedObject



97
98
99
100
101
102
103
104
105
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 97

def prepared
  @reservation.mark_as_prepared!

  if @reservation.save! validate: false
    render json: Api::Dashboard::ReservationSerializer.new(@reservation).as_json, status: :ok
  else
    render_error(@reservation, :unprocessable_entity)
  end
end

#rejectObject



192
193
194
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 192

def reject
  _action_for('reject')
end

#request_more_bikeObject



79
80
81
82
83
84
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 79

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



174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 174

def reservation_history
  reservation_id = params[:id]
  history(reservation_id)
  reservations = Reservation.where(id: history_result.to_a)
  begin
    pagy, reservations = pagy(reservations)
  rescue Pagy::OverflowError
    params[:page] = 1
    pagy, reservations = pagy(Reservation.where('1 = 0'))
  end

  render json: Api::Dashboard::V2::ReservationSerializer.new(reservations, set_options(pagy)).as_json
end

#self_checkinObject



337
338
339
340
341
342
343
344
345
346
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 337

def self_checkin
  MarkReservationArrivedService.new(@reservation.id).execute
  @reservation.reload

  if @reservation.arrived?
    render json: { success: true, message: 'Checkin successfully' }
  else
    render_error(@reservation, :unprocessable_entity)
  end
end

#send_custom_smsObject



234
235
236
237
238
239
240
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 234

def send_custom_sms
  ids = params_attributes.require(:ids)
  message = params_attributes.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' },
         status: :ok
end

#send_reminderObject

Raises:

  • (Pundit::NotAuthorizedError)


221
222
223
224
225
226
227
228
229
230
231
232
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 221

def send_reminder
  raise Pundit::NotAuthorizedError unless model_policy.be_reminded?

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

  if result.success
    render json: Api::Dashboard::ReservationSerializer.new(@reservation).as_json, status: :ok
  else
    render json: { errors: [detail: result.message] }, status: :unprocessable_entity
  end
end


242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 242

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



48
49
50
51
52
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 48

def show
  options = { include: params.fetch(:include, '').split(',') || [] }
  render json: Api::Dashboard::ReservationSerializer.new(@reservation, fix_include_options(options)).as_json,
         status: :ok
end

#statisticObject



360
361
362
363
364
365
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 360

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, @reservation.restaurant.id)
end

#updateObject

Raises:

  • (Pundit::NotAuthorizedError)


117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 117

def update
  model_policy = ::ReservationPolicy.new(current_staff, @reservation)
  raise Pundit::NotAuthorizedError unless model_policy.editable?

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

  restaurant = restaurants.first

  if restaurant.any_offers?
    update_package_booking
  else
    update_normal_booking
  end
end

#update_normal_bookingObject



377
378
379
380
381
382
383
384
385
386
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 377

def update_normal_booking
  @reservation.assign_attributes(format_reservation_params.permit!)
  builder = Agents::UpdateForOwner.new @reservation
  builder.status = reservation_params[:status] if reservation_params.try(:[], :status)
  if builder.update_booking
    render json: Api::Dashboard::ReservationSerializer.new(builder.reservation).as_json, status: :ok
  else
    render_error(builder, :unprocessable_entity)
  end
end

#update_package_bookingObject



367
368
369
370
371
372
373
374
375
# File 'app/controllers/api/dashboard/reservations_controller.rb', line 367

def update_package_booking
  operation = PackageBooking::Owners::Update.new(params.require(:id), format_reservation_params.permit!,
                                                 format_packages_params)
  if operation.update_booking
    render json: Api::Dashboard::ReservationSerializer.new(operation.reservation).as_json, status: :ok
  else
    render_error(operation, :unprocessable_entity)
  end
end