Class: Edi::Wayfair::ConfirmMessageProcessor

Inherits:
BaseEdiService show all
Defined in:
app/services/edi/wayfair/confirm_message_processor.rb

Constant Summary collapse

CONTAINER_MAP =
{
  carton: 'CTN',
  pallet: 'PLT'
}

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

#acknowledge_order(order, _options = {}) ⇒ Object



14
15
16
17
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 14

def acknowledge_order(order, _options = {})
  m = build_accept_message_from_order(order)
  process(m, :order_acknowledge, order)
end

#auto_cancel_order(order, order_hash, reason_code, _bad_vendor_skus = nil, _bad_merchant_skus = nil) ⇒ Object



24
25
26
27
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 24

def auto_cancel_order(order, order_hash, reason_code, _bad_vendor_skus = nil, _bad_merchant_skus = nil)
  m = build_cancel_message_from_order_hash(order, order_hash, reason_code)
  process(m, :order_acknowledge, order)
end

#back_order(order) ⇒ Object



29
30
31
32
33
34
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 29

def back_order(order)
  return if orchestrator.ignore_back_orders

  m = build_back_order_message_from_order(order)
  process(m, :order_acknowledge, order)
end

#build_accept_message_from_order(order) ⇒ Object

Here we build an accept mutation.



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
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 43

def build_accept_message_from_order(order)
  # mutation accept {
  #   purchaseOrders {
  #     accept(
  #       poNumber: "CS12345678",
  #       shipSpeed: GROUND,
  #       lineItems: [
  #         {
  #           partNumber: "ABC123456",
  #           quantity: 1,
  #           unitPrice: 17.07,
  #           estimatedShipDate: "2020-11-07 15:15:14.000000 -05:00"
  #         }
  #       ]
  #     ) {
  #       id,
  #       handle,
  #       status,
  #       submittedAt,
  #       completedAt,
  #       errors {
  #         key,
  #         message
  #       }
  #     }
  #   }
  # }

  order.deliveries.first
  ship_date = order.get_scheduled_ship_date_time.iso8601
  # shipping_option_result = orchestrator.ship_code_mapper.hw_to_wf(delivery.shipping_option.name, delivery.signature_confirmation, delivery.saturday_delivery)
  # ship_speed = shipping_option_result&.ship_speed
  ship_speed = order.edi_original_ship_code.split(' ').last # just use the original ship speed

  ack_lines = []
  order_lines_hash = JSON.parse(order.edi_original_order_message).with_indifferent_access.dig(:products) || []
  get_order_line_items(order).each_with_index do |li, i|
    ind = nil
    ind = li.edi_line_number - 1 if li.edi_line_number.present?
    ind ||= i
    part_number = order_lines_hash[ind].dig(:partNumber) || li.catalog_item.sku
    ack_lines << "{ partNumber: \\\"#{part_number}\\\", quantity: #{li.quantity}, unitPrice: #{li.discounted_price.round(2)}, estimatedShipDate: \\\"#{ship_date}\\\" }"
  end

  %(
    mutation accept {
      purchaseOrders {
        accept(
          poNumber: \\"#{order.po_number}\\",
          shipSpeed: #{ship_speed},
          lineItems: [
            #{ack_lines.join(', ')}
          ]
        ) {
          id,
          handle,
          status,
          submittedAt,
          completedAt,
          errors {
            key,
            message
          }
        }
      }
    }
  ).squish
end

#build_back_order_message_from_order(order) ⇒ Object

Here we build a backorder mutation (for order backorder).



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
292
293
294
295
296
297
298
299
300
301
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 237

def build_back_order_message_from_order(order)
  # mutation backorder {
  #   purchaseOrders {
  #     backorder(
  #       poNumber: "CS12345678",
  #       shipSpeed: GROUND,
  #       lineItems: [
  #         {
  #           partNumber: "ABC123456",
  #           quantity: 1,
  #           unitPrice: 17.07,
  #           newShipDate: "2020-11-12 15:15:14.000000 -05:00"
  #         }
  #       ]
  #     ) {
  #       id,
  #       handle,
  #       status,
  #       submittedAt,
  #       completedAt,
  #       errors {
  #         key,
  #         message
  #       }
  #     }
  #   }
  # }

  ship_date = order.get_scheduled_ship_date_time.iso8601
  ship_speed = order.edi_original_ship_code.split(' ').last

  ack_lines = []
  order_lines_hash = JSON.parse(order.edi_original_order_message).with_indifferent_access.dig(:products) || []
  get_order_line_items(order).each_with_index do |li, i|
    ind = nil
    ind = li.edi_line_number - 1 if li.edi_line_number.present?
    ind ||= i
    part_number = order_lines_hash[ind].dig(:partNumber) || li.catalog_item.sku
    ack_lines << "{ partNumber: \\\"#{part_number}\\\", quantity: #{li.quantity}, unitPrice: #{li.discounted_price.round(2)}, newShipDate: \\\"#{ship_date}\\\" }"
  end

  %(
    mutation backorder {
      purchaseOrders {
        backorder(
          poNumber: \\"#{order.po_number}\\",
          shipSpeed: #{ship_speed},
          lineItems: [
            #{ack_lines.join(', ')}
          ]
        ) {
          id,
          handle,
          status,
          submittedAt,
          completedAt,
          errors {
            key,
            message
          }
        }
      }
    }
  ).squish
end

#build_cancel_message_from_order(order) ⇒ Object

Here we build a reject mutation (for order rejection after the fact).



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
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 114

def build_cancel_message_from_order(order)
  # mutation reject {
  #   purchaseOrders {
  #     reject(
  #       poNumber: "CS275201571",
  #       lineItems: [
  #         {
  #           partNumber: "TWS6-GRD12PH",
  #           quantity: 1
  #         }
  #       ]
  #     ) {
  #       id,
  #       handle,
  #       status,
  #       submittedAt,
  #       completedAt,
  #       errors {
  #         key,
  #         message
  #       }
  #     }
  #   }
  # }

  ack_lines = []
  order_lines_hash = JSON.parse(order.edi_original_order_message).with_indifferent_access.dig(:products) || []
  get_order_line_items(order).each_with_index do |li, i|
    ind = nil
    ind = li.edi_line_number - 1 if li.edi_line_number.present?
    ind ||= i
    part_number = order_lines_hash[ind].dig(:partNumber) || li.catalog_item.sku
    ack_lines << "{ partNumber: \\\"#{part_number}\\\", quantity: #{li.quantity} }"
  end
  %(
    mutation reject {
      purchaseOrders {
        reject(
          poNumber: \\"#{order.first_po_number}\\",
          lineItems: [
            #{ack_lines.join(', ')}
          ]
        ) {
          id,
          handle,
          status,
          submittedAt,
          completedAt,
          errors {
            key,
            message
          }
        }
      }
    }
  ).squish
end

#build_cancel_message_from_order_hash(_order, order_hash, _reason_code) ⇒ Object

Here we build a reject mutation (for order rejection due to bad SKUs, we use the order hash not order).



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/confirm_message_processor.rb', line 174

def build_cancel_message_from_order_hash(_order, order_hash, _reason_code)
  # mutation reject {
  #   purchaseOrders {
  #     reject(
  #       poNumber: "CS275201571",
  #       lineItems: [
  #         {
  #           partNumber: "TWS6-GRD12PH",
  #           quantity: 1
  #         }
  #       ]
  #     ) {
  #       id,
  #       handle,
  #       status,
  #       submittedAt,
  #       completedAt,
  #       errors {
  #         key,
  #         message
  #       }
  #     }
  #   }
  # }

  #   "products": [
  #     {
  #       "partNumber": "TWS6-GRD10KH",
  #       "quantity": "1",
  #       "price": 539.4,
  #       "event": null
  #     }
  #   ],

  ack_lines = order_hash[:products].map do |line_hash|
    "{ partNumber: \\\"#{line_hash[:partNumber]}\\\", quantity: #{line_hash[:quantity]} }"
  end
  %(
    mutation reject {
      purchaseOrders {
        reject(
          poNumber: \\"#{order_hash[:poNumber]}\\",
          lineItems: [
            #{ack_lines.join(', ')}
          ]
        ) {
          id,
          handle,
          status,
          submittedAt,
          completedAt,
          errors {
            key,
            message
          }
        }
      }
    }
  ).squish
end

#build_confirm_message_from_invoice(invoice) ⇒ Object

mutation shipment {
purchaseOrders {
shipment(
notice: {
poNumber: "CS12345678",
supplierId: 7083,
packageCount: 1,
weight: 5.12,
volume: 4.65,
carrierCode: "FDEG",
shipSpeed: GROUND,
trackingNumber: "9999 9999 9999",
shipDate: "2020-11-04 15:15:14.000000 -05:00",
sourceAddress: {
name: "Wayfair",
streetAddress1: "4 Copley Place",
city: "Boston",
state: "MA",
postalCode: "02120",
country: "USA"
},
destinationAddress: {
name: "John Doe",
streetAddress1: "1 Elm St",
city: "Boston",
state: "MA",
postalCode: "02122",
country: "USA"
},
smallParcelShipments: [
{
package: {
code: {
type: TRACKING_NUMBER,
value: "1111 1111 1111"
},
weight: 5.12
},
items: [
{
partNumber: "ABC123456",
quantity: 1
}
]
}
]
}
) {
id,
handle,
status,
submittedAt,
completedAt,
errors {
key,
message
}
}
}
}



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
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 366

def build_confirm_message_from_invoice(invoice)
  order = invoice.order
  delivery = order.deliveries.first
  # this is an alias to building a shipment message

  # get the carrier_code and ship_speed
  ship_code = order.edi_original_ship_code # try to use Wayfair's original ship_code which can encode as either as "#{carrier_code} #{ship_speed}" or simply "#{ship_speed}"
  if ship_code.split(' ').size > 1 # here we have ship_code encoded by Wayfair with carrier_code and ship_code populated, we encode as "#{carrier_code} #{ship_speed}"
    carrier_code = ship_code.split(' ').first # use the original carrier code
    ship_speed = ship_code.split(' ').last # use the original ship speed
  else # here we have ship_code encoded by Wayfair with only ship_speed
    shipping_option_result = orchestrator.ship_code_mapper.hw_to_wf(delivery.shipping_option.name, delivery.signature_confirmation, delivery.saturday_delivery)
    carrier_code = shipping_option_result&.carrier_code # extract carrier_code from the actual shipping option used
    ship_speed = ship_code # use the original ship speed
  end

  order_hash = JSON.parse(order.edi_original_order_message).with_indifferent_access

  # Here we use the original kit SKUs, not the components, ie we use the goods and parents_only scope on line items. Handle case (ie when a single kit SKU ships in multple shipments) of more shipments than total line items by taking only the largest N shipments (by billable weight), where N is the smaller of the number of parents_only total line items vs the number of top level shipments.

  # So if we have unsual case of 3 kit items that ship in 6 packages, only report the largest 3 packages. If we have 20 items that ship in 2 packages, take all 2 packages

  n = [delivery.line_items.goods.parents_only.sum(:quantity), delivery.shipments.completed.top_level.count].min
  shp_lines = delivery.shipments.completed.top_level.sort_by { |s| s.to_package.billable_weight }.first(n).map do |s|
    "{
        package: {
          code: {
            type: TRACKING_NUMBER,
            value: \\\"#{s.tracking_number}\\\"
          },
          weight: #{s.weight.round(2)}
        },
        items: [
          #{s.shipment_content_grouped_content_key.map { |key_hash, qty| "{ partNumber: \\\"#{key_hash[:sku]}\\\", quantity: #{qty} }" }.join(', ')}
        ]
      }".squish
  end

  %(
    mutation shipment {
      purchaseOrders {
        shipment(
          notice: {
            poNumber: \\"#{order.po_number(limit: 1)}\\",
            supplierId: \\"#{orchestrator.warehouse_code}\\",
            packageCount: #{delivery.shipments.completed.top_level.count},
            weight: #{delivery.shipments.completed.top_level.sum(&:weight).round(2)},
            volume: #{delivery.shipments.completed.top_level.sum(&:volume_in_cubic_feet).round(2)},
            carrierCode: \\"#{carrier_code}\\",
            shipSpeed: #{ship_speed},
            trackingNumber: \\"#{delivery.master_tracking_number}\\",
            shipDate: \\"#{Time.parse('16:00:00').utc.iso8601}\\",
            sourceAddress: {
              name: \\"#{order_hash.dig(:warehouse, :address, :name) || order.delivery.origin_address.person_name_override || delivery.origin_address.company_name_override}\\",
              streetAddress1: \\"#{order_hash.dig(:warehouse, :address, :address1) || delivery.origin_address.street1}\\",
              streetAddress2: \\"#{order_hash.dig(:warehouse, :address, :address2) || delivery.origin_address.street2}\\",
              city: \\"#{order_hash.dig(:warehouse, :address, :city) || delivery.origin_address.city}\\",
              state: \\"#{order_hash.dig(:warehouse, :address, :state) || delivery.origin_address.state_code}\\",
              postalCode: \\"#{order_hash.dig(:warehouse, :address, :postalCode) || delivery.origin_address.zip}\\",
              country: \\"#{order_hash.dig(:warehouse, :address, :country) || delivery.origin_address.country_iso3}\\"
            },
            destinationAddress: {
              name: \\"#{order_hash.dig(:shipTo, :name) || delivery.destination_address.person_name_override || delivery.destination_address.company_name_override}\\",
              streetAddress1: \\"#{order_hash.dig(:shipTo, :address1) || delivery.destination_address.street1}\\",
              streetAddress2: \\"#{order_hash.dig(:shipTo, :address2) || delivery.destination_address.street2}\\",
              city: \\"#{order_hash.dig(:shipTo, :city) || delivery.destination_address.city}\\",
              state: \\"#{order_hash.dig(:shipTo, :state) || delivery.destination_address.state_code}\\",
              postalCode: \\"#{order_hash.dig(:shipTo, :postalCode) || delivery.destination_address.zip}\\",
              country: \\"#{order_hash.dig(:shipTo, :country) || delivery.destination_address.country_iso3}\\"
            },
            smallParcelShipments: [
              #{shp_lines.join(', ')}
            ]
          }
        ) {
          id,
          handle,
          status,
          submittedAt,
          completedAt,
          errors {
            key,
            message
          }
        }
      }
    }
  ).squish
end

#cancel_order(order) ⇒ Object



19
20
21
22
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 19

def cancel_order(order)
  m = build_cancel_message_from_order(order)
  process(m, :order_acknowledge, order)
end

#confirm_invoice(invoice) ⇒ Object



36
37
38
39
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 36

def confirm_invoice(invoice)
  m = build_confirm_message_from_invoice(invoice)
  process(m, :order_confirm, invoice.order)
end

#get_order_line_items(order) ⇒ Object



10
11
12
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 10

def get_order_line_items(order)
  order.line_items.where.not(edi_line_number: nil).order(:edi_line_number).goods
end

#process(confirm_message, category, order = nil) ⇒ Object

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



457
458
459
460
461
462
463
464
465
466
467
468
# File 'app/services/edi/wayfair/confirm_message_processor.rb', line 457

def process(confirm_message, category, order = nil)
  edi_log = nil
  EdiCommunicationLog.transaction do
    edi_log = EdiCommunicationLog.create! partner: orchestrator.partner,
                                          category: category,
                                          data: confirm_message,
                                          data_type: 'text',
                                          transmit_datetime: Time.current
  end
  edi_log.edi_documents.create!(order: order) if order.present?
  edi_log
end