Class: UponReservationCreationWorker

Inherits:
ApplicationWorker show all
Defined in:
app/workers/upon_reservation_creation_worker.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from ApplicationWorker

unlimited_retry

Instance Attribute Details

#reservationObject (readonly)

Returns the value of attribute reservation.



15
16
17
# File 'app/workers/upon_reservation_creation_worker.rb', line 15

def reservation
  @reservation
end

Instance Method Details

#a_day_after_dining(reservation) ⇒ Object



203
204
205
# File 'app/workers/upon_reservation_creation_worker.rb', line 203

def a_day_after_dining(reservation)
  reservation.reservation_time.twenty_four_hours_later
end

#calculate_avg_per_pax_booking(reservation) ⇒ Object



236
237
238
# File 'app/workers/upon_reservation_creation_worker.rb', line 236

def calculate_avg_per_pax_booking(reservation)
  UserAvgPerPaxBookingWorker.perform_at(a_day_after_dining(reservation), reservation.id)
end

#calculate_avg_spend_per_person(reservation) ⇒ Object



173
174
175
# File 'app/workers/upon_reservation_creation_worker.rb', line 173

def calculate_avg_spend_per_person(reservation)
  UserSpendingPerPersonWorker.perform_at(a_day_after_dining(reservation), reservation.id)
end

#calculate_total_booking_per_type(reservation) ⇒ Object



232
233
234
# File 'app/workers/upon_reservation_creation_worker.rb', line 232

def calculate_total_booking_per_type(reservation)
  UserTotalBookingPerTypeWorker.perform_at(a_day_after_dining(reservation), reservation.id)
end

#call_order_now_driver(reservation) ⇒ Object



87
88
89
90
91
92
93
# File 'app/workers/upon_reservation_creation_worker.rb', line 87

def call_order_now_driver(reservation)
  key = "sidekiq_job_ids_#{.key_suffix}"
  .note[key] ||= {}
  .note[key]["call_order_now_driver_at_#{.key_suffix}"] =
    DeliveryChannels::CreateOrderWorker.perform_at(reservation.call_order_now_driver_at, reservation.id)
  .save
end

#give_rewards(reservation) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
# File 'app/workers/upon_reservation_creation_worker.rb', line 74

def give_rewards(reservation)
  # No need to give rewards for vendor
  # because vendor create booking with guest
  return if reservation.booking_channel.skip_give_rewards?
  return if reservation.user_id.blank?

  if reservation.id.blank?
    APMErrorHandler.report('Nil reservation id detected before enqueuing reward workers')
    return
  end
  RewardWorkers::Reservation.perform_in(1.minute, reservation.id, :create)
end

#ignore_errorsObject



196
197
198
199
200
201
# File 'app/workers/upon_reservation_creation_worker.rb', line 196

def ignore_errors
  yield
rescue StandardError => e
  APMErrorHandler.report("error with #{self.class}", error: e, reservation_id: reservation.id)
  true
end

#metadataObject



211
212
213
# File 'app/workers/upon_reservation_creation_worker.rb', line 211

def 
  @metadata ||= GenericNote.find_or_initialize_by(parent: @reservation)
end

#monitor_report_data(reservation) ⇒ Object



122
123
124
# File 'app/workers/upon_reservation_creation_worker.rb', line 122

def monitor_report_data(reservation)
  ReportReservationDataWorker.perform_at(a_day_after_dining(reservation), reservation.id)
end

#netcore_event_complete(reservation) ⇒ Object



177
178
179
180
181
# File 'app/workers/upon_reservation_creation_worker.rb', line 177

def netcore_event_complete(reservation)
  Netcore::EventWorker.perform_at(
    a_day_after_dining(reservation), :reservation_event, reservation.id, :transaction_completed
  )
end

#netcore_point_used(reservation) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
# File 'app/workers/upon_reservation_creation_worker.rb', line 183

def netcore_point_used(reservation)
  return if reservation.skip_sending_netcore_event?

  redeemed_points = reservation.redeemed_points
  return if redeemed_points.blank?

  event_data = {
    number_of_point: redeemed_points,
    reservation_id: reservation.id,
  }
  Netcore::EventWorker.perform_async(:send_custom_event, 'Point Used', event_data, reservation.email)
end

#perform(reservation_id) ⇒ Object



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
# File 'app/workers/upon_reservation_creation_worker.rb', line 17

def perform(reservation_id)
  @reservation = reservation = Reservation.find(reservation_id)

  BUSINESS_LOGGER.set_business_context({ reservation_id: reservation_id })

  raise_error_if_booking_is_pending(reservation)

  ignore_errors { send_notifications(reservation) }
  ignore_errors { give_rewards(reservation) }
  ignore_errors { tight_time_call_driver(reservation) }
  ignore_errors { monitor_report_data(reservation) }
  ignore_errors { netcore_event_complete(reservation) }
  ignore_errors { netcore_point_used(reservation) }
  ignore_errors { postback_involve_asia(reservation) }
  ignore_errors { postback_access_trade(reservation) }
  ignore_errors { postback_forit(reservation) }
  ignore_errors do
    reservation.mark_voucher_as_active!
    # Trigger sync for voucher activation during creation (delayed to avoid blocking creation)
    reservation.trigger_summary_sync
  end
  unless reservation.dine_in?
    ignore_errors { MyPusher::ReservationDriver.broadcast_reservation(reservation, :create) }
  end
  ignore_errors { update_last_booking_was_made(reservation) }

  send_webhook_to_vendors(reservation)
  sync_inventory_for_supplier_restaurants(reservation)

  # extend points expiry date after dine-in for prepayment reservation only
  if reservation.property&.is_prepayment && reservation.user_id.present?
    ignore_errors do
      RewardWorkers::PointsExpired.perform_at(a_day_after_dining(reservation),
                                              reservation.user_id, :update)
    end
  end

  ignore_errors do
    if reservation.user_id.present?
      Users::UpdateMetaWorker.perform_at(a_day_after_dining(reservation),
                                         reservation.user_id)
    end
  end

  if reservation.is_order_now?
    ignore_errors { send_order_now_reminder_to_staff(reservation) }
    ignore_errors { call_order_now_driver(reservation) }
  end

  ignore_errors { run_tier_qualification(reservation) }
  ignore_errors { calculate_avg_spend_per_person(reservation) }
  ignore_errors { calculate_total_booking_per_type(reservation) }
  ignore_errors { calculate_avg_per_pax_booking(reservation) }

  send_alert_if_user_redeemed_more_than_allowed_points(reservation)
end

#postback_access_trade(reservation) ⇒ Object



142
143
144
145
146
147
148
149
150
151
# File 'app/workers/upon_reservation_creation_worker.rb', line 142

def postback_access_trade(reservation)
  adv_reservation = reservation.adv_reservation
  return if adv_reservation.blank?

  return if reservation.property.blank? || reservation.property.revenue <= 0

  # Execute the postback service
  service = AtPostBackService.new(reservation.id, adv_reservation.click_id, adv_reservation.adv_partner)
  service.execute
end

#postback_forit(reservation) ⇒ Object



153
154
155
156
157
158
159
# File 'app/workers/upon_reservation_creation_worker.rb', line 153

def postback_forit(reservation)
  adv_reservation = reservation.adv_reservation
  return if adv_reservation.blank? || adv_reservation.adv_partner != 'forit'

  service = ForitPostBackService.new(reservation.id, adv_reservation.click_id, adv_reservation.adv_partner)
  service.execute
end

#postback_involve_asia(reservation) ⇒ Object



134
135
136
137
138
139
140
# File 'app/workers/upon_reservation_creation_worker.rb', line 134

def postback_involve_asia(reservation)
  adv_reservation = reservation.adv_reservation
  return if adv_reservation.blank? || adv_reservation.adv_partner != 'involveasia' || IS_STAGING_ENV

  service = IaPostBackService.new(reservation.id, adv_reservation.click_id)
  service.execute
end

#raise_error_if_booking_is_pending(reservation) ⇒ Object



207
208
209
# File 'app/workers/upon_reservation_creation_worker.rb', line 207

def raise_error_if_booking_is_pending(reservation)
  raise 'pending booking' if reservation.is_temporary? || reservation.for_locking_system?
end

#run_tier_qualification(reservation) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
# File 'app/workers/upon_reservation_creation_worker.rb', line 161

def run_tier_qualification(reservation)
  # No need to handle this method for vendor
  # because vendor is created booking by guest
  return if reservation.booking_channel.skip_run_tier_qualification?

  if reservation.id.blank?
    APMErrorHandler.report('Nil reservation id detected before enqueuing reward workers')
    return
  end
  LoyaltyPrograms::TierQualificationWorker.perform_at(a_day_after_dining(reservation), reservation.id)
end

#send_alert_if_user_redeemed_more_than_allowed_points(reservation) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'app/workers/upon_reservation_creation_worker.rb', line 215

def send_alert_if_user_redeemed_more_than_allowed_points(reservation)
  return if reservation.vouchers&.first&.voucher_category&.to_s != 'redemption'

  package = reservation.property.package
  total_price = case package['package_type']
                when 'ayce'
                  package['package_data'].sum { |pack| pack['price_cents'].to_i / 100 } * reservation.adult
                when 'pp'
                  package['package_data'].sum { |pack| (pack['price_cents'].to_i * pack['quantity']) / 100 }
                else
                  reservation.property.package['price_cents'].to_i / 100
                end
  if total_price.present? && reservation.vouchers.first.amount.to_i > total_price * 0.25
    APMErrorHandler.report 'Debug: user has redeemed more than allowed points', reservation: reservation.id
  end
end

#send_notifications(reservation) ⇒ Object



95
96
97
98
99
100
101
# File 'app/workers/upon_reservation_creation_worker.rb', line 95

def send_notifications(reservation)
  key = "sidekiq_job_ids_#{.key_suffix}"
  .note[key] ||= {}
  .note[key]["send_notifications_#{.key_suffix}"] =
    NotificationWorkers::Reservation.perform_async(reservation.id, :create)
  .save!
end

#send_order_now_reminder_to_staff(reservation) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
# File 'app/workers/upon_reservation_creation_worker.rb', line 103

def send_order_now_reminder_to_staff(reservation)
  return unless reservation.delivery? && reservation.created_by.to_sym != :owner

  restaurant = reservation.restaurant
  remind_before_minute = restaurant.order_now&.cooking_time || 60
  remind_at = reservation.reservation_time - remind_before_minute.to_i.minutes
  .note[:remind_cooking_at] = remind_at.iso8601
  .save!

  ::NotificationServiceWorkers::CookingReminderWorker.perform_at(remind_at, reservation.id, remind_at.iso8601)
end

#send_webhook_to_vendors(reservation) ⇒ Object



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
283
284
285
286
287
288
# File 'app/workers/upon_reservation_creation_worker.rb', line 240

def send_webhook_to_vendors(reservation)
  if reservation.aoa_reservation.present? && reservation.aoa_channel?
    status = :pending_arrival
    BUSINESS_LOGGER.info("#{self.class}: Aoa::WebhookWorker called with status #{status}", status: status)
    ignore_errors { Aoa::WebhookWorker.default_perform_async(reservation.id, status) }
  end

  if reservation.by_marketplace?
    if reservation.tagthai_channel?
      ignore_errors do
        status = ApiVendorV1::Constants::PENDING_ARRIVAL
        BUSINESS_LOGGER.info("#{self.class}: Vendors::TagThai::WebhookWorker called with status #{status}",
                             status: status)
        Vendors::TagThai::WebhookWorker.perform_async(reservation.id, status)
      end
      ignore_errors do
        status = ApiVendorV1::Constants::CONFIRM
        BUSINESS_LOGGER.info("#{self.class}: Vendors::TagThai::WebhookWorker called with status #{status}",
                             status: status)
        Vendors::TagThai::WebhookWorker.perform_at(a_day_after_dining(reservation), reservation.id,
                                                   status, true)
      end
    end

    if reservation.openrice_channel?
      ignore_errors do
        # Need to send the auto arrived to openrice webhook
        # after 24 hours + 1 hour after the dining time
        # for make sure that the webhook is passed the validation
        # because openrice only allow CONFIRM or NO_SHOW after 24 hours of dining time
        perform_at = a_day_after_dining(reservation) + 1.hour
        status = ApiVendorV1::Constants::CONFIRM
        BUSINESS_LOGGER.info(
          "#{self.class}: Vendors::OpenRice::WebhookWorker scheduled for #{perform_at} with status #{status}", status: status
        )
        Vendors::OpenRice::WebhookWorker.
          perform_at(perform_at, reservation.id, reservation.vendor_reservation.id, status, nil, nil, nil, nil, true)
      end
    end

    if reservation.google_reserve_channel?
      ignore_errors do
        status = 'conversion_tracking'
        BUSINESS_LOGGER.info("#{self.class}: Vendors::GoogleReserve::ConversionTrackingWorker called", status: status)
        Vendors::GoogleReserve::ConversionTrackingWorker.perform_async(reservation.id)
      end
    end
  end
end

#sync_inventory_for_supplier_restaurants(reservation) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'app/workers/upon_reservation_creation_worker.rb', line 290

def sync_inventory_for_supplier_restaurants(reservation)
  if reservation.restaurant.inventory_tablecheck?
    Vendors::Tablecheck::ReservationInventorySyncWorker.perform_async(reservation.restaurant_id,
                                                                      reservation.date,
                                                                      :reservation_created)
  elsif reservation.restaurant.inventory_seven_rooms?
    Vendors::SevenRooms::ReservationInventorySyncWorker.perform_async(reservation.restaurant_id,
                                                                      reservation.date,
                                                                      :reservation_created)
  elsif reservation.restaurant.inventory_bistrochat?
    Vendors::Bistrochat::ReservationInventorySyncWorker.perform_async(reservation.restaurant_id,
                                                                      reservation.date,
                                                                      :reservation_created)
  elsif reservation.restaurant.inventory_my_menu?
    Vendors::MyMenu::ReservationInventorySyncWorker.perform_async(reservation.restaurant_id,
                                                                  reservation.date,
                                                                  :reservation_created)
  end
end

#tight_time_call_driver(reservation) ⇒ Object



115
116
117
118
119
120
# File 'app/workers/upon_reservation_creation_worker.rb', line 115

def tight_time_call_driver(reservation)
  # No need to handle this method for dine in booking
  return if reservation.dine_in?

  NotificationWorkers::TightTimeCallDriverWorker.perform_async(reservation.id)
end

#update_last_booking_was_made(reservation) ⇒ Object



126
127
128
129
130
131
132
# File 'app/workers/upon_reservation_creation_worker.rb', line 126

def update_last_booking_was_made(reservation)
  return if reservation.property.blank?

  reservation.property.package.fetch(:package_data, []).map do |package|
    HhPackage::RestaurantPackage.fetch(package[:restaurant_package_id]).touch(:last_booking_was_made)
  end
end