Class: Edi::Walmart::ShippingLabelPurchaser

Inherits:
MarketplaceLabelPurchaser show all
Defined in:
app/services/edi/walmart/shipping_label_purchaser.rb

Overview

Service for purchasing shipping labels via Walmart's "Ship with Walmart" (SWW) API

This service handles the full label lifecycle:

  • Purchase a label using a rate from Ship with Walmart
  • Download the label PDF
  • Attach the label to a shipment
  • Populate tracking information
  • Trigger ship confirmation to Walmart

Examples:

purchaser = Edi::Walmart::ShippingLabelPurchaser.new(shipment)
result = purchaser.purchase_label(rate)
if result.success
  puts "Tracking: #{result.tracking_number}"
end

Instance Attribute Summary collapse

Attributes inherited from MarketplaceLabelPurchaser

#delivery, #logger, #order, #shipment

Instance Method Summary collapse

Methods inherited from MarketplaceLabelPurchaser

#attach_label_pdf, #failure_result, for_delivery, for_order, for_shipment, #map_carrier_name, marketplace_carrier?, marketplace_name, #success_result, supports_marketplace_labels?

Constructor Details

#initialize(shipment, options = {}) ⇒ ShippingLabelPurchaser

Returns a new instance of ShippingLabelPurchaser.



23
24
25
26
# File 'app/services/edi/walmart/shipping_label_purchaser.rb', line 23

def initialize(shipment, options = {})
  super
  @orchestrator = Edi::Walmart::Orchestrator.new(order.edi_orchestrator_partner.to_sym)
end

Instance Attribute Details

#orchestratorObject (readonly)

Returns the value of attribute orchestrator.



21
22
23
# File 'app/services/edi/walmart/shipping_label_purchaser.rb', line 21

def orchestrator
  @orchestrator
end

Instance Method Details

#marketplace_nameString

Returns:

  • (String)


29
30
31
# File 'app/services/edi/walmart/shipping_label_purchaser.rb', line 29

def marketplace_name
  'Walmart'
end

#move_early_label_to_shipmentUpload?

Move early label PDF from order uploads to shipment uploads

Returns:



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'app/services/edi/walmart/shipping_label_purchaser.rb', line 457

def move_early_label_to_shipment
  early_upload = order.early_label_upload
  return nil unless early_upload

  logger.info("[SWW LabelPurchaser] Moving early label upload #{early_upload.id} from order to shipment")

  # Change the upload's resource and category
  early_upload.update!(
    resource_type: 'Shipment',
    resource_id: shipment.id,
    category: 'ship_label_pdf'
  )

  early_upload
rescue StandardError => e
  logger.warn("[SWW LabelPurchaser] Failed to move early label upload: #{e.message}")
  # Try to download a fresh copy if move fails
  download_and_attach_label(order.early_label_carrier, order.early_label_tracking_number, order.early_label_sww_label_id)
end

#purchase_label(rate) ⇒ PurchaseResult

Purchase a shipping label using a SWW rate

Parameters:

  • rate (Hash)

    The rate hash from Shipping::WalmartSeller.find_rates

Returns:



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
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
351
352
353
354
355
356
357
358
359
360
# File 'app/services/edi/walmart/shipping_label_purchaser.rb', line 37

def purchase_label(rate)
  logger.info("[SWW LabelPurchaser] Purchasing label for shipment #{shipment.id}, PO: #{order.edi_po_number}")
  logger.info("[SWW LabelPurchaser] Rate structure: #{rate.inspect}")

  # Check if order has an early-purchased label that we can reuse
  # Early labels are purchased when order reaches awaiting_deliveries (before warehouse processing)
  if order.has_early_purchased_label?
    return use_early_purchased_label(rate)
  end

  # Validate rate has required fields
  return failure_result("Rate missing carrier_id: #{rate.inspect}") unless rate[:carrier_id].present?

  return failure_result("Rate missing service_type: #{rate.inspect}") unless rate[:service_type].present?

  # Build box items for matching
  box_items = build_box_items

  # Check for existing labels first (per Walmart API error LS-4090)
  # "Looks like you have already generated a label for the requested items and quantity"
  sww_client = Edi::Walmart::ShipWithWalmart.new(orchestrator)
  existing_labels_result = sww_client.get_labels_by_purchase_order(order.edi_po_number)

  if existing_labels_result.success
    logger.info("[SWW LabelPurchaser] get_labels_by_purchase_order succeeded, found #{existing_labels_result.labels&.length || 0} label(s)")
  else
    logger.warn("[SWW LabelPurchaser] get_labels_by_purchase_order failed: #{existing_labels_result.error}")
  end

  if existing_labels_result.success && existing_labels_result.labels.any?
    logger.info("[SWW LabelPurchaser] Found #{existing_labels_result.labels.length} existing label(s) for PO #{order.edi_po_number}")

    # Filter out any labels that match a voided early label tracking number
    # This prevents reusing labels that were supposed to be discarded (e.g., after packing mismatch)
    available_labels = existing_labels_result.labels
    if order.early_label_voided_at.present? && order.early_label_tracking_number.present?
      voided_tracking = order.early_label_tracking_number
      available_labels = available_labels.reject do |label|
        tracking = label[:trackingNumber] || label[:trackingNo]
        if tracking == voided_tracking
          logger.info("[SWW LabelPurchaser] Skipping voided early label: tracking=#{tracking}")
          true
        else
          false
        end
      end
      logger.info("[SWW LabelPurchaser] After filtering voided labels: #{available_labels.length} label(s) remaining")
    end

    # Try to find a matching label by box items (SKU and quantity) AND service type
    # Only reuse a label if it matches both the items and the selected shipping service
    matching_label = find_matching_label(available_labels, box_items, rate[:service_type])

    if matching_label
      logger.info("[SWW LabelPurchaser] Found matching label with same items and service type: carrier=#{matching_label[:carrier]}, tracking=#{matching_label[:trackingNumber]}, service=#{matching_label[:carrierServiceType] || matching_label[:serviceType]}")
      label_to_use = matching_label
    else
      # No matching label found - either different items or different service type
      # Create a new label instead of reusing the wrong one
      logger.info("[SWW LabelPurchaser] No existing label matches both box items and service type (#{rate[:service_type]}), will create new label")
      label_to_use = nil
    end

    if label_to_use
      carrier = label_to_use[:carrier] || label_to_use[:carrierName]
      tracking_number = label_to_use[:trackingNumber] || label_to_use[:trackingNo]
      # Note: get_labels_by_purchase_order does NOT return labelId (Walmart API limitation)
      # labelId is only available from create_label response, so preserve existing if present
      label_id = label_to_use[:labelId] || label_to_use[:label_id] || shipment.sww_label_id
      service_type = label_to_use[:carrierServiceType] || label_to_use[:serviceType] || rate[:service_type]

      # Download and attach the existing label PDF
      label_upload = download_and_attach_label(carrier, tracking_number, label_id)

      # Update shipment with tracking info (preserve existing label_id if not provided)
      update_shipment_tracking(tracking_number, carrier, label_id)

      # Store the SWW metadata for potential voiding later
      (label_id, carrier, service_type)

      return success_result(
        label_id: label_id,
        tracking_number: tracking_number,
        carrier: carrier,
        service_type: service_type,
        label_upload: label_upload
      )
    end
    # If no matching label, fall through to create a new one
  end

  # No existing labels found, create a new one
  logger.info('[SWW LabelPurchaser] No existing labels found, creating new label')

  # Build the shipping options
  shipper = build_walmart_shipper(rate)

  # Add box items from delivery line items to the rate
  rate_with_items = rate.merge(box_items: box_items)
  logger.info("[SWW LabelPurchaser] Rate with items: carrier_id=#{rate_with_items[:carrier_id]}, service_type=#{rate_with_items[:service_type]}, box_items=#{rate_with_items[:box_items]&.length || 0} items")
  label_result = shipper.create_label(rate_with_items)

  unless label_result[:success]
    # If we get a 409 error (LS-4090), it means a label already exists
    # Try to retrieve it instead of failing
    error_msg = label_result[:error].to_s
    return failure_result(label_result[:error]) unless error_msg.include?('LS-4090') || error_msg.include?('409')

    logger.info('[SWW LabelPurchaser] Got 409 error, attempting to retrieve existing labels')
    existing_labels_result = sww_client.get_labels_by_purchase_order(order.edi_po_number)

    if existing_labels_result.success
      logger.info("[SWW LabelPurchaser] get_labels_by_purchase_order after 409: found #{existing_labels_result.labels&.length || 0} label(s)")
      if existing_labels_result.labels.any?
        existing_labels_result.labels.each_with_index do |label, idx|
          logger.info("[SWW LabelPurchaser] Label #{idx + 1}: carrier=#{label[:carrier] || label[:carrierName]}, tracking=#{label[:trackingNumber] || label[:trackingNo]}, service=#{label[:carrierServiceType] || label[:serviceType]}, boxItems=#{label[:boxItems] || label[:box_items] || []}")
        end
      end
    else
      logger.warn("[SWW LabelPurchaser] get_labels_by_purchase_order after 409 failed: #{existing_labels_result.error}")
    end

    if existing_labels_result.success && existing_labels_result.labels.any?
      logger.info("[SWW LabelPurchaser] Found #{existing_labels_result.labels.length} existing label(s) after 409 error")

      # Filter out voided early labels (same as above)
      available_labels = existing_labels_result.labels
      if order.early_label_voided_at.present? && order.early_label_tracking_number.present?
        voided_tracking = order.early_label_tracking_number
        available_labels = available_labels.reject do |label|
          tracking = label[:trackingNumber] || label[:trackingNo]
          tracking == voided_tracking
        end
        logger.info("[SWW LabelPurchaser] After filtering voided labels (409 path): #{available_labels.length} label(s) remaining")
      end

      # Try to find a matching label by box items AND service type
      # Only reuse if it matches both the items and the selected shipping service
      matching_label = find_matching_label(available_labels, box_items, rate[:service_type])

      if matching_label
        logger.info("[SWW LabelPurchaser] Found matching label with same items and service type: carrier=#{matching_label[:carrier]}, tracking=#{matching_label[:trackingNumber]}, service=#{matching_label[:carrierServiceType] || matching_label[:serviceType]}")

        carrier = matching_label[:carrier] || matching_label[:carrierName]
        tracking_number = matching_label[:trackingNumber] || matching_label[:trackingNo]
        label_id = matching_label[:labelId] || matching_label[:label_id]
        service_type = matching_label[:carrierServiceType] || matching_label[:serviceType] || rate[:service_type]

        # Download and attach the existing label PDF
        label_upload = download_and_attach_label(carrier, tracking_number, label_id)

        # Update shipment with tracking info
        update_shipment_tracking(tracking_number, carrier, label_id)

        # Store the SWW metadata for potential voiding later
        (label_id, carrier, service_type)

        return success_result(
          label_id: label_id,
          tracking_number: tracking_number,
          carrier: carrier,
          service_type: service_type,
          label_upload: label_upload
        )
      else
        # No matching label found - either different items or different service type
        # Try to void the non-matching label(s) and create a new one
        logger.warn("[SWW LabelPurchaser] Existing label found but doesn't match service type (#{rate[:service_type]}). Attempting to void and create new label.")

        # Void all existing labels for this PO that don't match
        voided_any = false
        existing_labels_result.labels.each do |label|
          label_carrier = label[:carrier] || label[:carrierName]
          label_tracking = label[:trackingNumber] || label[:trackingNo]
          next unless label_carrier.present? && label_tracking.present?

          logger.info("[SWW LabelPurchaser] Voiding non-matching label: carrier=#{label_carrier}, tracking=#{label_tracking}")
          void_result = sww_client.discard_label(label_carrier, label_tracking)

          if void_result.success
            voided_any = true
            logger.info("[SWW LabelPurchaser] Successfully voided label: #{label_tracking}")
          else
            logger.warn("[SWW LabelPurchaser] Failed to void label #{label_tracking}: #{void_result.error}")
          end
        end

        unless voided_any
          return failure_result("A label already exists for this order with a different shipping service (#{existing_labels_result.labels.first[:carrierServiceType] || existing_labels_result.labels.first[:serviceType]}). Could not void it automatically. Please void the existing label manually or select the same shipping service.")
        end

        # Wait a moment for Walmart to process the void, then retry creating the label
        logger.info('[SWW LabelPurchaser] Retrying label creation after voiding non-matching labels')
        sleep(1) # Brief pause to allow Walmart to process the void
        label_result = shipper.create_label(rate_with_items)

        return failure_result("Voided existing label but failed to create new one: #{label_result[:error]}") unless label_result[:success]

        # Successfully created new label after voiding old one
        label_id = label_result[:label_id]
        tracking_number = label_result[:tracking_number]
        carrier = label_result[:carrier]
        service_type = label_result[:service_type]

        # Download and attach the label PDF
        label_upload = download_and_attach_label(carrier, tracking_number, label_id)

        # Update shipment with tracking info
        update_shipment_tracking(tracking_number, carrier, label_id)

        # Store the SWW metadata for potential voiding later
        (label_id, carrier, service_type)

        return success_result(
          label_id: label_id,
          tracking_number: tracking_number,
          carrier: carrier,
          service_type: service_type,
          label_upload: label_upload
        )

        # Still failed after voiding - return error

        # Couldn't void the existing label(s)

      end
    else
      # Couldn't retrieve existing labels after 409 error
      # Walmart says label exists but GET returns nothing - this is likely a false positive 409
      # The label was probably never actually created
      # Try creating the label again immediately - treat 409 as transient/false positive
      logger.warn('[SWW LabelPurchaser] Got 409 but get_labels_by_purchase_order returned no labels. Treating as false positive and retrying label creation immediately...')

      label_result = shipper.create_label(rate_with_items)

      if label_result[:success]
        # Successfully created label on retry
        logger.info('[SWW LabelPurchaser] Successfully created label on retry after 409 false positive')
        label_id = label_result[:label_id]
        tracking_number = label_result[:tracking_number]
        carrier = label_result[:carrier]
        service_type = label_result[:service_type]

        label_upload = download_and_attach_label(carrier, tracking_number, label_id)
        update_shipment_tracking(tracking_number, carrier, label_id)
        (label_id, carrier, service_type)

        return success_result(
          label_id: label_id,
          tracking_number: tracking_number,
          carrier: carrier,
          service_type: service_type,
          label_upload: label_upload
        )
      else
        # Still failed on retry - check for labels one more time in case retry actually created it
        error_msg = label_result[:error].to_s
        return failure_result("Failed to create label after 409 retry: #{error_msg}") unless error_msg.include?('LS-4090') || error_msg.include?('409')

        logger.warn('[SWW LabelPurchaser] Retry also returned 409. Checking for labels one more time...')
        final_check = sww_client.get_labels_by_purchase_order(order.edi_po_number)

        unless final_check.success && final_check.labels.any?
          return failure_result("Walmart returned 409 Conflict (label already exists) but the label cannot be retrieved via API. This appears to be a Walmart API synchronization issue. The label may exist in Walmart's system but is not yet queryable. Please contact Walmart support to check for existing labels for PO #{order.edi_po_number}, or try again in a few minutes.")
        end

        logger.info("[SWW LabelPurchaser] Found #{final_check.labels.length} label(s) after retry 409")
        matching_label = find_matching_label(final_check.labels, box_items, rate[:service_type])

        unless matching_label
          return failure_result("Walmart returned 409 Conflict and labels exist but none match the requested service type (#{rate[:service_type]}). Please void existing labels manually in Walmart's system or select a different shipping method.")
        end

        carrier = matching_label[:carrier] || matching_label[:carrierName]
        tracking_number = matching_label[:trackingNumber] || matching_label[:trackingNo]
        # Note: get_labels_by_purchase_order does NOT return labelId, preserve existing if present
        label_id = matching_label[:labelId] || matching_label[:label_id] || shipment.sww_label_id
        service_type = matching_label[:carrierServiceType] || matching_label[:serviceType] || rate[:service_type]

        label_upload = download_and_attach_label(carrier, tracking_number, label_id)
        update_shipment_tracking(tracking_number, carrier, label_id)
        (label_id, carrier, service_type)

        return success_result(
          label_id: label_id,
          tracking_number: tracking_number,
          carrier: carrier,
          service_type: service_type,
          label_upload: label_upload
        )

      end
    end

    # Not a 409 error, return failure

  end

  label_id = label_result[:label_id]
  tracking_number = label_result[:tracking_number]
  carrier = label_result[:carrier]
  service_type = label_result[:service_type]

  # Download and attach the label PDF using carrier + tracking (per Walmart API)
  label_upload = download_and_attach_label(carrier, tracking_number, label_id)

  # Update shipment with tracking info
  update_shipment_tracking(tracking_number, carrier, label_id)

  # Store the SWW metadata for potential voiding later (uses carrier + tracking)
  (label_id, carrier, service_type)

  success_result(
    label_id: label_id,
    tracking_number: tracking_number,
    carrier: carrier,
    service_type: service_type,
    label_upload: label_upload
  )
rescue StandardError => e
  logger.error("[SWW LabelPurchaser] Error: #{e.message}")
  logger.error(e.backtrace.first(5).join("\n"))
  failure_result(e.message)
end

#use_early_purchased_label(rate) ⇒ PurchaseResult

Use an early-purchased label instead of purchasing a new one
Moves the label from the order to the shipment and updates tracking info

Parameters:

  • rate (Hash)

    The rate hash (used for logging/validation)

Returns:



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
# File 'app/services/edi/walmart/shipping_label_purchaser.rb', line 411

def use_early_purchased_label(rate)
  logger.info("[SWW LabelPurchaser] Using early-purchased label for shipment #{shipment.id}")
  logger.info("[SWW LabelPurchaser] Early label: tracking=#{order.early_label_tracking_number}, carrier=#{order.early_label_carrier}")

  tracking_number = order.early_label_tracking_number
  carrier = order.early_label_carrier
  label_id = order.early_label_sww_label_id
  service_type = order.early_label_service_type

  # Move the early label PDF from order to shipment
  label_upload = move_early_label_to_shipment

  # Update shipment with tracking info
  update_shipment_tracking(tracking_number, carrier, label_id)

  # Store the SWW metadata for potential voiding later
  (label_id, carrier, service_type)

  # Clear the early label flag on the order (it's now been used/transferred to shipment)
  # Keep metadata for audit trail
  order.update!(
    purchase_label_early: false
  )

  logger.info("[SWW LabelPurchaser] Successfully reused early-purchased label for shipment #{shipment.id}")

  success_result(
    label_id: label_id,
    tracking_number: tracking_number,
    carrier: carrier,
    service_type: service_type,
    label_upload: label_upload
  )
rescue StandardError => e
  logger.error("[SWW LabelPurchaser] Error using early-purchased label: #{e.message}")
  logger.error(e.backtrace.first(5).join("\n"))
  # Fall back to normal label purchase if early label reuse fails
  logger.info("[SWW LabelPurchaser] Falling back to normal label purchase")
  # Clear early label flag to prevent retry loop
  order.update(purchase_label_early: false)
  failure_result("Failed to use early-purchased label: #{e.message}. Please try purchasing a new label.")
end

#validate_order!Object (protected)

Raises:

  • (ArgumentError)


479
480
481
482
483
484
485
486
487
# File 'app/services/edi/walmart/shipping_label_purchaser.rb', line 479

def validate_order!
  super

  raise ArgumentError, 'Shipment is not for a Walmart marketplace order' unless order.edi_orchestrator_partner&.start_with?('walmart_seller')

  return if order.edi_po_number.present?

  raise ArgumentError, 'Order does not have a Walmart PO number'
end

#void_label(fallback_tracking_number: nil) ⇒ Hash

Void/discard a previously purchased label
Per Walmart API, labels are voided using carrier + tracking number

Parameters:

  • fallback_tracking_number (String, nil) (defaults to: nil)

    Tracking number to use if not on shipment
    (e.g., from delivery.master_tracking_number when tracking wasn't transferred to shipment)

Returns:

  • (Hash)

    Result with :success and :error keys



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
# File 'app/services/edi/walmart/shipping_label_purchaser.rb', line 368

def void_label(fallback_tracking_number: nil)
  # Try shipment tracking first, then fall back to delivery's master tracking number
  tracking_number = shipment.tracking_number.presence || fallback_tracking_number
  # Get carrier from SWW metadata (stored as "FedEx") or fallback to shipment carrier
  # The discard API expects the carrier name as returned by create_label (e.g., "FedEx")
  carrier = shipment.sww_carrier || shipment.carrier

  unless tracking_number.present?
    logger.warn("[SWW LabelPurchaser] No tracking number on shipment #{shipment.id} or fallback — clearing SWW metadata only")
    shipment.update(sww_label_id: nil, sww_metadata: nil)
    return { success: true, error: nil }
  end

  return { success: false, error: 'No carrier found on shipment' } unless carrier.present?

  logger.info("[SWW LabelPurchaser] Voiding label for shipment #{shipment.id}, carrier: #{carrier}, tracking: #{tracking_number}")

  sww_client = Edi::Walmart::ShipWithWalmart.new(orchestrator)
  # discard_label will normalize the carrier name internally (e.g., "FedEx" -> "FEDEX")
  result = sww_client.discard_label(carrier, tracking_number)

  if result.success
    # Clear the tracking info - state machine will handle category renaming
    shipment.update(
      tracking_number: nil,
      carrier: nil,
      sww_label_id: nil,
      sww_metadata: nil
    )
    { success: true, error: nil }
  else
    { success: false, error: result.error }
  end
rescue StandardError => e
  logger.error("[SWW LabelPurchaser] Void error: #{e.message}")
  { success: false, error: e.message }
end