Class: Edi::Wayfair::OrderMessageProcessor
- Inherits:
-
BaseEdiService
- Object
- BaseService
- BaseEdiService
- Edi::Wayfair::OrderMessageProcessor
- Defined in:
- app/services/edi/wayfair/order_message_processor.rb
Overview
Processes Wayfair purchase-order batches fetched from the GraphQL API into
Order records: builds the order, shipping address, line items, and PO
payment, flags duplicate POs, retrieves packing slips, and releases or
CR-holds each order.
Defined Under Namespace
Classes: BatchProcessResult, LineCreationResult, Result
Constant Summary
Constants included from RequestIdentifiable
RequestIdentifiable::REQUEST_ID_HEADERS
Constants included from AddressAbbreviator
AddressAbbreviator::MAX_LENGTH
Instance Attribute Summary
Attributes inherited from BaseEdiService
Attributes inherited from BaseService
Instance Method Summary collapse
-
#apply_payment(order, order_hash) ⇒ Payment
Builds the authorized PO payment covering the order total.
-
#create_line_items(order, order_hash) ⇒ LineCreationResult
Builds line items for each product in the message, matching part numbers against the customer catalog by SKU, third-party SKU, then third-party part number.
-
#create_shipping_address(order_hash) ⇒ Array(Address, Hash)
Builds and saves the shipping Address from the message's shipTo block, abbreviating streets and bypassing address correction/validation.
-
#customer(segment = nil) ⇒ Customer
The Wayfair customer record for the given segment.
-
#match_shipping_code(shipping_speed, carrier_code = nil, is_puerto_rico = nil) ⇒ Edi::Wayfair::ShippingOptionResult?
Returns the shipping option name and special service to use like saturday delivery.
-
#process(edi_logs = nil, edi_transaction_id: nil) ⇒ Result
Picks up the edi communication log in the queue ready to process, generate acknowledgements.
-
#process_order(order_hash = nil) ⇒ Order
Process a single order.
-
#process_orders(orders_data, edi_transaction_id: nil, edi_log_id: nil) ⇒ BatchProcessResult
Iterates through the batch order data.
-
#set_shipping_option(order, order_hash) ⇒ String?
Maps the message's shipSpeed/carrierCode onto the order's shipping method and requested ship dates.
-
#shipping_invalid?(order) ⇒ Boolean
Whether the order's quoting delivery no longer matches the EDI shipping option or signature confirmation captured from the order message.
Methods inherited from BaseEdiService
#amazon_feed_product_type, #duplicate_po_already_notified?, #initialize, #mark_duplicate_po_as_notified, #onboard_ordered_catalog_items, #report_order_creation_issues, #safe_process_edi_communication_log
Methods included from RequestIdentifiable
Methods included from AddressAbbreviator
#abbreviate_street, #collect_street_originals, #record_address_abbreviation_notes
Methods inherited from BaseService
#initialize, #log_debug, #log_error, #log_info, #log_warning, #logger, #tagged_logger
Constructor Details
This class inherits a constructor from Edi::BaseEdiService
Instance Method Details
#apply_payment(order, order_hash) ⇒ Payment
Builds the authorized PO payment covering the order total.
255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
# File 'app/services/edi/wayfair/order_message_processor.rb', line 255 def apply_payment(order, order_hash) order.reload order.pending_payment! total_due = order.total order.payments.build.tap do |payment| payment.category = Payment::PO payment.currency = order.currency payment.amount = total_due payment.state = 'authorized' payment.po_number = order_hash[:poNumber] payment.delivery = order.deliveries.quoting.first payment.save! end end |
#create_line_items(order, order_hash) ⇒ LineCreationResult
Builds line items for each product in the message, matching part numbers
against the customer catalog by SKU, third-party SKU, then third-party part
number.
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 |
# File 'app/services/edi/wayfair/order_message_processor.rb', line 310 def create_line_items(order, order_hash) # "products": [ # { # "partNumber": "TWS6-GRD10KH", # "quantity": "1", # "price": 539.4, # "event": null # } # ], line_total = BigDecimal(0) cust = order.customer all_skus_valid = true errors = [] bad_vendor_skus = [] bad_merchant_skus = [] catalog_items = cust.catalog.catalog_items.where(state: CatalogItem::ORDER_MATCHABLE_STATES).order(state: :asc) order_hash[:products].each_with_index do |line_hash, i| # First we try by promo sku vendor_sku = line_hash[:partNumber] raise 'Missing identifier partNumber in order query' if vendor_sku.blank? matched_catalog_item = nil matched_catalog_item ||= catalog_items.by_skus(vendor_sku).first if vendor_sku.present? # If no match, try third party sku matched_catalog_item ||= catalog_items.where(third_party_sku: vendor_sku).first if vendor_sku.present? # If no match, try third party part number matched_catalog_item ||= catalog_items.where(third_party_part_number: vendor_sku).first if vendor_sku.present? if matched_catalog_item order.line_items.build.tap do |line_item| line_item.quantity = line_hash[:quantity].to_i # 2 line_item.edi_reference = "#{order_hash[:poNumber]}-#{i + 1}" line_item.edi_line_number = i + 1 line_item.catalog_item = matched_catalog_item price = BigDecimal(line_hash[:price].to_s) line_item.edi_unit_cost = price line_total += price * line_item.quantity end if matched_catalog_item.state_requires_edi_warning_on_order? subj = "EDI order for orchestrator: #{orchestrator.partner}, processed, but catalog item with SKU #{matched_catalog_item.sku} in state #{matched_catalog_item.state} (i.e. not active state)" msg = "EDI order for orchestrator: #{orchestrator.partner}, catalog item with SKU #{matched_catalog_item.sku} in state #{matched_catalog_item.state} (i.e. not active state). The order #{order.reference_number} has been processed but this is an indication of a possible issue with this catalog item." EdiMailer.notify_edi_admin_of_warning(subj, msg).deliver_later end else all_skus_valid = false bad_vendor_skus << vendor_sku.presence errors << "Unknown vendor sku: #{vendor_sku}" end end order.save! LineCreationResult.new(line_total: line_total, lines_created: order.line_items.size, all_skus_valid: all_skus_valid, error_message: "#{errors.to_sentence.capitalize}. Please fix the order message or catalog items, otherwise you will need to send a 'reject' acknowledgement with reason 'bad SKU'.", bad_vendor_skus: bad_vendor_skus.compact, bad_merchant_skus: bad_merchant_skus.compact) end |
#create_shipping_address(order_hash) ⇒ Array(Address, Hash)
Builds and saves the shipping Address from the message's shipTo block,
abbreviating streets and bypassing address correction/validation.
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
# File 'app/services/edi/wayfair/order_message_processor.rb', line 369 def create_shipping_address(order_hash) # "shipTo": { # "name": "John Smith", # "address1": "123 Test Street", # "address2": "Apartment 1", # "address3": null, # "city": "Boston", # "state": "MA", # "country": "US", # "postalCode": "02116", # "phoneNumber": "1234567890" # } raw_street1 = order_hash[:shipTo][:address1] raw_street2 = order_hash[:shipTo][:address2] originals = collect_street_originals(street1: raw_street1, street2: raw_street2) address = Address.new address.person_name_override = order_hash[:shipTo][:name].to_s.titleize.strip address.street1 = abbreviate_street(raw_street1) address.street2 = abbreviate_street(raw_street2) address.city = order_hash[:shipTo][:city] address.state_code = order_hash[:shipTo][:state] address.country_iso = order_hash[:shipTo][:country] || 'US' address.zip = order_hash[:shipTo][:postalCode].to_s.upcase.delete(' ').strip address.disable_address_correction = true address.override_all_address_validation = true address.save! [address, originals] end |
#customer(segment = nil) ⇒ Customer
The Wayfair customer record for the given segment.
42 43 44 |
# File 'app/services/edi/wayfair/order_message_processor.rb', line 42 def customer(segment = nil) orchestrator.customer(segment) end |
#match_shipping_code(shipping_speed, carrier_code = nil, is_puerto_rico = nil) ⇒ Edi::Wayfair::ShippingOptionResult?
Returns the shipping option name and special service to use like saturday delivery
406 407 408 |
# File 'app/services/edi/wayfair/order_message_processor.rb', line 406 def match_shipping_code(shipping_speed, carrier_code = nil, is_puerto_rico = nil) orchestrator.ship_code_mapper.wf_to_hw(shipping_speed, carrier_code, is_puerto_rico) end |
#process(edi_logs = nil, edi_transaction_id: nil) ⇒ Result
Picks up the edi communication log in the queue ready to process, generate acknowledgements
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 |
# File 'app/services/edi/wayfair/order_message_processor.rb', line 52 def process(edi_logs = nil, edi_transaction_id: nil) edi_logs ||= EdiCommunicationLog.requiring_processing.where(partner: orchestrator.partner, category: 'order_batch') edi_logs = [edi_logs].flatten # This way you can pass a single edi communication log # Wrap in one big transaction batch_process_results = [] edi_logs.each do |edi_log| log_info "Starting processing edi communication log #{edi_log.id}" EdiCommunicationLog.transaction do # Process the orders in the batch batch_process_result = process_orders(edi_log.data, edi_transaction_id: edi_transaction_id, edi_log_id: edi_log.id) # Record some meta data in file info edi_log.file_info ||= {} edi_log.file_info[:orders_in_batch] = batch_process_result.orders_in_batch # retrieve related packing slips for this batch of orders orchestrator.packing_slip_retriever.process(batch_process_result.orders_created) if orchestrator.packing_slip_enabled? batch_process_results << batch_process_result edi_log.complete! # Mark our edi log as processed, we need some error handling at one point # Associate the created orders batch_process_result.orders_created.each do |order| edi_log.edi_documents.create(order: order) end rescue StandardError => e edi_log.notes = "#{e} at #{e&.backtrace_locations}" edi_log.error ErrorReporting.error(e, edi_communication_log_id: edi_log.id) end end report_order_creation_issues(batch_process_results) Result.new(batch_process_results: batch_process_results) end |
#process_order(order_hash = nil) ⇒ Order
Process a single order
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 |
# File 'app/services/edi/wayfair/order_message_processor.rb', line 122 def process_order(order_hash = nil) # { # "id": 9942996, # "poNumber": "CA282800125", # "poDate": "2020-11-03 17:32:10.000000 +00:00", # "estimatedShipDate": "2020-11-04 00:00:00.000000 +00:00", # "customerName": "John Smith", # "customerAddress1": "123 Test Street", # "customerAddress2": "Apartment 1", # "customerCity": "Boston", # "customerState": "MA", # "customerCountry": "US", # "customerPostalCode": "02116", # "orderType": "B2B", # "shippingInfo": { # "shipSpeed": "GROUND", # "carrierCode": "UPSN" # }, # "packingSlipUrl": "https://sandbox.api.wayfair.com/v1/packing_slip/CA282800125", # "warehouse": { # "id": "24331", # "name": "CAN_WarmlyYours", # "address": { # "name": "CAN_WarmlyYours", # "address1": "300 Granton Drive", # "address2": "Unit 4A", # "address3": null, # "city": "Richmond Hill", # "state": "ON", # "country": "USA", # "postalCode": "L4B1H7" # } # }, # "products": [ # { # "partNumber": "TWS6-GRD10KH", # "quantity": "1", # "price": 539.4, # "event": null # } # ], # "shipTo": { # "name": "John Smith", # "address1": "123 Test Street", # "address2": "Apartment 1", # "address3": null, # "city": "Boston", # "state": "MA", # "country": "US", # "postalCode": "02116", # "phoneNumber": "1234567890" # } # } cust = customer order = cust.orders.build order. = order_hash.to_json order.edi_orchestrator_partner = orchestrator.partner.to_s order.edi_order_date = Time.zone.parse(order_hash[:poDate]).to_date # Parse "2020-11-03 17:32:10.000000 +00:00" to date order.edi_transaction_id = "#{order.edi_order_date}-#{order_hash[:id]}" order.edi_po_number = order_hash[:poNumber] address, address_originals = create_shipping_address(order_hash) order.shipping_address = address recipient_name = order.shipping_address.person_name_override || order.shipping_address.company_name_override order.customer_reference = "Purchase Order Number: #{order_hash[:poNumber]}" # original currency order.currency = cust.store.currency order.attention_name_override = recipient_name order.edi_shipping_option_name = set_shipping_option(order, order_hash) order.single_origin = true order.edi_is_pick_slip_required = cust.customer_record&.always_custom_packing_list? # Prevent auto coupons on EDI imports with externally set pricing/discounts order.disable_auto_coupon = true order.save! record_address_abbreviation_notes(order, address_originals, order.shipping_address) line_creation_result = create_line_items(order, order_hash) raise line_creation_result. unless line_creation_result.all_skus_valid apply_payment(order, order_hash) # Revenue before taxes (for price comparison), if price differs, problem, cr hold if orchestrator.test_mode? order.price_match = order.line_total else order.line_total line_creation_result.line_total order.price_match = line_creation_result.line_total # will get save when we call the event end order.state = 'in_cr_hold' # Set this as the default state order.recalculate_shipping = true order.save! order.reset_discount # temporary measure to force sanity and have revenue show on the order order.save! if (same_po_orders = Order.where(edi_po_number: order.edi_po_number).excluding(order)).any? # warn but don't release orders for every duplicate PO, let someone do it manually subj = "EDI order message for orchestrator: #{orchestrator.partner}, order #{order.reference_number} CREATED, order message PO: #{order.edi_po_number}, duplicate" msg = "EDI order for orchestrator: #{orchestrator.partner}, order #{order.reference_number}, has the same PO #{order.edi_po_number} as the following older EDI orders: #{same_po_orders.map do |o| "#{o.reference_number} (created #{o.created_at.to_date})" end.join(', ')}. It has been processed but this is an indication of a possible duplicate order or other issue." EdiMailer.notify_edi_admin_of_warning(subj, msg).deliver_later else order.reload.release_order # Then try to release, if there's any issue (discrepancy, etc) the order will remain on hold end # simplest thing to do is to flag the issue and raise an exception, don't even create the order # Only once the order is fully built: a rejected order raises before this, # and some processors rescue per-order INSIDE the batch transaction, which # would otherwise commit a promotion for an order we refused. onboard_ordered_catalog_items(order) order end |
#process_orders(orders_data, edi_transaction_id: nil, edi_log_id: nil) ⇒ BatchProcessResult
Iterates through the batch order data
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 |
# File 'app/services/edi/wayfair/order_message_processor.rb', line 90 def process_orders(orders_data, edi_transaction_id: nil, edi_log_id: nil) # rubocop:disable Lint/UnusedMethodArgument json_hash = JSON.parse(orders_data).with_indifferent_access orders_created = [] orders_in_batch = 0 json_hash[:data][:purchaseOrders].each do |order_hash| log_info "Processing order #{order_hash.inspect}" orders_in_batch += 1 po_number = order_hash[:poNumber] if Order.where('created_at > ?', 24.months.ago).where(edi_po_number: po_number).none? # only process these once since Wayfair does not have an acknowledged status, allow for duplicate EDI PO numbers (it has happened), as long as it has been at least 24 months old. We want to eliminate duplicate orders with the same PO, from message to message i.e. within ~the same day orders_created << process_order(order_hash) elsif (same_po_orders = Order.where(created_at: ...4.days.ago).where('created_at > ?', 24.months.ago).where(edi_po_number: po_number)).any? # otherwise warn that we skipped creating order because we found a matching PO order created older than four days ago, which might indicate the small chance of an order PO collision from another EDI partner # Only send notification if we haven't already notified about this duplicate PO unless duplicate_po_already_notified?(po_number, edi_log_id) msg = "EDI order message for orchestrator: #{orchestrator.partner}, EDI Communication log ID: #{edi_log_id}, order message PO: #{po_number}, has the same PO as the following recent EDI orders: #{same_po_orders.map do |o| "#{o.reference_number} (created #{o.created_at.to_date})" end.join(', ')}. It has been NOT been processed but SKIPPED as this is an indication of a duplicate order. Please ensure there is no PO number from another partner that might inadvertently match." # EdiMailer.notify_edi_admin_of_warning(subj, msg).deliver_later ErrorReporting.warning(msg.to_s) if Rails.env.production? mark_duplicate_po_as_notified(po_number, edi_log_id) end end end BatchProcessResult.new(batch_number: nil, orders_created: orders_created, orders_in_batch: orders_in_batch) end |
#set_shipping_option(order, order_hash) ⇒ String?
Maps the message's shipSpeed/carrierCode onto the order's shipping method
and requested ship dates.
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
# File 'app/services/edi/wayfair/order_message_processor.rb', line 276 def set_shipping_option(order, order_hash) # "shippingInfo": { # "shipSpeed": "GROUND", # "carrierCode": "UPSN" # }, shipping_speed = order_hash[:shippingInfo][:shipSpeed] carrier_code = order_hash[:shippingInfo][:carrierCode] # UPSN or FDEG is_puerto_rico = true if (order_hash[:shipTo] || {})[:state] == 'PR' shipping_option_result = match_shipping_code(shipping_speed, carrier_code, is_puerto_rico) order.edi_original_ship_code = "#{carrier_code} #{shipping_speed}" order.signature_confirmation = shipping_option_result&.signature order.shipping_method = shipping_option_result&.name ShippingOption.find_by(name: order.shipping_method) order.requested_ship_on_or_after = Time.zone.parse(order_hash[:poDate]).to_date # Parse "2020-11-03 17:32:10.000000 +00:00" to date order.requested_ship_before = Time.zone.parse(order_hash[:estimatedShipDate]).to_date # Parse "2020-11-03 17:32:10.000000 +00:00" to date if order.requested_ship_on_or_after && (order.requested_ship_on_or_after > Date.current) order.do_not_reserve_stock = false # we want to reserve the stock order.future_release_date = order.requested_ship_on_or_after end order.shipping_method end |
#shipping_invalid?(order) ⇒ Boolean
Whether the order's quoting delivery no longer matches the EDI shipping
option or signature confirmation captured from the order message.
240 241 242 243 244 245 246 247 248 |
# File 'app/services/edi/wayfair/order_message_processor.rb', line 240 def shipping_invalid?(order) dq = order.deliveries.quoting.first return true unless dq return true if dq.shipping_option.is_override? return true unless dq.shipping_option.name == order.edi_shipping_option_name return true unless dq.signature_confirmation == order.signature_confirmation false end |