Class: DeliveryChannel::OrderManager

Inherits:
Object
  • Object
show all
Includes:
DefaultErrorContainer, CourierDriverHelper, ProgressStatus
Defined in:
app/my_lib/delivery_channel/order_manager.rb

Overview

This class is responsible to manage delivery order

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ProgressStatus

#available_delivery_status, #convert_from_grab_as_symbol, #convert_from_lalamove, #convert_from_lalamove_as_symbol, #convert_from_reservation, #owner_delivery_progress

Methods included from CourierDriverHelper

#can_wait_for_driver, #valid_time_to_call_driver?, #valid_to_call_driver?

Methods included from DefaultErrorContainer

#error, #error_message_simple, #merge_errors

Constructor Details

#initialize(reservation_id, config_param = {}) ⇒ OrderManager

Returns a new instance of OrderManager.

Parameters:

  • reservation_id
  • config_param (Hash) (defaults to: {})

    { webhook_params: {}, skip_reorder: boolean, service_type: '', order_id: '', lib_class: ''}



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'app/my_lib/delivery_channel/order_manager.rb', line 14

def initialize(reservation_id, config_param = {})
  @reservation = Reservation.find(reservation_id)
  @config = config_param.with_indifferent_access
  @config[:skip_reorder] = false unless config.key?(:skip_reorder)
  @service_type = config.fetch(:service_type, nil)
  @courier = determine_courier
  @webhook_info = get_data_webhook(config)
  @order_id = config.fetch(:order_id, nil)
  @order_data = {}
  if reservation.driver&.persisted?
    @driver = reservation.driver
  else
    @driver = reservation.build_driver
    order = create_or_update_hh_order
    @driver.order = order
    @driver.save!
  end
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



10
11
12
# File 'app/my_lib/delivery_channel/order_manager.rb', line 10

def config
  @config
end

#courierObject

Returns the value of attribute courier.



9
10
11
# File 'app/my_lib/delivery_channel/order_manager.rb', line 9

def courier
  @courier
end

#driverObject

Returns the value of attribute driver.



9
10
11
# File 'app/my_lib/delivery_channel/order_manager.rb', line 9

def driver
  @driver
end

#orderObject

Returns the value of attribute order.



9
10
11
# File 'app/my_lib/delivery_channel/order_manager.rb', line 9

def order
  @order
end

#order_dataObject (readonly)

Returns the value of attribute order_data.



10
11
12
# File 'app/my_lib/delivery_channel/order_manager.rb', line 10

def order_data
  @order_data
end

#order_idObject (readonly)

Returns the value of attribute order_id.



10
11
12
# File 'app/my_lib/delivery_channel/order_manager.rb', line 10

def order_id
  @order_id
end

#reservationObject

Returns the value of attribute reservation.



9
10
11
# File 'app/my_lib/delivery_channel/order_manager.rb', line 9

def reservation
  @reservation
end

#service_typeObject (readonly)

Returns the value of attribute service_type.



10
11
12
# File 'app/my_lib/delivery_channel/order_manager.rb', line 10

def service_type
  @service_type
end

#webhook_infoObject (readonly)

Returns the value of attribute webhook_info.



10
11
12
# File 'app/my_lib/delivery_channel/order_manager.rb', line 10

def webhook_info
  @webhook_info
end

Instance Method Details

#cancel_because_too_far?Boolean

Returns:

  • (Boolean)


234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'app/my_lib/delivery_channel/order_manager.rb', line 234

def cancel_because_too_far?
  driver = reservation.driver

  if order_id && courier.cancel_order(order_id) == false
    HH_LOGGER.info('courier:cancel_because_too_far', {
                     reservation_id: reservation.id,
                     order_id: order_id,
                     driver: driver.attributes,
                   })
    return false
  end

  reservation.update! driver_called: false
  true
end

#cancel_orderObject



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'app/my_lib/delivery_channel/order_manager.rb', line 167

def cancel_order
  reservation.update! driver_called: false, delivery_channel_id: nil
  return if reservation&.driver.nil? || reservation&.driver&.order&.order_ref.nil?

  if order_id && courier.cancel_order(order_id) == false
    subject = "Alert! failed cancel #{courier_name} Order. Reservation ID: #{reservation.id}"
    body = "Reservation ID: #{reservation.id}. #{courier_name} Order ID #{order_id}, error message:
                                                                                      #{courier.error_message_simple}"
    reservation.errors.add :base, body
    StaffMailer.notify_error_staff(subject, body).deliver_later!
    false
  else
    courier.force_cancel_order(reservation, skip_reorder: config[:skip_reorder])
    true
  end
end

#courier_nameObject



254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'app/my_lib/delivery_channel/order_manager.rb', line 254

def courier_name
  case courier.class.name
  when 'DeliveryChannel::Lalamove'
    'Lalamove'
  when 'DeliveryChannel::Grab'
    'Grab'
  when 'DeliveryChannel::ManualCourier'
    'Manual'
  when 'DeliveryChannel::RestaurantDelivery'
    "Restaurant's Courier"
  else
    raise NotImplementedError
  end
end

#fetch_order_dataObject

Raises:

  • (ArgumentError)


69
70
71
72
73
74
75
76
77
78
79
80
# File 'app/my_lib/delivery_channel/order_manager.rb', line 69

def fetch_order_data
  raise ArgumentError, 'Invalid parameter, order id not found' if order_id.blank?

  data = {}
  case courier.class.name
  when 'DeliveryChannel::Lalamove'
    data = build_lalamove_attributes
  when 'DeliveryChannel::Grab'
    data = build_grab_attributes
  end
  @order_data = data.with_indifferent_access
end

#order_driverObject



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'app/my_lib/delivery_channel/order_manager.rb', line 82

def order_driver
  request_order = courier.place_an_order_from_reservation(reservation)
  unless request_order
    merge_errors(courier.errors)
    report_to_rollbar "failed request order to #{courier_name}", :critical,
                      { id: reservation.id, errors: courier.errors.full_messages }
    return false
  end

  request_order.transform_keys!(&:underscore)
  @order_id = courier.instance_of?(DeliveryChannel::Grab) ? request_order['delivery_id'] : request_order['data']['orderId']
  @order = create_or_update_hh_order

  @order.update! order_ref: @order_id

  request_order
end

#report_to_rollbar(name, level, params) ⇒ Object



250
251
252
# File 'app/my_lib/delivery_channel/order_manager.rb', line 250

def report_to_rollbar(name, level, params)
  APMErrorHandler.report(name, level: level, params: params)
end

#should_create_new_order?Boolean

Returns:

  • (Boolean)


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
# File 'app/my_lib/delivery_channel/order_manager.rb', line 204

def should_create_new_order?
  return false if driver&.duration.present?

  return false unless order_data['driver'].present? && order_data['driver']['location'].present?

  d_location = order_data['driver']['location']

  driver_location = {
    'lat' => d_location['lat'],
    'lng' => d_location['lng'],
  }

  restaurant = reservation.restaurant

  destination = {
    'lat' => restaurant.lat.to_s,
    'lng' => restaurant.lng.to_s,
  }

  driving_duration = check_driving_duration(driver_location, destination)

  if can_wait_for_driver(reservation, driving_duration)
    driver.update duration: driving_duration / 60 unless driver.frozen?
    false
  else
    driver.update duration: nil unless driver.frozen?
    true
  end
end

#update_driverObject



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
# File 'app/my_lib/delivery_channel/order_manager.rb', line 100

def update_driver
  return false if errors.present?

  @order = create_or_update_hh_order if order.blank?

  if [Driver::LALAMOVE_DELIVERED,
      Driver::GRAB_DELIVERED].include?(order_data['status']) && driver.plate_number.present? && driver.tracking_link.present?
    driver.update is_complete: true, status: Driver::DELIVERED
    property = reservation.property
    property.delivered_timestamp = webhook_info['timestamp'].to_s
    property.save!
    return true
  end

  return if driver.frozen?

  if driver.new_record?
    driver.attributes = {
      status: Driver::FINDING_DRIVER,
      reservation_id: reservation.id,
      order: order,
    }
    driver.save!
    return
  elsif driver.order.blank?
    driver.update! order: order
  else
    driver.update! status: order&.status_as_constant&.constantize
  end
  driver_detail = order_data['driver']

  return unless driver_detail.present?

  driver_attr = {
    name: driver_detail['name'],
    phone: driver_detail['phone'],
    plate_number: driver_detail['plate_number'],
    order: order,
    status: order&.status_as_constant&.constantize,
    reservation_id: reservation.id,
  }

  if driver.tracking_link.blank?
    if courier.instance_of?(DeliveryChannel::Grab)
      driver_attr[:tracking_link] = courier.generate_tracking_link(reservation)
    elsif courier.instance_of?(DeliveryChannel::Lalamove)
      driver_attr[:tracking_link] = webhook_info.dig('data', 'order', 'share_link')
    end
  end
  if [Driver::LALAMOVE_DELIVERED].include?(order_data[:status])
    driver_attr[:is_complete] = true
  end
  driver.attributes = driver_attr

  driver.save!

  driver_location = order_data['driver']['location']

  return unless driver_location.present?

  driver.attributes = {
    lat: driver_location['lat'],
    lng: driver_location['lng'],
  }
  driver.save!
end

#update_firebase_delivery_detailObject

Raises:

  • (ActiveRecord::Rollback)


184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'app/my_lib/delivery_channel/order_manager.rb', line 184

def update_firebase_delivery_detail
  firebase = MyFirebase.new
  status_as_constant = order&.status_as_constant

  return if status_as_constant.nil?

  delivery_status = convert_from_lalamove_as_symbol(status_as_constant)
  if delivery_status == 'Driver::DELIVERED'
    reservation.update arrived: true
    reservation.reload
  end
  attr = {
    status: reservation.status_as_symbol,
    delivery_status: delivery_status,
  }
  response = firebase.update("reservations/#{reservation.id}", attr)

  raise ActiveRecord::Rollback, 'failed update data in Firebase' unless response.success?
end

#valid_delivery_channel?Boolean

Returns:

  • (Boolean)


42
43
44
45
46
47
48
49
50
51
52
53
# File 'app/my_lib/delivery_channel/order_manager.rb', line 42

def valid_delivery_channel?
  return false unless reservation.active?
  return false unless reservation.service_type.delivery?
  return false if reservation.address.blank? || reservation.address.new_record?

  if reservation.delivery_channel.present? &&
      !DeliveryChannel::COURIER_PARTNERS.include?(reservation.delivery_channel.lib_class)
    return false
  end

  true
end

#valid_to_assign_driver?Boolean

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
# File 'app/my_lib/delivery_channel/order_manager.rb', line 33

def valid_to_assign_driver?
  driver = reservation.driver

  reservation.reload
  return false if reservation.driver_called?

  true
end

#valid_webhook?Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'app/my_lib/delivery_channel/order_manager.rb', line 55

def valid_webhook?
  api_secret = Figaro.env.LALAMOVE_SECRET_KEY!
  api_key = Figaro.env.LALAMOVE_API_KEY
  http_verb = 'POST'
  path = '/api/webhook/lalamove_webhook'
  body = Oj.dump webhook_info['data']
  raw_signature = "#{webhook_info['timestamp']}\r\n#{http_verb}\r\n#{path}\r\n\r\n#{body}"
  signature = OpenSSL::HMAC.hexdigest('sha256', api_secret, raw_signature)
  valid_signature = signature == webhook_info['signature']
  valid_api_key = api_key == webhook_info['api_key']

  valid_api_key && valid_signature
end