Class: Api::Vendor::V1::Dianping::OrdersController
- Inherits:
-
BaseController
- Object
- ActionController::Base
- ApplicationController
- BaseController
- Api::Vendor::V1::Dianping::OrdersController
- Includes:
- Concerns::OrderErrorResponses
- Defined in:
- app/controllers/api/vendor/v1/dianping/orders_controller.rb
Constant Summary collapse
- OTA_PID_PREFIX =
'HH-VG-'.freeze
Instance Attribute Summary collapse
-
#parsed_data ⇒ Object
readonly
Returns the value of attribute parsed_data.
-
#ticket_group_id ⇒ Object
readonly
Returns the value of attribute ticket_group_id.
-
#ticket_transaction_id ⇒ Object
readonly
Returns the value of attribute ticket_transaction_id.
-
#vendor_order_id ⇒ Object
readonly
Returns the value of attribute vendor_order_id.
Attributes inherited from BaseController
Instance Method Summary collapse
- #cancel ⇒ Object
- #confirm ⇒ Object
- #heart ⇒ Object
- #occupy ⇒ Object
-
#query ⇒ Object
post 'order/query_confirm', to: 'orders#query', defaults: { query_type: 'confirm' } post 'order/query_consume', to: 'orders#query', defaults: { query_type: 'consume' } post 'order/query_refund', to: 'orders#query', defaults: { query_type: 'refund' }.
- #release ⇒ Object
Methods inherited from BaseController
Methods included from ResponseCacheConcern
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
Methods included from ControllerHelpers
#check_boolean_param, #get_banners, #inventory_params, #reservation_params
Instance Attribute Details
#parsed_data ⇒ Object (readonly)
Returns the value of attribute parsed_data.
5 6 7 |
# File 'app/controllers/api/vendor/v1/dianping/orders_controller.rb', line 5 def parsed_data @parsed_data end |
#ticket_group_id ⇒ Object (readonly)
Returns the value of attribute ticket_group_id.
5 6 7 |
# File 'app/controllers/api/vendor/v1/dianping/orders_controller.rb', line 5 def ticket_group_id @ticket_group_id end |
#ticket_transaction_id ⇒ Object (readonly)
Returns the value of attribute ticket_transaction_id.
5 6 7 |
# File 'app/controllers/api/vendor/v1/dianping/orders_controller.rb', line 5 def ticket_transaction_id @ticket_transaction_id end |
#vendor_order_id ⇒ Object (readonly)
Returns the value of attribute vendor_order_id.
5 6 7 |
# File 'app/controllers/api/vendor/v1/dianping/orders_controller.rb', line 5 def vendor_order_id @vendor_order_id end |
Instance Method Details
#cancel ⇒ Object
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 283 284 285 286 287 288 289 290 291 |
# File 'app/controllers/api/vendor/v1/dianping/orders_controller.rb', line 215 def cancel 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| params.require(k) } permitted_params = params.permit(:orderId, :otaOrderId, :refundId, :refundReason, :refundQuantity) @vendor_order_id = permitted_params[:orderId] @ticket_transaction_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_order_id, ticket_transaction_id: ticket_transaction_id }) BUSINESS_LOGGER.info("#{self.class}##{__method__}: Incoming Request", params: params) # we need to ignore Klick Digital orders with success response, they are manually handled by the partner if TicketTransaction.klick_digital_client_order_id?(ticket_transaction_id) return render_cancel_success_response_and_send_push_api_webhook(refund_id, kd_order: true) end ticket_transaction = TicketTransaction.find_by(id: ticket_transaction_id) BUSINESS_LOGGER.set_business_context({ ticket_transaction_id: ticket_transaction_id }) raise(ActiveRecord::RecordNotFound, 'The order number does not exist') if ticket_transaction.blank? tickets = ticket_transaction.tickets raise(ActiveRecord::RecordNotFound, 'The order coupons does not exist') if tickets.blank? # idempotency check unless ticket_transaction.active? BUSINESS_LOGGER.info("#{self.class}##{__method__}: [idempotency_check] ticket_transaction was already cancelled") return render_cancel_success_response_and_send_push_api_webhook(refund_id) end raise(OrderAlreadyUsedError, 'This order has been used') if order_partially_redeemed?(tickets) raise(OrderValidityExpiredError, 'The order has passed the refund period') if any_ticket_expired?(ticket_transaction) ticket_count = tickets.count if ticket_count != refund_quantity raise(CancelQtyMismatchError, "Cancel quantity error, order qty: #{ticket_count}, refund qty: #{refund_quantity}") end reason = 'cancel payment by vendor' service = ::PaymentProcessService::Cancelled.new(:ticket_transaction, ticket_transaction_id, reason) service.execute ticket_transaction.reload raise(StandardError, 'Failed to cancel order') if ticket_transaction.active? # since there will always be 100% refund request order_amount_cents = ticket_transaction.vendor_ticket_transaction_payment.amount_cents.to_i ticket_transaction.vendor_ticket_transaction_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) rescue ActiveRecord::RecordNotFound => e render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_NOT_EXIST_CODE, msg: e., method: :cancel) rescue OrderAlreadyUsedError => e render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_ALREADY_USED_CODE, msg: e., method: :cancel) rescue OrderValidityExpiredError => e render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_VALIDITY_EXPIRED_CODE, msg: e., method: :cancel) rescue CancelAmountMismatchError => e render_error(code: ApiVendorV1::Constants::DIANPING_CANCEL_AMOUNT_MISMATCH_CODE, msg: e., method: :cancel) rescue CancelQtyMismatchError => e render_error(code: ApiVendorV1::Constants::DIANPING_CANCEL_QTY_MISMATCH_CODE, msg: e., method: :cancel) rescue StandardError => e render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_NOT_REFUNDABLE_CODE, msg: e., error_backtrace: e.backtrace, method: :cancel) end |
#confirm ⇒ Object
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 |
# File 'app/controllers/api/vendor/v1/dianping/orders_controller.rb', line 159 def confirm # Dianping does not send customer info at confirm stage params = ActionController::Parameters.new(parsed_data) [:orderId, :otaOrderId].each { |k| params.require(k) } permitted_params = params.permit(:orderId, :otaOrderId) @vendor_order_id = permitted_params[:orderId] @ticket_transaction_id = permitted_params[:otaOrderId] BUSINESS_LOGGER.set_business_context({ vendor_reference_id: vendor_order_id, ticket_transaction_id: ticket_transaction_id }) BUSINESS_LOGGER.info("#{self.class}##{__method__}: Incoming Request", params: params) # we need to ignore Klick Digital orders with success response, they are manually handled by the partner if TicketTransaction.klick_digital_client_order_id?(ticket_transaction_id) return render_confirm_success_response_and_send_push_api_webhook(kd_order: true) end ticket_transaction = TicketTransaction.find_by(id: ticket_transaction_id, active: true) if ticket_transaction.blank? raise(ActiveRecord::RecordNotFound, 'The order number does not exist') end guest = ticket_transaction.guest guest_user_param = { name: guest&.name, email: guest&.email, phone: guest&.phone } vendor_payment_param = { transaction_id: ticket_transaction_id, status: 'success', amount_cents: ticket_transaction.total_price_cents, amount_currency: 'THB', paid_at: Time.current, vendor_id: vendor&.id } params_hash = { payment_type: ApiVendorV1::Constants::HH_TICKET_TRANSACTION_PAYMENT_TYPE, restaurant_id: ticket_transaction.restaurant_id, source: ApiVendorV1::Constants::HH_TICKET_TRANSACTION_SOURCE, channel: ApiVendorV1::Constants::DIANPING_CHANNEL_URI, guest_user: guest_user_param, vendor_payment: vendor_payment_param } params = ActionController::Parameters.new(params_hash) service = ::TicketService::Transaction.new(params) service.set_transaction(ticket_transaction_id) if service.create render_confirm_success_response_and_send_push_api_webhook(ticket_transaction) else render_error(code: ApiVendorV1::Constants::DIANPING_INSUFFICIENT_INVENTORY_CODE, msg: service..presence, method: :confirm) end rescue ActiveRecord::RecordNotFound => e render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_NOT_EXIST_CODE, msg: e., method: :confirm) rescue StandardError => e render_error(code: ApiVendorV1::Constants::DIANPING_INSUFFICIENT_INVENTORY_CODE, msg: e., error_backtrace: e.backtrace, method: :confirm) end |
#heart ⇒ Object
11 12 13 |
# File 'app/controllers/api/vendor/v1/dianping/orders_controller.rb', line 11 def heart render json: { status: 'alive' }, status: :ok end |
#occupy ⇒ Object
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 106 107 108 109 110 111 112 113 114 |
# File 'app/controllers/api/vendor/v1/dianping/orders_controller.rb', line 15 def occupy params = ActionController::Parameters.new(parsed_data) %i[orderId otaPid orderItems contactInfo].each { |key| params.require(key) } %i[name email phone].each { |k| params[:contactInfo].require(k) } params.require(:orderItems).each { |item| %i[quantity rawPrice].each { |k| item.fetch(k) } } permitted_params = params.permit( :orderId, :otaPid, orderItems: %i[quantity rawPrice], contactInfo: %i[name email phone] ) @vendor_order_id = permitted_params[:orderId] ota_pid = permitted_params[:otaPid] @ticket_group_id = remove_ota_pid_prefix(ota_pid) order_items = permitted_params[:orderItems] raw_price = permitted_params[:orderItems].first[:rawPrice] name = permitted_params.dig(:contactInfo, :name) email = permitted_params.dig(:contactInfo, :email) phone = permitted_params.dig(:contactInfo, :phone) BUSINESS_LOGGER.set_business_context({ vendor_reference_id: vendor_order_id }) BUSINESS_LOGGER.info("#{self.class}##{__method__}: Incoming Request", params: 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 TicketTransaction.klick_digital_client_order_id?(ota_pid) # idempotency check ticket_transaction = TicketTransaction.find_by(vendor_order_id: vendor_order_id, active: true) if ticket_transaction.present? BUSINESS_LOGGER.info("#{self.class}##{__method__}: [idempotency_check] tmp. ticket_transaction already exists", ticket_transaction_id: ticket_transaction.id) @ticket_transaction_id = ticket_transaction.id return render_occupy_success_response end guest = Guest.find_or_initialize_by(email: email) guest.name = name guest.phone = Phonelib.valid?(phone) ? phone : AdminSetting.support_phone if (guest.new_record? || guest.changed?) && !guest.save raise(UserValidationFailedError, guest.errors..to_sentence) end ticket_group = TicketGroup.not_expired.find_by(id: ticket_group_id) if ticket_group.blank? raise(ActiveRecord::RecordNotFound, 'Product not found or inactive') end # Dianping should have only one restaurant per ticket group, since we don't get restaurant_id info from Dianping order restaurant_id = ticket_group.restaurants.pluck(:id)[0] if restaurant_id.blank? raise(ActiveRecord::RecordNotFound, 'Product restaurant not found') end ticket_group_price_min = [ticket_group.price.amount.to_d, ticket_group.discount_price.amount.to_d].compact.min if raw_price.to_d < ticket_group_price_min raise(PriceVerificationFailedError, "Order price is less than Expected price. Order price: #{raw_price}, Expected price: #{ticket_group_price_min.to_f}") end ticket_groups = order_items.map { |item| { id: ticket_group_id, quantity: item[:quantity] } } params_hash = { ticket_groups: ticket_groups, restaurant_id: restaurant_id } params = ActionController::Parameters.new(params_hash) service = ::TicketService::Transaction.new(params) if service.lock && service.outcome @ticket_transaction_id = service.outcome.id BUSINESS_LOGGER.set_business_context({ vendor_reference_id: vendor_order_id, ticket_transaction_id: ticket_transaction_id }) BUSINESS_LOGGER.info("#{self.class}##{__method__}: tmp. ticket_transaction lock created successfully") begin service.outcome.update!(vendor_order_id: vendor_order_id, guest_id: guest.id) BUSINESS_LOGGER.info("#{self.class}##{__method__}: vendor_order_id & guest_id updated successfully in ticket_transaction") rescue StandardError => e raise(StandardError, "Failed to update vendor_order_id in ticket transaction: #{e.}") end render_occupy_success_response else render_error(code: ApiVendorV1::Constants::DIANPING_INSUFFICIENT_INVENTORY_CODE, msg: service..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., method: :occupy) rescue ActiveRecord::RecordNotFound => e render_error(code: ApiVendorV1::Constants::DIANPING_PRODUCT_ID_NOT_EXIST_CODE, msg: e., method: :occupy) rescue PriceVerificationFailedError => e render_error(code: ApiVendorV1::Constants::DIANPING_PRICE_VERIFICATION_FAILED_CODE, msg: e., method: :occupy) rescue StandardError => e render_error(code: ApiVendorV1::Constants::DIANPING_INSUFFICIENT_INVENTORY_CODE, msg: e., error_backtrace: e.backtrace, method: :occupy) end |
#query ⇒ Object
post 'order/query_confirm', to: 'orders#query', defaults: { query_type: 'confirm' } post 'order/query_consume', to: 'orders#query', defaults: { query_type: 'consume' } post 'order/query_refund', to: 'orders#query', defaults: { query_type: 'refund' }
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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
# File 'app/controllers/api/vendor/v1/dianping/orders_controller.rb', line 296 def query custom_params = ActionController::Parameters.new(parsed_data) [:orderId, :otaOrderId].each { |k| custom_params.require(k) } query_type = params[:query_type] permitted_params = custom_params.permit(:orderId, :otaOrderId) @vendor_order_id = permitted_params[:orderId] @ticket_transaction_id = permitted_params[:otaOrderId] BUSINESS_LOGGER.set_business_context({ vendor_reference_id: vendor_order_id, ticket_transaction_id: ticket_transaction_id }) BUSINESS_LOGGER.info("#{self.class}##{__method__}: Incoming Request", params: custom_params, query_type: query_type) # we need to ignore Klick Digital orders with success response, they are manually handled by the partner if TicketTransaction.klick_digital_client_order_id?(ticket_transaction_id) case query_type when 'confirm' = ApiVendorV1::Constants::DIANPING_CONFIRM_SUCCESS_MSG ota_order_status = ApiVendorV1::Constants::DIANPING_CONFIRM_SUCCESS_STATUS when 'consume' = ApiVendorV1::Constants::DIANPING_WRITEOFF_SUCCESS_MSG ota_order_status = ApiVendorV1::Constants::DIANPING_WRITEOFF_SUCCESS_STATUS when 'refund' = ApiVendorV1::Constants::DIANPING_CANCEL_SUCCESS_MSG ota_order_status = ApiVendorV1::Constants::DIANPING_CANCEL_SUCCESS_STATUS end else ticket_transaction = TicketTransaction.find_by(id: ticket_transaction_id) raise(ActiveRecord::RecordNotFound, 'The order number does not exist') if ticket_transaction.blank? tickets = ticket_transaction.tickets if order_partially_redeemed?(tickets) = ApiVendorV1::Constants::DIANPING_WRITEOFF_SUCCESS_MSG ota_order_status = ApiVendorV1::Constants::DIANPING_WRITEOFF_SUCCESS_STATUS elsif ticket_transaction.active? if ticket_transaction.for_locking_system? = ApiVendorV1::Constants::DIANPING_OCCUPY_SUCCESS_MSG ota_order_status = ApiVendorV1::Constants::DIANPING_OCCUPY_SUCCESS_STATUS else = ApiVendorV1::Constants::DIANPING_CONFIRM_SUCCESS_MSG ota_order_status = ApiVendorV1::Constants::DIANPING_CONFIRM_SUCCESS_STATUS end else if ticket_transaction.for_locking_system? = ApiVendorV1::Constants::DIANPING_RELEASE_SUCCESS_MSG ota_order_status = ApiVendorV1::Constants::DIANPING_RELEASE_SUCCESS_STATUS else = ApiVendorV1::Constants::DIANPING_CANCEL_SUCCESS_MSG ota_order_status = ApiVendorV1::Constants::DIANPING_CANCEL_SUCCESS_STATUS end end end order_data = OpenStruct.new( msg: , code: 200, vendor_order_id: vendor_order_id, ticket_transaction_id: ticket_transaction_id, is_success: true, ota_order_status: ota_order_status, tickets: ticket_transaction&.tickets, ) serialized_data = Api::Vendor::V1::Dianping::OrderSerializer.new(order_data) BUSINESS_LOGGER.info("#{self.class}##{__method__}: Query Successful Response", response: serialized_data) render json: serialized_data, status: :ok rescue ActiveRecord::RecordNotFound => e render_error(code: ApiVendorV1::Constants::DIANPING_ORDER_NOT_EXIST_CODE, msg: e., method: :query) rescue StandardError => e render_error(code: ApiVendorV1::Constants::DIANPING_UNKNOWN_EXCEPTION_STATUS, msg: e., method: :query) end |
#release ⇒ Object
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 |
# File 'app/controllers/api/vendor/v1/dianping/orders_controller.rb', line 116 def release params = ActionController::Parameters.new(parsed_data) [:orderId, :otaOrderId].each { |k| params.require(k) } permitted_params = params.permit(:orderId, :otaOrderId) @vendor_order_id = permitted_params[:orderId] @ticket_transaction_id = permitted_params[:otaOrderId] BUSINESS_LOGGER.set_business_context({ vendor_reference_id: vendor_order_id, ticket_transaction_id: ticket_transaction_id }) BUSINESS_LOGGER.info("#{self.class}##{__method__}: Incoming Request", params: 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 TicketTransaction.klick_digital_client_order_id?(ticket_transaction_id) ticket_transaction = TicketTransaction.find_by(id: ticket_transaction_id) if ticket_transaction.blank? raise(ActiveRecord::RecordNotFound, 'The order number does not exist') end # idempotency check if ticket_transaction.active? && ticket_transaction.for_locking_system? reason = 'cancel lock system by vendor' service = ::PaymentProcessService::Cancelled.new(:ticket_transaction, ticket_transaction_id, reason) service.execute BUSINESS_LOGGER.info("#{self.class}##{__method__}: tmp. ticket_transaction lock released successfully") elsif ticket_transaction.active? || !ticket_transaction.for_locking_system? raise(ActiveRecord::RecordNotFound, 'This placeholder was already used') else BUSINESS_LOGGER.info("#{self.class}##{__method__}: [idempotency_check] tmp. ticket_transaction 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., method: :release) rescue StandardError => e render_error(code: ApiVendorV1::Constants::DIANPING_RELEASE_SUCCESS_CODE, msg: e., error_backtrace: e.backtrace, method: :release) end |