Class: Api::Vendor::V1::Dianping::ReservationsController

Inherits:
BaseController show all
Includes:
Concerns::ReservationUtils, Concerns::ReservationErrorResponses
Defined in:
app/controllers/api/vendor/v1/dianping/reservations_controller.rb

Instance Attribute Summary collapse

Attributes inherited from BaseController

#vendor

Instance Method Summary collapse

Methods inherited from BaseController

#authenticate

Methods included from ResponseCacheConcern

#my_response_cache

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 LogrageCustomLogger

#append_info_to_payload

Methods included from ControllerHelpers

#check_boolean_param, #get_banners, #inventory_params, #reservation_params

Instance Attribute Details

#parsed_dataObject (readonly)

Returns the value of attribute parsed_data.



6
7
8
# File 'app/controllers/api/vendor/v1/dianping/reservations_controller.rb', line 6

def parsed_data
  @parsed_data
end

#reservationObject (readonly)

Returns the value of attribute reservation.



6
7
8
# File 'app/controllers/api/vendor/v1/dianping/reservations_controller.rb', line 6

def reservation
  @reservation
end

#restaurantObject (readonly)

Returns the value of attribute restaurant.



6
7
8
# File 'app/controllers/api/vendor/v1/dianping/reservations_controller.rb', line 6

def restaurant
  @restaurant
end

#restaurant_packageObject (readonly)

Returns the value of attribute restaurant_package.



6
7
8
# File 'app/controllers/api/vendor/v1/dianping/reservations_controller.rb', line 6

def restaurant_package
  @restaurant_package
end

#vendor_reference_idObject (readonly)

Returns the value of attribute vendor_reference_id.



6
7
8
# File 'app/controllers/api/vendor/v1/dianping/reservations_controller.rb', line 6

def vendor_reference_id
  @vendor_reference_id
end

#vendor_reservationObject (readonly)

Returns the value of attribute vendor_reservation.



6
7
8
# File 'app/controllers/api/vendor/v1/dianping/reservations_controller.rb', line 6

def vendor_reservation
  @vendor_reservation
end

Instance Method Details

#cancelObject



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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
# File 'app/controllers/api/vendor/v1/dianping/reservations_controller.rb', line 204

def cancel
  custom_params = ActionController::Parameters.new(parsed_data)
  # attribute refundAmount is in RMB currency so we cannot use it for validation
  [:orderId, :otaOrderId, :refundId, :refundReason, :refundQuantity].each { |k| custom_params.require(k) }
  permitted_params = custom_params.permit(:orderId, :otaOrderId, :refundId, :refundReason, :refundQuantity)

  @vendor_reference_id = permitted_params[:orderId]
  vendor_reservation_id = permitted_params[:otaOrderId]
  refund_id = permitted_params[:refundId]
  refund_reason = permitted_params[:refundReason]
  refund_quantity = permitted_params[:refundQuantity].to_i

  BUSINESS_LOGGER.set_business_context({ vendor_reference_id: vendor_reference_id })
  VendorLogger.log_event(:request, params[:route], payload: custom_params)

  # we need to ignore Klick Digital orders with success response, they are manually handled by the partner
  if Reservation.klick_digital_client_order_id?(vendor_reservation_id)
    return render_cancel_success_response_and_send_push_api_webhook(refund_id, kd_order: true)
  end

  @vendor_reservation = VendorReservation.find_by(id: vendor_reservation_id)
  @reservation = vendor_reservation&.reservation

  if vendor_reservation.blank? || reservation.blank? || reservation.for_locking_system?
    raise(ActiveRecord::RecordNotFound, 'The order number does not exist')
  end

  BUSINESS_LOGGER.set_business_context({ reservation_id: reservation.id })

  # idempotency check
  if reservation.status_as_symbol == :cancelled
    BUSINESS_LOGGER.info("#{self.class}##{__method__}: [idempotency_check] reservation was already cancelled")
    return render_cancel_success_response_and_send_push_api_webhook(refund_id)
  end

  raise(OrderAlreadyUsedError, 'This order has been used') if reservation_consumed?
  raise(OrderValidityExpiredError, 'The order has passed the refund period') if refund_period_expired?

  rest_package_quantity = reservation.package_obj&.formatted_packages&.first&.fetch('quantity', 0).to_i
  if rest_package_quantity != refund_quantity
    raise(CancelQtyMismatchError,
          "Cancel quantity error, order qty: #{rest_package_quantity}, refund qty: #{refund_quantity}")
  end

  service_options = { require_reason: true }
  service_options[:force_cancel] = integration_test_force_cancel_option if integration_test_mode?
  service = CancelReservationService.new(reservation.id, :user, service_options)
  service.cancel_reason = "Cancelled by user for reason: #{refund_reason}"
  if service.execute
    @reservation = reservation.reload
    # since there will always be 100% refund request
    order_amount_cents = reservation.total_price_v2_cents.to_i
    reservation.vendor_payment&.update!(status: :refund,
                                        refund_id: refund_id,
                                        refund_reason: refund_reason,
                                        refund_cents: order_amount_cents)
    render_cancel_success_response_and_send_push_api_webhook(refund_id)
  else
    raise(StandardError, 'Failed to cancel order')
  end
rescue ActiveRecord::RecordNotFound => e
  render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_NOT_EXIST_CODE,
               msg: e.message, method: :cancel, refund_id: refund_id)
rescue OrderAlreadyUsedError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_ALREADY_USED_CODE,
               msg: e.message, method: :cancel, refund_id: refund_id)
rescue OrderValidityExpiredError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_VALIDITY_EXPIRED_CODE,
               msg: e.message, method: :cancel, refund_id: refund_id)
rescue CancelAmountMismatchError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_CANCEL_AMOUNT_MISMATCH_CODE,
               msg: e.message, method: :cancel, refund_id: refund_id)
rescue CancelQtyMismatchError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_CANCEL_QTY_MISMATCH_CODE,
               msg: e.message, method: :cancel, refund_id: refund_id)
rescue StandardError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_NOT_REFUNDABLE_CODE,
               msg: e.message, error_backtrace: e.backtrace, method: :cancel, refund_id: refund_id)
end

#confirmObject



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

def confirm
  # Dianping does not send customer info at confirm stage
  custom_params = ActionController::Parameters.new(parsed_data)
  [:orderId, :otaOrderId].each { |k| custom_params.require(k) }
  permitted_params = custom_params.permit(:orderId, :otaOrderId)

  @vendor_reference_id = permitted_params[:orderId]
  vendor_reservation_id = permitted_params[:otaOrderId]

  BUSINESS_LOGGER.set_business_context({ vendor_reference_id: vendor_reference_id })
  VendorLogger.log_event(:request, params[:route], payload: custom_params)

  # we need to ignore Klick Digital orders with success response, they are manually handled by the partner
  if Reservation.klick_digital_client_order_id?(vendor_reservation_id)
    return render_confirm_success_response_and_send_push_api_webhook(kd_order: true)
  end

  @vendor_reservation = VendorReservation.find_by(id: vendor_reservation_id)
  @reservation = vendor_reservation&.reservation

  if vendor_reservation.blank? || reservation.blank?
    raise(ActiveRecord::RecordNotFound, 'The order number does not exist')
  end

  BUSINESS_LOGGER.set_business_context({ reservation_id: reservation.id })
  @restaurant = reservation.restaurant

  # idempotency check
  if reservation.vendor_payment.present?
    return render_confirm_success_response_and_send_push_api_webhook
  end

  service = ReservationService::Create.new(build_reservation_params, reservation)

  if service.execute
    @reservation = service.outcome
    BUSINESS_LOGGER.info("#{self.class}##{__method__}: create reservation success")
    handle_successful_reservation
    render_confirm_success_response_and_send_push_api_webhook
  else
    render_error(code: ApiVendorV1::Constants::DIANPING_INSUFFICIENT_INVENTORY_CODE,
                 msg: service.error_message_simple.presence, method: :confirm)
  end
rescue ActiveRecord::RecordNotFound => e
  render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_NOT_EXIST_CODE,
               msg: e.message, method: :confirm)
rescue StandardError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_INSUFFICIENT_INVENTORY_CODE,
               msg: e.message, error_backtrace: e.backtrace, method: :confirm)
end

#heartObject



10
11
12
# File 'app/controllers/api/vendor/v1/dianping/reservations_controller.rb', line 10

def heart
  render json: { status: 'alive' }, status: :ok
end

#occupyObject



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

def occupy
  custom_params = ActionController::Parameters.new(parsed_data)
  %i[orderId otaPid orderItems contactInfo].each { |key| custom_params.require(key) }
  %i[name email phone startDate].each { |k| custom_params[:contactInfo].require(k) }
  custom_params.require(:orderItems).each { |item| %i[quantity rawPrice].each { |k| item.fetch(k) } }

  permitted_params = custom_params.permit(
    :orderId, :otaPid,
    orderItems: %i[quantity rawPrice],
    contactInfo: %i[name email phone startDate]
  )

  @vendor_reference_id = permitted_params[:orderId]
  raw_ota_pid = permitted_params[:otaPid]

  BUSINESS_LOGGER.set_business_context({ vendor_reference_id: vendor_reference_id })
  VendorLogger.log_event(:request, params[:route], payload: custom_params)

  # we need to ignore Klick Digital orders with success response, they are manually handled by the partner
  return render_occupy_success_response(kd_order: true) if Reservation.klick_digital_client_order_id?(raw_ota_pid)

  # dianping sandbox don't let us set startDate & rawPrice so we need to override them for sandbox testing
  is_test_booking = raw_ota_pid.start_with?('TEST-')
  ota_pid = is_test_booking ? raw_ota_pid.delete_prefix('TEST-') : raw_ota_pid

  raw_price = is_test_booking ? custom_params[:orderPrice] : permitted_params[:orderItems].first[:rawPrice]
  # Use a date 2 days from now for test bookings to bypass refund_period_expired logic
  date = is_test_booking ? 2.days.from_now.to_date.to_s : permitted_params.dig(:contactInfo, :startDate)
  restaurant_package_id, start_time = parse_rp_id_and_time(ota_pid)
  user_name = permitted_params.dig(:contactInfo, :name)
  user_email = permitted_params.dig(:contactInfo, :email)
  phone = permitted_params.dig(:contactInfo, :phone)
  user_phone = Phonelib.valid?(phone) ? phone : AdminSetting.support_phone

  @restaurant_package = HhPackage::RestaurantPackage.valid_to_have_agendas_and_not_preview.find_by(id: restaurant_package_id)
  # we will re-add this validation after Phase-II
  # dianping_package = Vendors::DianpingPackage.find_by(restaurant_package_id: restaurant_package_id)

  # if restaurant_package.blank? || dianping_package.blank?
  if restaurant_package.blank?
    raise(ActiveRecord::RecordNotFound, 'Product not found or inactive')
  end

  @restaurant = restaurant_package.restaurant

  if restaurant.blank?
    raise(ActiveRecord::RecordNotFound, 'Product restaurant not found')
  end

  rp_pricings = restaurant_package.package.dynamic_pricings_as_json(
    for_rules_attribute: true,
    support_dynamic_pricing_feature: true,
    time_zone: restaurant_package.restaurant&.time_zone,
  ) || []

  rp_price_cents_min = rp_pricings.map { |d| d['price_cents'].to_i }.min
  rp_price_decimal_min = (rp_price_cents_min.to_d / 100.to_d).round(2, BigDecimal::ROUND_CEILING)

  if raw_price.to_d < rp_price_decimal_min
    raise(PriceVerificationFailedError,
          "Order price is less than Expected price. Order price: #{raw_price}, Expected price: #{rp_price_decimal_min.to_f}")
  end

  res_params = prepare_tmp_reservation_params(permitted_params, user_name, user_email, user_phone, date, start_time)
  service = ReservationService::InitFactory.build(res_params)
  result = service.create_temporary

  if result.success?
    @reservation = result.data

    BUSINESS_LOGGER.set_business_context({ reservation_id: reservation.id })
    BUSINESS_LOGGER.info("#{self.class}##{__method__}: temporary reservation lock created successfully")
    create_vendor_reservation!(user_name, user_email, user_phone) if vendor_reservation.blank?
    render_occupy_success_response
  else
    render_error(code: ApiVendorV1::Constants::DIANPING_INSUFFICIENT_INVENTORY_CODE,
                 msg: service.error_message_simple.presence || I18n.t('errors.too_many_requests'),
                 method: :occupy)
  end
rescue UserValidationFailedError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_OTHER_ABNORMAL_CAUSES_CODE,
               msg: e.message, method: :occupy)
rescue ActiveRecord::RecordNotFound => e
  render_error(code: ApiVendorV1::Constants::DIANPING_PRODUCT_ID_NOT_EXIST_CODE,
               msg: e.message, method: :occupy)
rescue PriceVerificationFailedError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_PRICE_VERIFICATION_FAILED_CODE,
               msg: e.message, method: :occupy)
rescue StandardError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_INSUFFICIENT_INVENTORY_CODE,
               msg: e.message, error_backtrace: e.backtrace, method: :occupy)
end

#queryObject



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'app/controllers/api/vendor/v1/dianping/reservations_controller.rb', line 284

def query
  custom_params = ActionController::Parameters.new(parsed_data)
  [:orderId, :otaOrderId].each { |k| custom_params.require(k) }

  route = params[:route]
  permitted_params = custom_params.permit(:orderId, :otaOrderId)
  @vendor_reference_id = permitted_params[:orderId]
  vendor_reservation_id = permitted_params[:otaOrderId]

  BUSINESS_LOGGER.set_business_context({ vendor_reference_id: vendor_reference_id })
  show_tickets = false

  # we need to ignore Klick Digital orders with success response, they are manually handled by the partner
  if Reservation.klick_digital_client_order_id?(vendor_reservation_id)
    kd_order = true
    case route
    when 'query_confirm'
      message = ApiVendorV1::Constants::DIANPING_CONFIRM_SUCCESS_MSG
      ota_order_status = ApiVendorV1::Constants::DIANPING_CONFIRM_SUCCESS_STATUS
      show_tickets = true
    when 'query_consume'
      message = ApiVendorV1::Constants::DIANPING_WRITEOFF_SUCCESS_MSG
      ota_order_status = ApiVendorV1::Constants::DIANPING_WRITEOFF_SUCCESS_STATUS
      show_tickets = true
    when 'query_refund'
      message = ApiVendorV1::Constants::DIANPING_CANCEL_SUCCESS_MSG
      ota_order_status = ApiVendorV1::Constants::DIANPING_CANCEL_SUCCESS_STATUS
    end
  else
    kd_order = false
    @vendor_reservation = VendorReservation.find_by(id: vendor_reservation_id)
    @reservation = vendor_reservation&.reservation

    if vendor_reservation.blank? || reservation.blank?
      raise(ActiveRecord::RecordNotFound, 'The order number does not exist')
    end

    BUSINESS_LOGGER.set_business_context({ reservation_id: reservation.id })
    res_status = reservation.status_as_symbol

    if reservation_consumed?
      message = ApiVendorV1::Constants::DIANPING_WRITEOFF_SUCCESS_MSG
      ota_order_status = ApiVendorV1::Constants::DIANPING_WRITEOFF_SUCCESS_STATUS
      show_tickets = true
    elsif res_status == :pending_confirmation
      message = ApiVendorV1::Constants::DIANPING_OCCUPY_SUCCESS_MSG
      ota_order_status = ApiVendorV1::Constants::DIANPING_OCCUPY_SUCCESS_STATUS
    elsif res_status == :rejected && reservation.for_locking_system?
      message = ApiVendorV1::Constants::DIANPING_RELEASE_SUCCESS_MSG
      ota_order_status = ApiVendorV1::Constants::DIANPING_RELEASE_SUCCESS_STATUS
    elsif [:cancelled, :rejected].include?(res_status)
      message = ApiVendorV1::Constants::DIANPING_CANCEL_SUCCESS_MSG
      ota_order_status = ApiVendorV1::Constants::DIANPING_CANCEL_SUCCESS_STATUS
    else
      message = ApiVendorV1::Constants::DIANPING_CONFIRM_SUCCESS_MSG
      ota_order_status = ApiVendorV1::Constants::DIANPING_CONFIRM_SUCCESS_STATUS
      show_tickets = true
    end
  end

  render_query_success_response(message, ota_order_status, show_tickets, kd_order: kd_order)
rescue ActiveRecord::RecordNotFound => e
  render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_NOT_EXIST_CODE,
               msg: e.message, method: :query)
rescue StandardError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_UNKNOWN_EXCEPTION_STATUS,
               msg: e.message, method: :query)
end

#releaseObject



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

def release
  custom_params = ActionController::Parameters.new(parsed_data)
  [:orderId, :otaOrderId].each { |k| custom_params.require(k) }
  permitted_params = custom_params.permit(:orderId, :otaOrderId)

  @vendor_reference_id = permitted_params[:orderId]
  vendor_reservation_id = permitted_params[:otaOrderId]

  BUSINESS_LOGGER.set_business_context({ vendor_reference_id: vendor_reference_id })
  VendorLogger.log_event(:request, params[:route], payload: custom_params)

  # we need to ignore Klick Digital orders with success response, they are manually handled by the partner
  return render_release_success_response(kd_order: true) if Reservation.klick_digital_client_order_id?(vendor_reservation_id)

  @vendor_reservation = VendorReservation.find_by(id: vendor_reservation_id)
  @reservation = vendor_reservation&.reservation

  if vendor_reservation.blank? || reservation.blank?
    raise(ActiveRecord::RecordNotFound, 'The order number does not exist')
  end

  BUSINESS_LOGGER.set_business_context({ reservation_id: reservation.id })

  # idempotency check
  if reservation.active? && reservation.for_locking_system?
    reservation.audit_comment = 'cancel lock system by vendor'
    reservation.mark_as_canceled!
    Retriable.retriable on: [ActiveRecord::Deadlocked], tries: 10 do
      reservation.save!(validate: false)
    end
    BUSINESS_LOGGER.info("#{self.class}##{__method__}: tmp. reservation lock released successfully")
  elsif reservation.active? || !reservation.for_locking_system?
    raise(ActiveRecord::RecordNotFound, 'This placeholder was already used')
  else
    BUSINESS_LOGGER.info("#{self.class}##{__method__}: [idempotency_check] tmp. reservation lock was already released")
  end

  render_release_success_response
rescue ActiveRecord::RecordNotFound => e
  render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_NOT_EXIST_CODE,
               msg: e.message, method: :release)
rescue StandardError => e
  render_error(code: ApiVendorV1::Constants::DIANPING_RELEASE_SUCCESS_CODE,
               msg: e.message, error_backtrace: e.backtrace, method: :release)
end