Class: Agents::ModifyBookingForUser

Inherits:
Update show all
Includes:
ActionView::Helpers::DateHelper, RefundGuaranteeHelper, Reservations::CheckSeatDecreased, Reservations::CheckSeatIncreased
Defined in:
app/my_lib/agents/modify_booking_for_user.rb

Overview

This class only for booking that doesn't have package See PackageBooking::Users::Update TODO create `update_reservation_service.rb` to replace this class

Direct Known Subclasses

PackageBooking::Users::Update

Defined Under Namespace

Classes: NotModified

Constant Summary

Constants inherited from Base

Base::WORKER_DELAY_TIME

Instance Attribute Summary

Attributes inherited from Base

#audit_comment, #errors, #executor, #force_update, #owner, #reservation, #reservation_params, #restaurant, #user, #vendor_booking_id

Instance Method Summary collapse

Methods included from RefundGuaranteeHelper

#calculate_min_refund_hours, #calculate_refundable_until_time

Methods included from Reservations::CheckSeatDecreased

#decrease_seat_only?

Methods included from Reservations::CheckSeatIncreased

#change_packages?, #increase_seat_only?

Methods inherited from Update

#after_initialize, #update_booking, #update_booking!

Methods included from ErrorType

#fatal_error?, #inventory_error?, #normal_error?, #overwrite_error_type!

Methods inherited from Base

#error_message, #hotline, #inventory_available?, #save_reservation!, #status=

Methods included from SharedJobs

#give_campaign_reward, #send_rating_email

Constructor Details

#initialize(reservation, params) ⇒ ModifyBookingForUser

Returns a new instance of ModifyBookingForUser.



22
23
24
25
26
27
28
29
30
31
# File 'app/my_lib/agents/modify_booking_for_user.rb', line 22

def initialize(reservation, params)
  self.reservation = reservation.is_a?(::Reservation) ? reservation : ::Reservation.find(reservation)
  self.reservation = self.reservation.decorate
  self.restaurant = self.reservation.restaurant
  self.reservation_params = normalize_parameters(params).merge(modified_by: :user)
  @new_reservation = self.reservation.object.dup.decorate
  @old_reservation_attributes = self.reservation.attributes
  @old_reservation_property_attributes = self.reservation&.property&.attributes
  self.reservation.assign_attributes(reservation_params)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Agents::Base

Instance Method Details

#executeObject



243
244
245
246
247
248
249
250
251
252
253
254
# File 'app/my_lib/agents/modify_booking_for_user.rb', line 243

def execute
  execute!
rescue NotModified => e
  errors.add(:base, e.message)
  false
rescue InvalidReservation, ActiveRecord::RecordInvalid => e
  errors.add(:base, e.message)
  false
rescue ActiveRecord::ActiveRecordError => e
  APMErrorHandler.report e
  false
end

#execute!Object



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
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
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
203
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
# File 'app/my_lib/agents/modify_booking_for_user.rb', line 33

def execute!
  if has_paid? && has_change_package_attr?
    normal_error!
    raise NotModified, I18n.t('errors.cannot_modify_prepaid_booking')
  end

  # https://3.basecamp.com/5190892/buckets/24029614/todos/5496562041
  # user can not decrease or increase seat if the booking has prepayment
  if (changes.key?(:adult) || changes.key?(:kids)) && has_paid?
    normal_error!
    raise NotModified, I18n.t('errors.cannot_modify_prepaid_booking')
  end

  # validate if user change package from non-prepaid to prepaid
  # user can not change package from non-prepaid to prepaid
  if nonprepaid_to_prepaid_switch?
    normal_error!
    raise NotModified, I18n.t('views.package.nonprepaid_to_prepaid_blocked')
  end

  # Enhanced package data corruption check with detailed logging
  if has_package_data_corruption?
    normal_error!
    raise ActiveRecord::Rollback,
          'Unable to modify reservation: Package data validation failed. Please contact customer support.'
  end

  unless primary_attr_changed?
    normal_error!
    raise NotModified, I18n.t('errors.no_modified')
  end

  unless new_reservation.allowed_to_rectify?
    restaurant = new_reservation.restaurant
    time_needed = distance_of_time_in_words(restaurant.time_in_advance_to_rectify.minutes)

    normal_error!
    raise NotModified, I18n.t('reservation.too_quick_to_rectify',
                              time_needed: time_needed, phone: restaurant.phone)
  end

  result = false
  old_reservation = nil
  ::ActiveRecord::Base.transaction do
    if change_only_special_request?
      # do nothing
    elsif change_personal_data_or_special_request_only?
      # do nothing
    elsif increase_seat_only?
      # For seat increases, we need to validate the new total party size
      # but account for the existing reservation when checking availability
      new_adult = reservation.adult
      new_kids = reservation.kids
      original_adult = @old_reservation_attributes['adult']
      original_kids = @old_reservation_attributes['kids']

      # Calculate the difference for logging purposes
      adult_diff = new_adult - original_adult
      kids_diff = new_kids - original_kids

      BUSINESS_LOGGER.info(
        'Validating seat increase for reservation',
        {
          reservation_id: reservation.id,
          original_adult: original_adult,
          original_kids: original_kids,
          new_adult: new_adult,
          new_kids: new_kids,
          adult_diff: adult_diff,
          kids_diff: kids_diff,
          has_packages: reservation.package.present?,
        },
      )

      # Only validate if there's an actual increase in party size
      if adult_diff > 0 || kids_diff > 0
        # For package bookings, the inventory_available? method will handle
        # the adult_from parameter correctly via PackageBooking::Users::Update
        unless inventory_available?(new_adult, new_kids)
          BUSINESS_LOGGER.warn(
            'Seat increase validation failed',
            {
              reservation_id: reservation.id,
              new_adult: new_adult,
              new_kids: new_kids,
              adult_diff: adult_diff,
              kids_diff: kids_diff,
            },
          )

          inventory_error!
          raise ActiveRecord::Rollback
        end

        BUSINESS_LOGGER.info(
          'Seat increase validation passed',
          {
            reservation_id: reservation.id,
            new_adult: new_adult,
            new_kids: new_kids,
          },
        )
      end
    elsif decrease_seat_only?
      # For seat decreases, no inventory check needed as we're freeing up seats
      BUSINESS_LOGGER.info(
        'Processing seat decrease only - no inventory validation required',
        {
          reservation_id: reservation.id,
          adult: reservation.adult,
          kids: reservation.kids,
        },
      )
    else
      unless inventory_available?
        inventory_error!
        raise ActiveRecord::Rollback
      end
    end

    reset_old_reservation_attributes
    reset_old_reservation_property_attributes
    set_audit_comment

    update_reservation
    create_new_reservation

    dup_relations(reservation, new_reservation)
    old_reservation = reservation
    update_vendor_reservation(new_reservation)

    update_sr_result = update_seven_rooms_reservation
    unless update_sr_result.success?
      errors.add(:base, SevenRooms::ErrorMessages.error_message('user', update_sr_result.message))
      raise ActiveRecord::Rollback
    end

    update_tc_result = update_tablecheck_reservation
    unless update_tc_result.success?
      raise ActiveRecord::Rollback
    end

    update_weeloy_result = update_weeloy_reservation
    unless update_weeloy_result.success?
      raise ActiveRecord::Rollback
    end

    update_bc_result = update_bistrochat_reservation
    unless update_bc_result.success?
      raise ActiveRecord::Rollback
    end

    update_mm_result = update_mymenu_reservation
    unless update_mm_result.success?
      raise ActiveRecord::Rollback
    end

    self.reservation = new_reservation
    result = true
  end

  unless result
    raise InvalidReservation, I18n.t('inventory.not_available') if inventory_error?
    raise InvalidReservation, 'Something went wrong' if errors.empty?

    raise InvalidReservation, errors.full_messages.to_sentence
  end

  # Sync disabled - handled by calling controllers/services
  # sync_reservation_summaries(old_reservation)

  begin
    send_notification(old_reservation, new_reservation)
  rescue StandardError => e
    APMErrorHandler.report('Failed to send notification during modify booking', {
                             old_reservation_id: old_reservation.id,
                             new_reservation_id: new_reservation.id,
                             error_message: e.message,
                             exception: e,
                           })
  end

  give_reward
  ask_feedback

  time = reservation.reservation_time.twenty_four_hours_later
  # used for staging tests — set time to 10 minutes from now if the feature flag is enabled
  if ENV['RAILS_ENV_REAL'] == 'staging' && Flipper.enabled?(:instant_referral_reward)
    time = 10.minutes.from_now
  end

  if reservation.user_id.present?
    if reservation.id.blank?
      APMErrorHandler.report('Nil reservation id detected before enqueuing reward workers')
    else
      RewardWorkers::Reservation.perform_in(1.minute, reservation.id, :create)
      LoyaltyPrograms::TierQualificationWorker.perform_at(time, reservation.id)
    end
  end

  if reservation.user_id.present? && reservation.active_vouchers.present?
    referral_voucher = reservation.active_vouchers.select { |v| v.voucher_code.to_s.include?('REF-') }
    RewardWorkers::UserReferralReward.perform_in(time, reservation.id) if referral_voucher.present?
  end

  Netcore::EventWorker.perform_in(Netcore::EventWorker::DELAY, :reservation_event, old_reservation_id)

  true
end