Class: Edi::Walmart::PriceMessageProcessor

Inherits:
BaseEdiService show all
Defined in:
app/services/edi/walmart/price_message_processor.rb

Overview

Service object: price message processor.

Constant Summary collapse

WALMART_MARKUP_FROM_AMZ =

Walmart markup from amz.

0.05
WALMART_TO_AMAZON_CATALOG =

Walmart to amazon catalog.

{
  CatalogConstants::WALMART_SELLER_USA => CatalogConstants::AMAZON_SC_US_CATALOG_ID,
  CatalogConstants::WALMART_SELLER_CANADA => CatalogConstants::AMAZON_SC_CA_CATALOG_ID
}.freeze

Constants included from AddressAbbreviator

AddressAbbreviator::MAX_LENGTH

Instance Attribute Summary

Attributes inherited from BaseEdiService

#orchestrator

Attributes inherited from BaseService

#options

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, #tagged_logger

Constructor Details

This class inherits a constructor from Edi::BaseEdiService

Instance Method Details

#append_catalog_item(messages, ci) ⇒ Object



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

def append_catalog_item(messages, ci)
  # See API reference: https://developer.walmart.com/us-marketplace/reference/pricebulkuploads-1
  # And API Guide: https://developer.walmart.com/global-marketplace/docs/price-and-promotional-price-management-api-overview-new-1

  begin
    return if ci.reported_vendor_sku.blank?

    wm_price = walmart_price_for(ci)

    # NOTE: Must convert BigDecimal to Float for JSON serialization.
    # BigDecimal.to_json produces strings like "163.32" instead of numbers 163.32
    # which causes Walmart API to reject the feed with DATA_ERROR on price/msrp fields.
    message = {
      'Promo&Discount': {
        sku: ci.reported_vendor_sku,
        price: wm_price.to_f,
        msrp: ci.msrp.to_f
      }
    }
    messages << message
  rescue StandardError => e
    logger.error "Error processing catalog item #{ci.id} for partner #{orchestrator.partner}: #{e.message}"
    ErrorReporting.error(e, catalog_item_id: ci.id, partner_id: orchestrator.partner.id)
  end
  messages
end

#append_catalog_items(catalog_items) ⇒ Object



120
121
122
123
124
125
126
127
128
129
# File 'app/services/edi/walmart/price_message_processor.rb', line 120

def append_catalog_items(catalog_items)
  messages = []
  catalog_items.find_each do |ci|
    ErrorReporting.scoped(catalog_item_id: ci.id) do
      logger.info "Processing catalog item #{ci.id} for partner #{orchestrator.partner}"
      append_catalog_item(messages, ci)
    end
  end
  messages
end

#build_json(catalog_items: nil, states: nil) ⇒ Object



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

def build_json(catalog_items: nil, states: nil)
  # see: https://github.com/amzn/selling-partner-api-models/blob/main/schemas/feeds/listings-feed-schema-v2.json
  catalog_items ||= load_catalog_items(states:)
  logger.info "#{catalog_items.size} items in price feed payload"

  # https://developer.walmart.com/us-marketplace/reference/priceandpromotionbulkuploads
  #
  # {
  #   "MPItemFeedHeader":{
  #     "businessUnit":"WALMART_US",
  #     "locale":"en",
  #     "version":"2.0.20240126-12_25_52-api"
  #   },
  #   "MPItem":[
  #     {
  #       "Promo&Discount":{
  #         "sku":"Qq9CG25SZjJJnjE",
  #         "price":96.5,
  #         "msrp":15,
  #         "promoid":"0a4aba2c-c62f-4be2-9738-cb62d2ccd4b2",
  #         "promotionInformation":{
  #           "promotionSettingAction":"Create",
  #           "promotionPlacement":"MAP Cart",
  #           "promotionType":"Clearance",
  #           "promotionPrice":90.5,
  #           "promotionPriceStartDateTime":"2024-05-03T07:00:46Z",
  #           "promotionPriceEndDateTime":"2024-10-19T20:52:46Z"
  #         }
  #       }
  #     },
  #     ...
  #   ]
  # }

  mp_items = append_catalog_items(catalog_items)

  # Validate that we have items to send - Walmart rejects feeds with empty MPItem arrays
  if mp_items.empty?
    logger.warn "[Walmart PriceProcessor] No items to include in price feed after filtering. Catalog items loaded: #{catalog_items.size}"
    raise "Cannot create price feed: All catalog items were filtered out (missing reported_vendor_sku or other issues). Loaded #{catalog_items.size} items but 0 items in final feed."
  end

  logger.info "[Walmart PriceProcessor] Building price feed with #{mp_items.size} items"

  feed_hash = {
    MPItemFeedHeader: {
      businessUnit: orchestrator.business_unit,
      locale: orchestrator.default_locale,
      version: '2.0.20240126-12_25_52-api'
    },
    MPItem: mp_items
  }
  feed_hash.to_json
end

#load_catalog_items(states: nil, use_delta_since_last_message: false) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'app/services/edi/walmart/price_message_processor.rb', line 55

def load_catalog_items(states: nil, use_delta_since_last_message: false)
  states ||= %w[active require_vendor_update pending_vendor_update pending_discontinue]
  catalog_items = orchestrator.customer.catalog
                              .catalog_items
                              .for_edi_feeds_by_states(states)
                              .with_item.eager_load(:store_item, :item)
  catalog_items = catalog_items.edi_delta_feeds_for_partner_inventory_advice(orchestrator.partner) if use_delta_since_last_message
  catalog_items.order(StoreItem[:qty_available])
end

#process(catalog_items: nil, states: nil, use_delta_since_last_message: false) ⇒ Object



15
16
17
18
19
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
49
50
51
52
53
# File 'app/services/edi/walmart/price_message_processor.rb', line 15

def process(catalog_items: nil, states: nil, use_delta_since_last_message: false)
  # see: https://developer.walmart.com/us-marketplace/docs/inventory-api-overview
  # see: https://developer.walmart.com/us-marketplace/reference/
  # see: https://www.postman.com/walmart-developer-portal/us-collection/request/j6u6dtg/bulk-item-inventory-update?tab=configurations
  logger.info "Creating price feed for partner #{orchestrator.partner}"
  catalog_items ||= load_catalog_items(states:, use_delta_since_last_message:)
  return :empty_set if catalog_items.blank?

  ecl = nil
  EdiCommunicationLog.transaction do
    data_json = build_json(catalog_items:, states:)

    # Validate the feed has items before creating ECL
    # Parse the JSON to check MPItem array is not empty
    feed_data = JSON.parse(data_json).with_indifferent_access
    mp_items_count = feed_data.dig(:MPItem)&.size || 0

    if mp_items_count.zero?
      logger.error "[Walmart PriceProcessor] Cannot create price feed: MPItem array is empty after processing #{catalog_items.size} catalog items"
      raise "Cannot create price feed: All catalog items were filtered out (missing reported_vendor_sku or other issues). Loaded #{catalog_items.size} items but 0 items in final feed."
    end

    logger.info "[Walmart PriceProcessor] Created price feed with #{mp_items_count} items"

    ecl = EdiCommunicationLog.create_outbound_file_from_data(
      data: data_json,
      data_type: 'json',
      file_extension: 'json',
      partner: orchestrator.partner,
      category: 'price_advice',
      resources: catalog_items,
      file_info: {
        items_count: mp_items_count,
        catalog_items_loaded: catalog_items.size
      }
    )
  end
  ecl
end

#walmart_price_for(ci) ⇒ Object

Price the Walmart item as Amazon Seller price + 5% markup so Amazon wins the Buy Box.
Each Walmart catalog maps to its same-country Amazon Seller catalog (US->US, CA->CA).
Falls back to the Walmart catalog item's own amount when no Amazon match exists.



161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'app/services/edi/walmart/price_message_processor.rb', line 161

def walmart_price_for(ci)
  amz_catalog_id = WALMART_TO_AMAZON_CATALOG[ci.catalog_id]
  if amz_catalog_id
    amz_ci = CatalogItem.where(catalog_id: amz_catalog_id).by_skus(ci.sku).first
    amz_price = amz_ci&.amount
  end

  if amz_price
    ((1.0 + WALMART_MARKUP_FROM_AMZ) * amz_price).round(2)
  else
    logger.warn "[Walmart PriceProcessor] No Amazon match for catalog item #{ci.id} (SKU #{ci.sku}), falling back to ci.amount"
    ci.amount
  end
end