Class: Edi::MftGateway::OrderMessageProcessor

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

Defined Under Namespace

Classes: BatchProcessResult, LineCreationResult, Result

Constant Summary collapse

REQUESTED_SHIP_BEFORE_DATE_CODES =

Per DSCO EDI spec: ‘038’ for Line Item Ship By Date.

%w[038 068 110 369]
REQUESTED_SHIP_AFTER_DATE_CODES =

010: Requested Ship, 068: Scheduled Ship, 110: Originally Scheduled Ship, 369: Estimated Departure Date

%w[010 037 071]
REQUESTED_ARRIVAL_DATE_CODES =

037: Earliest Ship, 071: First Arrive

%w[002 017 063 067 069 074 371]

Constants included from AddressAbbreviator

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 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



191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'app/services/edi/mft_gateway/order_message_processor.rb', line 191

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.dig(:Header, :OrderHeader, :PurchaseOrderNumber) # 234234
    payment.delivery = order.deliveries.quoting.first
    payment.save!
  end
end

#create_line_items(order, order_hash) ⇒ Object



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

def create_line_items(order, order_hash)
  line_total = BigDecimal(0)
  cust = order.customer
  all_skus_valid = true
  errors = []
  bad_vendor_skus = []
  bad_merchant_skus = []
  # Look for an item that is in a state suitable to be accepted by the merchant partner, adding active_hidden because this is a live order so do not prevent the order from processing, but perhaps notify
  catalog_items = cust.catalog.catalog_items.where(state: %w[active active_hidden require_vendor_update pending_vendor_update pending_discontinue pending_onboarding]).order('state ASC')
  (order_hash.dig(:Structure, :LineItem) || []).each do |line_hash|
    merchant_sku = line_hash.dig(:OrderLine, :BuyerPartNumber) || line_hash.dig(:OrderLine, :SKU)
    vendor_sku = line_hash.dig(:OrderLine, :VendorPartNumber)
    upc = line_hash.dig(:OrderLine, :ConsumerPackageCode)
    raise 'Missing identifier sku in file' if vendor_sku.blank? && merchant_sku.blank?

    # Typical OrderLines:
    # "Structure": {
    #     "LineItem": [
    #         {
    #             "OrderLine": {
    #                 "LineSequenceNumber": "1",
    #                 "VendorPartNumber": "TW-F10KS-HP",
    #                 "ConsumerPackageCode": "881308069032",
    #                 "OrderQty": 1,
    #                 "OrderQtyUOM": "EA",
    #                 "PurchasePrice": 440.30
    #             }
    #         },
    #         {
    #             "OrderLine": {
    #                 "LineSequenceNumber": "2",
    #                 "VendorPartNumber": "TW-55252-HP",
    #                 "ConsumerPackageCode": "46535336366",
    #                 "OrderQty": 5,
    #                 "OrderQtyUOM": "EA",
    #                 "PurchasePrice": 234.10
    #             }
    #         }
    #     ]
    # },
    # First we try by promo sku
    matched_catalog_item = catalog_items.find_by(third_party_promo_part_number: merchant_sku) if merchant_sku.present?
    # If no match on that, try by merchant sku
    matched_catalog_item ||= catalog_items.find_by(third_party_part_number: merchant_sku) if merchant_sku.present?
    if vendor_sku.present?
      # vendor sku vs third_party_part_number
      matched_catalog_item ||= catalog_items.find_by(third_party_part_number: vendor_sku)
      # If no match, try third party sku but only on active items
      matched_catalog_item ||= catalog_items.find_by(third_party_sku: vendor_sku)
      # If no match, use our vendor SKU
      matched_catalog_item ||= catalog_items.by_skus(vendor_sku).first
    end
    # try UPC
    matched_catalog_item ||= catalog_items.by_upcs(upc).first if upc.present?
    # And finally, try merchant SKU
    matched_catalog_item ||= catalog_items.by_skus(merchant_sku).first if merchant_sku.present?

    if matched_catalog_item
      order.line_items.build.tap do |line_item|
        line_hash.dig(:OrderLine, :OrderQtyUOM) # EA
        # Frankly we don't care the uom, it is always one of whatever we have listed with them
        # raise "Unknown unit of measure in edi order id #{order.customer_reference}" unless %w[EA PK].include?(uom) # for now we can't handle anything else

        line_item.quantity = line_hash.dig(:OrderLine, :OrderQty).to_i # 3
        line_item.edi_reference = "#{order.edi_po_number}_#{line_hash.dig(:OrderLine, :LineSequenceNumber)}" # no ref id per line item so use PO and line item sequence number
        line_item.edi_line_number = line_hash.dig(:OrderLine, :LineSequenceNumber) # 1
        requested_ship_date = nil
        requested_arrival_date = nil
        (order_hash.dig(:Dates) || []).each do |date_hash|
          dtq = date_hash.dig(:DateTimeQualifier)
          if REQUESTED_SHIP_DATE_CODES.include?(dtq)
            requested_ship_date = Date.parse(date_hash.dig(:Date)) # Parse "2022-05-22"
          end
          if REQUESTED_ARRIVAL_DATE_CODES.include?(dtq)
            requested_arrival_date = Date.parse(date_hash.dig(:Date)) # Parse "2022-05-22"
          end
        end
        line_hash.dig(:ProductOrItemDescription, :ProductDescription)
        line_item.catalog_item = matched_catalog_item
        price = BigDecimal(line_hash.dig(:OrderLine, :PurchasePrice).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."
        InternalMailer.notify_edi_admin_of_warning(subj, msg).deliver_later
      end
    else
      all_skus_valid = false
      bad_vendor_skus << vendor_sku.presence
      bad_merchant_skus << merchant_sku.presence
      errors << "Unknown vendor sku: #{vendor_sku} / merchant sku: #{merchant_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

#customer(segment = nil) ⇒ Object

002: Requested Delivery, 017: Estimated Delivery, 063: Latest Delivery, 067: Current Schedule Delivery, 069: Promised For Delivery, 074: Last Arrive, 371: Estimated Arrival Date



19
20
21
# File 'app/services/edi/mft_gateway/order_message_processor.rb', line 19

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

#extract_ship_to_info(order_hash, country_iso3) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
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
# File 'app/services/edi/mft_gateway/order_message_processor.rb', line 352

def extract_ship_to_info(order_hash, country_iso3)
  # "Address": [
  # "Address": [
  #     {
  #         "AddressTypeCode": "ST",
  #         "LocationCodeQualifier": "92",
  #         "AddressLocationNumber": "02",
  #         "AddressName": "Customer Name",
  #         "Address1": "123 Street Rd",
  #         "City": "City Name",
  #         "State": "CA",
  #         "PostalCode": "902101234",
  #         "Country": "US",
  #         "Contacts":[ {
  #             "ContactTypeCode": "IC",
  #             "PrimaryPhone": "1234567890"
  #         }]
  #     },
  #     {
  #         "AddressTypeCode": "BT",
  #         "LocationCodeQualifier": "9",
  #         "AddressLocationNumber": "847174989",
  #         "AddressName": "Build.com",
  #         "Address1": "402 Otterson Dr Ste 100",
  #         "City": "Chico",
  #         "State": "CA",
  #         "PostalCode": "95928"
  #     }
  # ],

  res = {}
  (order_hash.dig(:Header, :Address) || []).each do |address_hash|
    # Assume only one ST or MA Address will be here so taking the first one will work
    next unless %w[ST MA].include?(address_hash.dig(:AddressTypeCode)) # MA Address is used for Canadian Tire, to support ship to store, use store number in AddressLocationNumber or last half of Address1

    store_number = (address_hash.dig(:AddressLocationNumber) || address_hash.dig(:Address1).to_s.split('#').last.delete(' ')).last(4) # we only want last 4 digits here, CT sometimes passes on an extra digit to indicate some other store status which is not material to us
    if orchestrator.partner == :mft_gateway_canadian_tire && store_number.present?
      res[:address] = orchestrator.customer.find_or_create_canadian_tire_address_from_store_number(store_number) # deal with inconsistent store address naming
    else
      address = Address.new
      if orchestrator.partner == :mft_gateway_canadian_tire
        # Argh ^&$^&% Canadian Tire and ^&$%&^% DSCO! Though we should probably never get here...
        address.company_name_override = address_hash.dig(:Address1) # this should only ever be a CT store with the address.company_name following the regex CustomerConstants::CANADIAN_TIRE_STORE_NAME_REGEX
        raw_street1 = address_hash.dig(:Address2)
        raw_street2 = address_hash.dig(:Address3)
      else
        address.person_name_override = address_hash.dig(:AddressName) # otherwise assume a human customer
        raw_street1 = address_hash.dig(:Address1)
        raw_street2 = address_hash.dig(:Address2)
        raw_street3 = address_hash.dig(:Address3)
      end
      res[:address_originals] = collect_street_originals(street1: raw_street1, street2: raw_street2, street3: raw_street3)
      address.street1 = abbreviate_street(raw_street1)
      address.street2 = abbreviate_street(raw_street2)
      address.street3 = abbreviate_street(raw_street3) if raw_street3.present?
      address.city = address_hash.dig(:City)
      address.state_code = address_hash.dig(:State)
      address.country_iso3 = Country.where(iso: address_hash.dig(:Country)).first&.iso3
      postal_code = address_hash.dig(:PostalCode).to_s.upcase.delete(' ').strip
      is_usa = true if address.country_iso3.to_s.upcase == 'USA' || country_iso3 == 'USA'
      address.zip = (is_usa ? postal_code.to_s.first(5) : postal_code) # only take first 5 of zip when country is USA, because they sometimes send us incorrectly rendered zip5-code4
      address.disable_address_correction = true
      address.override_all_address_validation = true
      address.save!
      # determine if address is residential
      address.is_residential = WyShipping.is_address_residential?(address) # let's just set this correctly if we can
      # here we have to assume the address is freight ready if they ask us to ship via ltl freight or it will be held require manual intervention etc so set defaults and save to mark address as valid for freight
      address.set_freight_field_defaults
      address.save!
      res[:address] = address
    end

    if (number = address_hash.dig(:AddressLocationNumber)) && number&.size == 10 # here SPS Commerce seems to send ship to phone numbers in the &**&%^v AddressLocationNumber!
      res[:contact_phone] = number
    end

    (address_hash.dig(:Contacts) || []).each do |contact_hash|
      if %w[IC OC RE SC].include?(contact_hash.dig(:ContactTypeCode)) # IC: Primary Information Contact, OC: Order Contact, RE: Receiving Contact, The recipient receiving the merchandise, SC: Shipping Contact, Point of contact for shipping information
        res[:contact_name] = contact_hash.dig(:ContactName)
        res[:contact_email] = contact_hash.dig(:PrimaryEmail)
        res[:contact_phone] = contact_hash.dig(:PrimaryPhone)
      end
      break
    end
  end
  res
end

#match_shipping_code(ch_shipping_code) ⇒ Object

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



441
442
443
444
445
# File 'app/services/edi/mft_gateway/order_message_processor.rb', line 441

def match_shipping_code(ch_shipping_code)
  raise "Unmatched shipping code #{ch_shipping_code}" unless shipping_match = orchestrator.ship_code_mapper.ch_to_hw(ch_shipping_code)

  shipping_match
end

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

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



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

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}"
    begin
      EdiCommunicationLog.transaction do
        # Process the orders in the batch
        batch_process_result = process_orders(edi_log.data, file_name: edi_log.file_name, 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
        # 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
        # Generate an acknowledgement
        # ack_xml = orchestrator.fa_message_processor.process(batch_process_result)
        batch_process_results << batch_process_result
        edi_log.complete!
      end # End transaction
    rescue StandardError => e
      edi_log.notes = "#{e} at #{e&.backtrace_locations&.first}"
      edi_log.error
      ErrorReporting.error(e, edi_communication_log_id: edi_log.id)
      # End transaction
    end
  end # End edi log iteration
  report_order_creation_issues(batch_process_results)
  Result.new(batch_process_results: batch_process_results)
end

#process_order(order_hash = nil, file_name: nil) ⇒ Object

Process a single order



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

def process_order(order_hash = nil, file_name: nil)
  # "Header": {
  #     "OrderHeader": {
  #         "PurchaseOrderNumber": "896628588",
  #         "TsetPurposeCode": "00",
  #         "PrimaryPOTypeCode": "DR",
  #         "PurchaseOrderDate": "2023-01-27",
  #         "Vendor": "Warmly_Yours"
  #     },
  # }
  cust = customer
  order = cust.orders.build
  # sigh SPS requires all kinds of bizarre useless data we don't store sent back to them on various acknowledge and shipment messages, so let's store the whole order message so we can retrieve it and send the &^*%&^% crap back to them
  order.edi_original_order_message = order_hash.to_json
  order.edi_orchestrator_partner = orchestrator.partner.to_s
  order.edi_po_number = order_hash.dig(:Header, :OrderHeader, :PurchaseOrderNumber)
  # TsetPurposeCode
  order_hash.dig(:Header, :OrderHeader, :TsetPurposeCode) # 00: Original, 01: Cancellation, 05: Replace
  order_hash.dig(:Header, :OrderHeader, :PrimaryPOTypeCode) #  KN: Cross Dock, SA: Stand Alone, DS: Drop Ship
  order.edi_order_date = Date.parse(order_hash.dig(:Header, :OrderHeader, :PurchaseOrderDate)) # Parse "2022-05-19"
  order_hash.dig(:Header, :OrderHeader, :Vendor)
  order.edi_transaction_id = "#{order.edi_order_date}_#{file_name}_#{order.edi_po_number}"
  ship_to_info = extract_ship_to_info(order_hash, order&.store&.country_iso3)
  order.shipping_address = ship_to_info[:address]
  address_originals = ship_to_info[:address_originals]
  order.tracking_email << ship_to_info[:contact_email] if ship_to_info[:contact_email].present?
  order.shipping_phone = ship_to_info[:contact_phone]
  recipient_name = ship_to_info[:contact_name] || order.shipping_address.person_name_override || order.shipping_address.company_name_override
  customer_order_number = order_hash.dig(:Header, :OrderHeader, :CustomerOrderNumber)
  customer_sales_order_number = order_hash.dig(:Header, :OrderHeader, :SalesOrderNumber)
  order.customer_reference = "Partner Order Nbr: #{customer_order_number || order.edi_po_number}#{" | #{customer_sales_order_number}" if customer_sales_order_number.present?}"
  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.error_message 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).where.not(id: order.id)).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
  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

  order
end

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

Iterates through the batch order data



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

def process_orders(orders_data, file_name: nil, edi_transaction_id: nil, edi_log_id: nil)
  json_hash_or_arr = JSON.parse(orders_data)
  json_hash_arr = if json_hash_or_arr.is_a?(Array)
                    json_hash_or_arr
                  else
                    [json_hash_or_arr]
                  end
  orders_created = []
  orders_in_batch = 0
  json_hash_arr.each do |order_hsh|
    order_hash = order_hsh.with_indifferent_access
    log_info "Processing order #{order_hash.inspect}"
    po_number = order_hash.dig(:Header, :OrderHeader, :PurchaseOrderNumber)
    purpose_code = order_hash.dig(:Header, :OrderHeader, :TsetPurposeCode) # 00: Original, 01: Cancellation, 04: some sort of canadian Tire change code, 05: Replace
    if purpose_code != '00'
      # handle cancellation
      order_to_cancel = customer.orders.not_cancelled.not_processing_deliveries.not_partially_invoiced.where(edi_po_number: po_number).first
      if order_to_cancel
        order_to_cancel.cancellation_reason = (purpose_code == '01' ? 'merchant_request' : 'vendor_request: we fill or kill orders as is, we do not accept any changes once order processing has begun')
        order_to_cancel.cr_hold # in case awaiting deliveries
        order_to_cancel.cancel!
        InternalMailer.notify_edi_admin_of_edi_cancel(order_to_cancel,
                                                      "EDI 850 with purpose_code: #{purpose_code} initiated cancel for orchestrator: #{orchestrator.partner}, with order PO: #{po_number}, HW reference number: #{order_to_cancel.reference_number}.").deliver_later
      else
        subj = "EDI order cancellation message for orchestrator: #{orchestrator.partner}, FAILED, no active/cancelable orders with order message PO: #{po_number} found to cancel!"
        msg = "EDI order cancellation message for orchestrator: #{orchestrator.partner}, FAILED, no active/cancelable orders with order message PO: #{po_number} found to cancel!"
        InternalMailer.notify_edi_admin_of_warning(subj, msg).deliver_later
      end
    elsif Order.where('created_at > ?', 12.months.ago).where(edi_po_number: po_number).count.zero? # 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, file_name: file_name)
    elsif (same_po_orders = Order.where('created_at < ?', 4.days.ago).where('created_at > ?', 12.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)
        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: #{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
  end
  BatchProcessResult.new(orders_created: orders_created,
                         orders_in_batch: orders_in_batch)
end

#set_shipping_option(order, order_hash) ⇒ Object



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

def set_shipping_option(order, order_hash)
  # "CarrierInformation": {
  #   "CarrierTransMethodCode": "ZZ",
  #   "CarrierAlphaCode": "Parcel",
  #   "CarrierRouting": "GR"
  # }

  scac_code = order_hash.dig(:Header, :CarrierInformation, :CarrierAlphaCode).presence
  shipping_code = order_hash.dig(:Header, :CarrierInformation, :ServiceLevelCodes, :ServiceLevelCode).presence || order_hash.dig(:Header, :CarrierInformation, :ShipServiceLevelCode).presence # This can be all kinds of different for SPS ServiceLevelCode Parcel for new Canadian Tire DSCO ShipServiceLevelCode 'PRLG'
  shipping_code ||= order_hash.dig(:Header, :CarrierInformation, :CarrierRouting).presence if scac_code # Parcel
  shipping_option_result = match_shipping_code(shipping_code || scac_code || 'DEFAULT')
  order.edi_original_ship_code = shipping_code || scac_code
  order.signature_confirmation = shipping_option_result.signature
  order.shipping_method = shipping_option_result.name
  so = ShippingOption.find_by(name: order.shipping_method)
  # "Dates": [
  #     {
  #         "DateTimeQualifier": "010",
  #         "Date": "2023-01-27"
  #     }
  # ],
  requested_ship_before_date = nil
  requested_ship_on_or_after_date = nil
  requested_arrival_date = nil
  (order_hash.dig(:Header, :Dates) || []).each do |date_hash|
    dtq = date_hash.dig(:DateTimeQualifier)
    if REQUESTED_SHIP_BEFORE_DATE_CODES.include?(dtq)
      requested_ship_before_date = Date.parse(date_hash.dig(:Date)) # Parse "2022-05-22"
    end
    if REQUESTED_SHIP_AFTER_DATE_CODES.include?(dtq)
      requested_ship_on_or_after_date = Date.parse(date_hash.dig(:Date)) # Parse "2022-05-22"
    end
    if REQUESTED_ARRIVAL_DATE_CODES.include?(dtq)
      requested_arrival_date = Date.parse(date_hash.dig(:Date)) # Parse "2022-05-22"
    end
  end
  order.requested_ship_before = requested_ship_before_date
  order.requested_ship_on_or_after = requested_ship_on_or_after_date if requested_ship_on_or_after_date.present?
  order.requested_ship_before ||= (requested_arrival_date - so.days_commitment.floor.days + 1.day) if requested_arrival_date.present? # estimate the last date we can ship this (optimistically)
  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

Returns:

  • (Boolean)


181
182
183
184
185
186
187
188
189
# File 'app/services/edi/mft_gateway/order_message_processor.rb', line 181

def shipping_invalid?(order)
  dq = order.deliveries.quoting.first
  return true unless dq
  return true if dq.shipping_option.is_override? || dq.shipping_option.is_third_party_only?
  return true unless dq.shipping_option.name == order.edi_shipping_option_name
  return true unless dq.signature_confirmation == order.signature_confirmation

  false
end