Class: Edi::Amazon::OrderMessageProcessor

Inherits:
BaseEdiService show all
Defined in:
app/services/edi/amazon/order_message_processor.rb

Defined Under Namespace

Classes: BatchProcessResult, LineCreationResult, Result

Constant Summary

Constants included from Edi::AddressAbbreviator

Edi::AddressAbbreviator::MAX_LENGTH

Instance Attribute Summary

Attributes inherited from BaseEdiService

#orchestrator

Instance Method Summary collapse

Methods inherited from BaseEdiService

#duplicate_po_already_notified?, #initialize, #mark_duplicate_po_as_notified, #report_order_creation_issues, #safe_process_edi_communication_log

Methods included from Edi::AddressAbbreviator

#abbreviate_street, #collect_street_originals, #record_address_abbreviation_notes

Methods inherited from BaseService

#initialize, #log_debug, #log_error, #log_info, #log_warning, #logger, #options, #tagged_logger

Constructor Details

This class inherits a constructor from Edi::BaseEdiService

Instance Method Details

#apply_payment(order, order_hash) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'app/services/edi/amazon/order_message_processor.rb', line 274

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[:AmazonOrderId]
    payment.delivery = order.deliveries.quoting.first
    payment.save!
  end
end

#create_line_items(order, order_hash) ⇒ Object



363
364
365
366
367
368
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'app/services/edi/amazon/order_message_processor.rb', line 363

def create_line_items(order, order_hash)
  # "OrderItems" => [
  #  {
  #            "TaxCollection" => {
  #                    "Model" => "MarketplaceFacilitator",
  #         "ResponsibleParty" => "Amazon Services, Inc."
  #     },
  # ...
  #                  "ItemTax" => {
  #         "CurrencyCode" => "USD",
  #               "Amount" => "17.34"
  #     },
  #          "QuantityShipped" => 1,
  # ...
  #                "ItemPrice" => {
  #         "CurrencyCode" => "USD",
  #               "Amount" => "216.75"
  #     },
  #                     "ASIN" => "B007V46Q6K",
  #                "SellerSKU" => "TRT120-1.5x12",
  #                    "Title" => "Warmly Yours TRT120-1.5x12 TempZone Electric Radiant Floor Heating Flex Roll, 18 sq. ft",
  #              "ShippingTax" => {
  #         "CurrencyCode" => "USD",
  #               "Amount" => "0.91"
  #     },
  # ...
  #            "ShippingPrice" => {
  #         "CurrencyCode" => "USD",
  #               "Amount" => "11.34"
  # ...
  #          "QuantityOrdered" => 1,
  #          "OrderItemId" => "122128512084961"
  # }
  # ]

  line_total = BigDecimal(0)
  shipping_price_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: %w[active active_hidden require_vendor_update pending_vendor_update pending_discontinue]).order(state: :asc)
  is_replacement_order = order_hash[:IsReplacementOrder].to_b
  order_hash.dig(:OrderItems).each_with_index do |line_hash, i|
    quantity_ordered = line_hash.dig(:QuantityOrdered).to_i
    if quantity_ordered.zero?
      subj = "EDI order for orchestrator: #{orchestrator.partner}, processed, but there is a zero quantity ordered"
      msg = "EDI order for orchestrator: #{orchestrator.partner}, SKU #{line_hash[:SellerSKU] || line_hash[:ASIN]}. The order #{order.reference_number} has been processed but this is a zero quantity ordered."
      InternalMailer.notify_edi_admin_of_warning(subj, msg).deliver_later
      next
    end

    # First we try by vendor product identifier
    vendor_sku = line_hash[:SellerSKU]
    # then we try by buyer product identifier
    buyer_asin = line_hash[:ASIN]
    raise 'Missing identifiers SellerSKU and ASIN in order query' if vendor_sku.blank? && buyer_asin.blank?

    # Check if this is a cancellation!
    cancel = line_hash.dig(:BuyerRequestedCancel, :IsBuyerRequestedCancel).to_b
    matched_catalog_item = nil
    matched_catalog_item ||= catalog_items.by_skus(vendor_sku).first if vendor_sku.present?
    matched_catalog_item ||= catalog_items.by_asins(buyer_asin).first if buyer_asin.present?
    if matched_catalog_item
      order.line_items.build.tap do |line_item|
        line_item.quantity = quantity_ordered # 2
        line_item.edi_reference = line_hash[:OrderItemId] # old style/legacy: "#{order_hash[:AmazonOrderId]}-#{i + 1}"
        line_item.edi_line_number = i + 1
        line_item.catalog_item = matched_catalog_item
        price = is_replacement_order ? 0.0 : BigDecimal(line_hash.dig(:ItemPrice, :Amount).to_s) / quantity_ordered
        shipping_price = is_replacement_order ? 0.0 : BigDecimal((line_hash.dig(:ShippingPrice, :Amount) || 0.0).to_s)
        line_item.price = price
        line_item.edi_unit_cost = price
        line_total += price * line_item.quantity
        shipping_price_total += shipping_price
      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."
        InternalMailer.notify_edi_admin_of_warning(subj, msg).deliver_later
      end
      if cancel
        cancel_details = line_hash.dig(:BuyerRequestedCancel, :BuyerCancelReason).presence || 'REASON_LEFT_UNSPECIFIED'
        subj = "EDI order for orchestrator: #{orchestrator.partner}, processed, but there is a cancellation request"
        msg = "EDI order for orchestrator: #{orchestrator.partner}, SKU #{matched_catalog_item.sku}. The order #{order.reference_number} has been processed but this is a cancellation request, Buyer Cancel Reason: #{cancel_details}"
        InternalMailer.notify_edi_admin_of_warning(subj, msg).deliver_later
        order.cancellation_reason = cancel_details
      end
    else
      all_skus_valid = false
      bad_vendor_skus << vendor_sku.presence
      bad_merchant_skus << buyer_asin.presence
      errors << "Unknown vendor sku: #{vendor_sku} / ASIN: #{buyer_asin}"
    end
  end

  # Shipping pricing has already been set above after recalculate_shipping
  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 or catalog items.", bad_vendor_skus: bad_vendor_skus.compact,
                         bad_merchant_skus: bad_merchant_skus.compact)
end

#create_shipping_address(order_hash) ⇒ Object



465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'app/services/edi/amazon/order_message_processor.rb', line 465

def create_shipping_address(order_hash)
  # {
  #   "StateOrRegion" => "MN",
  #    "AddressLine1" => "1805 HAVEN RD",
  #           "Phone" => "+1 929-436-4790 ext. 38661",
  #      "PostalCode" => "56345-2286",
  #            "City" => "LITTLE FALLS",
  #     "CountryCode" => "US",
  #     "AddressType" => "Commercial",
  #            "Name" => "XXX XXX"
  # }

  # {
  #   "StateOrRegion": "Manitoba",
  #   "AddressLine1": "PO Box 412",
  #   "PostalCode": "R0L0C0",
  #   "City": "Benito",
  #   "CountryCode": "CA",
  #   "Name": "David Pleli"
  # }

  raw_street1 = order_hash.dig(:ShippingAddressPii, :AddressLine1)
  raw_street2 = order_hash.dig(:ShippingAddressPii, :AddressLine2)
  originals = collect_street_originals(street1: raw_street1, street2: raw_street2)

  address = Address.new
  # Here we are using the ShippingAddressPii we extracted using a restricted data token
  address.person_name_override = order_hash.dig(:ShippingAddressPii, :Name).to_s.titleize.strip
  address.street1 = abbreviate_street(raw_street1)
  address.street2 = abbreviate_street(raw_street2)
  address.city = order_hash.dig(:ShippingAddressPii, :City)
  address.country_iso = order_hash.dig(:ShippingAddressPii, :CountryCode)
  address.state_code = State.code_for_string(order_hash.dig(:ShippingAddressPii, :StateOrRegion), countries_iso3: [Country.iso3_for_string(address.country_iso)]) # we get state code for US but Province name for Canada!
  address.zip = order_hash.dig(:ShippingAddressPii, :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) ⇒ Object



15
16
17
# File 'app/services/edi/amazon/order_message_processor.rb', line 15

def customer(segment = nil)
  orchestrator.customer(segment)
end

#match_shipping_code(shipping_code) ⇒ Object

Returns the shipping option name and special service to use like saturday delivery



506
507
508
# File 'app/services/edi/amazon/order_message_processor.rb', line 506

def match_shipping_code(shipping_code)
  orchestrator.ship_code_mapper.az_to_hw(shipping_code)
end

#process(edi_logs = nil, edi_transaction_id: nil) ⇒ Object

Picks up the edi communication log in the queue ready to process, generate acknowledgements



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
# File 'app/services/edi/amazon/order_message_processor.rb', line 20

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
      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 begin rescue block
    end # End transaction
  end # End edi log iteration
  Result.new(batch_process_results: batch_process_results)
end

#process_order(order_hash = nil) ⇒ Object

Process a single order



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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'app/services/edi/amazon/order_message_processor.rb', line 92

def process_order(order_hash = nil)
  # {
  #                          "BuyerInfo" => {
  #         "BuyerEmail" => "mh8bs1ln08v30sq@marketplace.amazon.com"
  #     },
  #                      "AmazonOrderId" => "111-9561766-6637803",
  #               "EarliestDeliveryDate" => "2024-10-15T07:00:00Z",
  #                   "EarliestShipDate" => "2024-10-11T07:00:00Z",
  #                       "SalesChannel" => "Amazon.com",
  #          "AutomatedShippingSettings" => {
  #                     "AutomatedCarrier" => "FedEx",
  #         "HasAutomatedShippingSettings" => true,
  #                  "AutomatedShipMethod" => "FedEx Home Delivery®",
  #              "AutomatedShipMethodName" => "FedEx Home Delivery®",
  #                 "AutomatedCarrierName" => "FedEx"
  #     },
  #                        "OrderStatus" => "Shipped",
  #               "NumberOfItemsShipped" => 1,
  #                          "OrderType" => "StandardOrder",
  #                     "IsPremiumOrder" => false,
  #                            "IsPrime" => false,
  #                 "FulfillmentChannel" => "MFN",
  #             "NumberOfItemsUnshipped" => 0,
  #                  "HasRegulatedItems" => false,
  #                 "IsReplacementOrder" => "false",
  #                         "IsSoldByAB" => false,
  #                     "LatestShipDate" => "2024-10-12T06:59:59Z",
  #                   "ShipServiceLevel" => "Std US D2D Dom",
  #     "DefaultShipFromLocationAddress" => {
  #         "StateOrRegion" => "IL",
  #          "AddressLine1" => "null",
  #            "PostalCode" => "60047-1584",
  #                  "City" => "LAKE ZURICH",
  #           "CountryCode" => "US",
  #                  "Name" => "null"
  #     },
  #                             "IsISPU" => false,
  #                      "MarketplaceId" => "ATVPDKIKX0DER",
  #                 "LatestDeliveryDate" => "2024-10-16T06:59:59Z",
  #                       "PurchaseDate" => "2024-10-11T03:13:18Z",
  #                    "ShippingAddress" => {
  #         "StateOrRegion" => "NJ",
  #            "PostalCode" => "07950-2741",
  #                  "City" => "MORRIS PLAINS",
  #           "CountryCode" => "US"
  #     },
  #                 "IsAccessPointOrder" => false,
  #                      "PaymentMethod" => "Other",
  #                    "IsBusinessOrder" => false,
  #                         "OrderTotal" => {
  #         "CurrencyCode" => "USD",
  #               "Amount" => "423.03"
  #     },
  #               "PaymentMethodDetails" => [
  #         [0] "Standard"
  #     ],
  #             "IsGlobalExpressEnabled" => false,
  #                     "LastUpdateDate" => "2024-10-11T14:23:13Z",
  #       "ShipmentServiceLevelCategory" => "Standard"
  # }
  cust = customer
  order = cust.orders.build
  order.edi_original_order_message = order_hash.to_json
  order.edi_orchestrator_partner = orchestrator.partner.to_s
  order.edi_order_date = Time.zone.parse(order_hash.dig(:PurchaseDate)).to_date # Parse "2020-11-03 17:32:10.000000 +00:00" to date
  order.edi_transaction_id = "#{order.edi_order_date}-#{order_hash[:AmazonOrderId]}"
  order.edi_po_number = order_hash[:AmazonOrderId]
  address, address_originals = create_shipping_address(order_hash)
  order.shipping_address = address
  order.shipping_phone = order_hash.dig(:ShippingAddressPii, :Phone)
  recipient_name = order.shipping_address.person_name_override || order.shipping_address.company_name_override
  order.customer_reference = "Purchase Order Number: #{order_hash[:AmazonOrderId]}, Customer Order Number: #{order_hash.dig(:AmazonOrderId)}"
  # original currency
  order.currency = cust.store.currency
  order.attention_name_override = recipient_name
  order.single_origin = true
  order.edi_is_pick_slip_required = true
  # 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)
  order.quick_note('Replacement Order') if order_hash[:IsReplacementOrder].to_b
  line_creation_result = create_line_items(order, order_hash)
  raise line_creation_result.error_message unless line_creation_result.all_skus_valid

  order.edi_shipping_option_name = set_shipping_option(order, order_hash) # This sets order.shipping_metho, ship window etc.

  # Save line items before apply_payment (which does order.reload)
  order.save!

  # Sanity check: verify order was created with correct number of line items
  # Count only parent line items (kits create multiple child line items)
  expected_line_item_count = order_hash[:OrderItems].select{|o_item_h| o_item_h[:QuantityOrdered] != 0}&.count || 0 # we have to allow for QuantityOrdered of 0 per order 113-9349399-0115441
  order.reload
  actual_line_item_count = order.line_items.goods.where(parent_id: nil).count
  if actual_line_item_count != expected_line_item_count
    raise "Order creation failed sanity check: expected #{expected_line_item_count} line items but order #{order.reference_number} has #{actual_line_item_count}. Amazon Order ID: #{order_hash[:AmazonOrderId]}"
  end

  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!

  # After deliveries are created, update them with Amazon's shipping pricing
  # (Amazon provides shipping costs that may differ from calculated rates)
  # After deliveries are created with shipping costs, map Amazon's shipping code to our shipping option
  order.reload
  delivery = order.deliveries.first

  # Calculate total shipping price from order items (Amazon sends shipping price per item)
  is_replacement_order = order_hash[:OrderType] == 'Replacement'
  shipping_price_total = if is_replacement_order
                           0.0
                         else
                           order_hash[:OrderItems]&.sum do |item|
                             BigDecimal((item.dig(:ShippingPrice, :Amount) || 0.0).to_s)
                           end || 0.0
                         end
  # Now apply them to the delivery selected cost and/or override
  if delivery && delivery.shipping_costs.any?
    matched_cost = delivery.selected_shipping_cost
    matched_cost ||= delivery.shipping_costs.override_only.first || delivery.shipping_costs.first
    if matched_cost
      # Select this shipping cost and override the price with Amazon's provided amount
      # Set description to show Amazon's original codes
      matched_cost.description_override = order.edi_original_ship_code
      matched_cost.save!
      delivery.selected_shipping_cost = matched_cost
      delivery.save!
    end
  end
  # Update the shipping line item to match
  shipping_line_item = order.line_items.shipping_only.first
  if shipping_line_item
    shipping_line_item.price = shipping_price_total
    shipping_line_item.discounted_price = shipping_price_total
    shipping_line_item.description = order.edi_original_ship_code
    shipping_line_item.save!
  end

  order.save!
  order.commit_line_items # Reserve  stock.
  same_po_orders = orchestrator.orders_with_amazon_id_po(order.edi_po_number).select { |o| o.id != order.id }
  if same_po_orders.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."
    InternalMailer.notify_edi_admin_of_warning(subj, msg).deliver_later
  elsif order.cancellation_reason.present?
    order.reload.cancel
    # 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

  order
end

#process_orders(orders_data, edi_transaction_id: nil, edi_log_id: nil) ⇒ Object

Iterates through the batch order data



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
# File 'app/services/edi/amazon/order_message_processor.rb', line 51

def process_orders(orders_data, edi_transaction_id: nil, edi_log_id: nil)
  json_hash = JSON.parse(orders_data).with_indifferent_access
  orders_created = []
  orders_in_batch = 0
  (json_hash.dig(:payload, :Orders) || []).each do |order_hash|
    log_info "Processing order #{order_hash.inspect}"
    orders_in_batch += 1
    po_number = order_hash[:AmazonOrderId]
    begin
      same_po_orders = orchestrator.orders_with_amazon_id_po(po_number)
      if same_po_orders.select { |o| o.created_at > 12.months.ago }.none?
        # only process these once, allow for duplicate EDI PO numbers (it has happened), as long as it has been at least 12 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 (recent_same_po_orders = # 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
               same_po_orders.select do |o|
                 o.created_at < 4.days.ago && o.created_at > 12.months.ago && !o.suppress_edi_duplicate_warning?
               end).any?
        # Only send notification if we haven't already notified about this duplicate PO
        unless duplicate_po_already_notified?(po_number, edi_log_id)
          subj = "EDI order message for orchestrator: #{orchestrator.partner}, SKIPPED, order message PO: #{po_number}, duplicate"
          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: #{recent_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."
          InternalMailer.notify_edi_admin_of_warning(subj, msg).deliver_later
          mark_duplicate_po_as_notified(po_number, edi_log_id)
        end
      end
    rescue StandardError => e
      subj = "EDI order message for orchestrator: #{orchestrator.partner}, ERROR, SKIPPED, order message PO: #{po_number}, #{e.message}"
      msg = "Exception #{e.message} while processing amazon order #{po_number} with orchestrator #{orchestrator.partner}, and edi log id #{edi_log_id}"
      ErrorReporting.error e, msg
      InternalMailer.notify_edi_admin_of_warning(subj, msg).deliver_later
    end
  end
  InternalMailer.edi_orders_notification(orders_created).deliver_later if orders_created.any?
  BatchProcessResult.new(batch_number: nil,
                         orders_created: orders_created,
                         orders_in_batch: orders_in_batch)
end

#set_shipping_option(order, order_hash) ⇒ Object



289
290
291
292
293
294
295
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
# File 'app/services/edi/amazon/order_message_processor.rb', line 289

def set_shipping_option(order, order_hash)
  # Here we will create a manual override pending a full shipping integration, but pay attention to the
  # - shipping window dates
  # - ship service level/category
  # - automated shipping setting

  # typical US order hash:
  # {
  # ...
  #                       "SalesChannel" => "Amazon.com",
  # ...
  #               "EarliestDeliveryDate" => "2024-10-12T07:00:00Z",
  #                   "EarliestShipDate" => "2024-10-11T07:00:00Z",
  #          "AutomatedShippingSettings" => {
  #                     "AutomatedCarrier" => "FedEx",
  #         "HasAutomatedShippingSettings" => true,
  #                  "AutomatedShipMethod" => "FedEx Overnight®",
  #              "AutomatedShipMethodName" => "FedEx Overnight®",
  #                 "AutomatedCarrierName" => "FedEx"
  #     },
  # ...
  #                     "IsPremiumOrder" => true,
  #                            "IsPrime" => false,
  # ...
  #                     "LatestShipDate" => "2024-10-12T06:59:59Z",
  #                   "ShipServiceLevel" => "Next US D2D Dom",
  # ...
  #                 "LatestDeliveryDate" => "2024-10-13T06:59:59Z",
  #                       "PurchaseDate" => "2024-10-11T16:52:54Z",
  # ...
  #       "ShipmentServiceLevelCategory" => "NextDay" # Possible values: Expedited, FreeEconomy, NextDay, Priority, SameDay, SecondDay, Scheduled, and Standard.
  # }

  # typical CA order hash:
  # {
  # ...
  #                       "SalesChannel" => "Amazon.ca",
  # ...
  #               "EarliestDeliveryDate" => "2024-10-18T07:00:00Z",
  #                   "EarliestShipDate" => "2024-10-15T07:00:00Z",
  #          "AutomatedShippingSettings" => {
  #         "HasAutomatedShippingSettings" => false
  #     },
  # ...
  #                     "LatestShipDate" => "2024-10-16T06:59:59Z",
  #                   "ShipServiceLevel" => "Std CA D2D Dom",
  # ...
  #                 "LatestDeliveryDate" => "2024-10-23T06:59:59Z",
  #                       "PurchaseDate" => "2024-10-15T00:17:24Z",
  # ...
  #       "ShipmentServiceLevelCategory" => "Standard" # Possible values: Expedited, FreeEconomy, NextDay, Priority, SameDay, SecondDay, Scheduled, and Standard.
  # }

  shipping_code = "#{order_hash.dig(:ShipmentServiceLevelCategory) || 'UNSP'}"
  shipping_code = "#{shipping_code} (suggested: #{order_hash.dig(:AutomatedShippingSettings, :AutomatedShipMethod)})" if order_hash.dig(:AutomatedShippingSettings)&.dig(:AutomatedShipMethod)
  order.edi_original_ship_code = shipping_code

  if orchestrator.buy_shipping_enabled?
    order.shipping_method = 'amzbs'
    order.purchase_label_early = true
  else
    order.shipping_method = 'override'
  end

  order.requested_ship_on_or_after ||= Date.current
  order.requested_ship_before = Date.parse(order_hash.dig(:LatestShipDate)) if order_hash.dig(:LatestShipDate).present?
  order.requested_deliver_by = Date.parse(order_hash.dig(:LatestDeliveryDate)).prev_day if order_hash.dig(:LatestDeliveryDate).present?
  if order.requested_ship_on_or_after && (order.requested_ship_on_or_after > Date.current)
    order.do_not_reserve_stock = false
    order.future_release_date = order.requested_ship_on_or_after
  end
  order.shipping_method
end

#shipping_invalid?(order) ⇒ Boolean

Returns:

  • (Boolean)


264
265
266
267
268
269
270
271
272
# File 'app/services/edi/amazon/order_message_processor.rb', line 264

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