Class: Edi::MiraklSeller::OrderMessageProcessor
- Inherits:
-
BaseEdiService
- Object
- BaseService
- BaseEdiService
- Edi::MiraklSeller::OrderMessageProcessor
- Defined in:
- app/services/edi/mirakl_seller/order_message_processor.rb
Overview
Service object: order message processor.
Defined Under Namespace
Classes: BatchProcessResult, LineCreationResult, Result
Constant Summary collapse
- LM_FR_CID =
Lm fr cid.
21_631_999- LM_ES_CID =
Lm es cid.
22_444_117- LM_PT_CID =
Lm pt cid.
22_444_128- LM_IT_CID =
Lm it cid.
22_473_614
Constants included from AddressAbbreviator
AddressAbbreviator::MAX_LENGTH
Instance Attribute Summary
Attributes inherited from BaseEdiService
Attributes inherited from BaseService
Instance Method Summary collapse
- #adjust_shipping_cost(order, order_hash) ⇒ Object
- #apply_payment(order, order_hash) ⇒ Object
- #create_line_items(order, order_hash) ⇒ Object
- #create_shipping_address(order_hash) ⇒ Object
- #create_sold_to_billing_address(order_hash) ⇒ Object
- #customer(segment = nil) ⇒ Object
- #get_customer(order_hash) ⇒ Object
-
#process(edi_logs = nil, edi_transaction_id: nil) ⇒ Object
Picks up the edi communication log in the queue ready to process, generate acknowledgements.
-
#process_confirmed_order(order_hash = nil) ⇒ Object
Process a single order.
-
#process_orders(orders_data, edi_transaction_id: nil, edi_log_id: nil) ⇒ Object
Iterates through the batch order data.
-
#process_unconfirmed_order(order_hash = nil) ⇒ Object
Process a single order.
- #set_shipping_option(order, order_hash) ⇒ Object
- #shipping_invalid?(order) ⇒ Boolean
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
#adjust_shipping_cost(order, order_hash) ⇒ Object
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 240 def adjust_shipping_cost(order, order_hash) return if order.line_items.shipping_only.blank? # If we are not pulling the shipping then there is nothing to adjust # first calculate the adjustment order.reload order_sc = order.shipping_cost # This can be nil? marketplace_sc_with_vat = order_hash[:shipping_price] tax_rate = order.customer.catalog.tax_rate + 1 # We use the first line item to get the shipping tax rate marketplace_sc = marketplace_sc_with_vat / tax_rate adjustment = marketplace_sc - order_sc # add the price match coupon coupon = Coupon.find_by(code: 'EDI_SHIPPING_ADJ') discount = Discount.new(itemizable: order, coupon_id: coupon.id, effective_date: Date.current) shipping_li = order.line_items.shipping_only.first discount.line_discounts.build(coupon_id: coupon.id, amount: adjustment, line_item_id: shipping_li.id) if discount.line_discounts.any? discount.amount = discount.user_amount = discount.line_discounts.to_a.sum(&:amount) discount.save! end order.reload end |
#apply_payment(order, order_hash) ⇒ Object
265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 265 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[:order_id] payment.delivery = order.deliveries.quoting.first payment.save! end end |
#create_line_items(order, order_hash) ⇒ Object
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 361 362 363 364 365 366 367 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 288 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 = [] catalog_items = cust.catalog.catalog_items.where(state: %w[active active_hidden require_vendor_update pending_vendor_update pending_discontinue]).order(state: :asc) order_hash[:order_lines].each_with_index do |line_hash, i| # First we try by promo sku vendor_upc = line_hash[:offer_sku] merchant_sku = line_hash[:product_sku] raise 'Missing identifier UPC in file' if vendor_upc.blank? && merchant_sku.blank? matched_catalog_item = nil # All products in Channel Engine are identified with their EAN13 if vendor_upc.present? case vendor_upc.size when 12 normalized_upc = vendor_upc when 13 normalized_upc = vendor_upc[1..] # remove the first character that will most likely be a zero end end matched_catalog_item ||= catalog_items.by_upcs(normalized_upc).first if normalized_upc.present? matched_catalog_item ||= catalog_items.where(third_party_promo_part_number: merchant_sku).first if merchant_sku.present? # If no match on that, try by merchant sku matched_catalog_item ||= catalog_items.where(third_party_part_number: merchant_sku).first if merchant_sku.present? # If no match, try third party sku matched_catalog_item ||= catalog_items.where(third_party_sku: merchant_sku).first if merchant_sku.present? if matched_catalog_item order.line_items.build.tap do |line_item| line_item.quantity = line_hash[:quantity].to_i # 2 line_item.edi_reference = line_hash[:order_line_id] line_item.edi_line_number = i + 1 line_item.catalog_item = matched_catalog_item # Prefer the line's own VAT rate when the orchestrator provides a # breakdown AND the line actually carries one. A VAT-breakdown order # can still arrive with an empty `taxes` array or a nil rate, and # Catalog#tax_rate (country&.tax_rate&.goods) is nil when the # catalog's country has no configured goods rate (e.g. the CAD # orchestrators with vat_breakdown_available: false). In either # missing-rate case fall back to the catalog rate, treating a nil as # 0% (vat_rate 1 → price == price_unit) — matching how the rest of # the app handles a nil rate (amazon_products_helper returns the # price unchanged). Without the guard a missing line tax rate raised # NoMethodError on nil and aborted the whole order flow (AppSignal # #3480, firing since Feb 2026). # Mirakl's OR11 order `rate` is a percent in [0, 100] (e.g. 21 for # 21%), and JSON.parse yields an Integer for "rate": 21 — so coerce # to BigDecimal before dividing, otherwise `21 / 100` integer-divides # to 0, vat_rate collapses to 1 and the line is under-priced. line_tax_rate = line_hash[:taxes]&.first&.dig(:rate) if orchestrator.vat_breakdown_available vat_rate = if line_tax_rate (BigDecimal(line_tax_rate.to_s) / 100) + 1 else (cust.catalog.tax_rate || 0) + 1 end price_with_vat = BigDecimal(line_hash[:price_unit].to_s) price = price_with_vat / vat_rate # line_item.edi_unit_cost = price # Mirakl doesn't provide the original price if we have a sale so this edi_unit_cost field becomes unreliable. better to remove it. 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." EdiMailer.notify_edi_admin_of_warning(subj, msg).deliver_later end else all_skus_valid = false bad_vendor_skus << vendor_upc.presence bad_merchant_skus << merchant_sku.presence errors << "Unknown vendor UPC: #{vendor_upc} / 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, bad_vendor_skus: bad_vendor_skus.compact, bad_merchant_skus: bad_merchant_skus.compact) end |
#create_shipping_address(order_hash) ⇒ Object
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 369 def create_shipping_address(order_hash) address_hash = order_hash[:customer][:shipping_address] raw_street1 = address_hash[:street_1]&.squish raw_street2 = address_hash[:street_2]&.squish originals = collect_street_originals(street1: raw_street1, street2: raw_street2) address = Address.new address.person_name_override = "#{address_hash[:firstname]} #{address_hash[:lastname]}".titleize.squish address.street1 = abbreviate_street(raw_street1) address.street2 = abbreviate_street(raw_street2) address.city = address_hash[:city]&.squish address.state_code = address_hash[:state]&.squish&.truncate(20) address.country_iso3 = address_hash[:country_iso_code]&.squish address.zip = address_hash[:zip_code].to_s.upcase.delete(' ')&.squish address.disable_address_correction = true address.override_all_address_validation = true address.save! [address, originals] end |
#create_sold_to_billing_address(order_hash) ⇒ Object
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 390 def create_sold_to_billing_address(order_hash) address = Address.new address_hash = order_hash[:customer][:billing_address] address.person_name_override = "#{address_hash[:firstname]} #{address_hash[:lastname]}".titleize&.squish address.company_name_override = address_hash[:company]&.squish address.street1 = address_hash[:street_1]&.squish address.street2 = address_hash[:street_2]&.squish address.city = address_hash[:city]&.squish address.state_code = address_hash[:state]&.squish&.truncate(20) address.country_iso3 = address_hash[:country_iso_code]&.squish address.zip = address_hash[:zip_code].to_s.upcase.delete(' ')&.squish address.disable_address_correction = true address.override_all_address_validation = true address.save! address end |
#customer(segment = nil) ⇒ Object
28 29 30 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 28 def customer(segment = nil) orchestrator.customer(segment) end |
#get_customer(order_hash) ⇒ Object
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 121 def get_customer(order_hash) if orchestrator.partner.to_s == 'leroymerlin_adeo' # The actual channel country comes from the order ID. chanel_order_number = order_hash[:commercial_id] country_code = chanel_order_number.split('-')[0] case country_code when '001' # France cus_id = LM_FR_CID when '002' # Spain cus_id = LM_ES_CID when '003' # Portugal cus_id = LM_PT_CID when '005' # Italy cus_id = LM_IT_CID end else # This assumes there is only 1 customer id for this partner. cus_id = orchestrator.customer_id.values.first end Customer.find(cus_id) end |
#process(edi_logs = nil, edi_transaction_id: nil) ⇒ Object
Picks up the edi communication log in the queue ready to process, generate acknowledgements
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 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 33 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_result.orders_created.each do |order| # This will only take care of new orders created in AWAITING_CONFIRM # Associate the created orders edi_log.edi_documents.create!(order: order) # Acknowledge the orders so we can send our order ID back to Channel Engine orchestrator..process(order) if orchestrator.orders_require_acceptance # retrieve related packing slips for this batch of orders # orchestrator.packing_slip_retriever.process(order) end batch_process_result.orders_confirmed.each do |order| # Associate the created orders only if is not associated yet edi_log.edi_documents.create!(order: order) if order.present? && edi_log.edi_documents.none? { |a| a.resource_id == order.id } end batch_process_results << batch_process_result edi_log.complete! # Mark our edi log as processed, we need some error handling at one point 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 begin rescue block end end report_order_creation_issues(batch_process_results) Result.new(batch_process_results: batch_process_results) end |
#process_confirmed_order(order_hash = nil) ⇒ Object
Process a single order
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 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 190 def process_confirmed_order(order_hash = nil) order = Order.find_by(edi_po_number: order_hash[:order_id]) # if order is pending it means it hasn't been fully processed yet if order.present? && order.pending? address, address_originals = create_shipping_address(order_hash) order.shipping_address = address order.sold_to_billing_address = create_sold_to_billing_address(order_hash) recipient_name = order.shipping_address.person_name_override || order.shipping_address.company_name_override # Customer info order.attention_name_override = recipient_name order.shipping_phone = order_hash[:customer][:shipping_address][:phone] email = order_hash[:customer_notification_email].presence order.tracking_email = [email].compact order.billing_emails = [email].compact # This is where the invoice will be sent order.edi_shipping_option_name = set_shipping_option(order, order_hash) order.edi_channel_order_support = order_hash[:commercial_id] order.save! record_address_abbreviation_notes(order, address_originals, order.shipping_address) apply_payment(order, order_hash) order.state = 'in_cr_hold' # Set this as the default state order.recalculate_shipping = true order.save! if (same_po_orders = Order.where(edi_po_number: order.edi_po_number).excluding(order)).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." EdiMailer.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 else # Order is already past processing logger.warn "Order #{order_hash[:order_id]} already processed and in state #{order.state}" end order end |
#process_orders(orders_data, edi_transaction_id: nil, edi_log_id: nil) ⇒ Object
Iterates through the batch order data
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 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 73 def process_orders(orders_data, edi_transaction_id: nil, edi_log_id: nil) # rubocop:disable Lint/UnusedMethodArgument json_hash = JSON.parse(orders_data).with_indifferent_access orders_created = [] orders_confirmed = [] orders_in_batch = 0 json_hash[:orders].each do |order_hash| log_info "Processing order #{order_hash.inspect}" po_number = order_hash[:order_id] if orchestrator.orders_require_acceptance if order_hash[:order_state] == 'WAITING_ACCEPTANCE' orders_in_batch += 1 if Order.where('created_at > ?', 12.months.ago).where(edi_po_number: po_number).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_unconfirmed_order(order_hash) 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." EdiMailer.notify_edi_admin_of_warning(subj, msg).deliver_later mark_duplicate_po_as_notified(po_number, edi_log_id) end end elsif order_hash[:order_state] == 'SHIPPING' ord = process_confirmed_order(order_hash) orders_confirmed << ord if ord.present? end elsif order_hash[:order_state] == 'SHIPPING' orders_in_batch += 1 if Order.where(created_at: 12.months.ago..).where(edi_po_number: po_number).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_unconfirmed_order(order_hash) ord = process_confirmed_order(order_hash) orders_confirmed << ord if ord.present? 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 "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." # EdiMailer.notify_edi_admin_of_warning(subj, msg).deliver_later end end end BatchProcessResult.new(batch_number: nil, orders_created: orders_created, orders_confirmed: orders_confirmed, orders_in_batch: orders_in_batch) end |
#process_unconfirmed_order(order_hash = nil) ⇒ Object
Process a single order
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 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 144 def process_unconfirmed_order(order_hash = nil) cust = get_customer(order_hash) order = cust.orders.build order. = order_hash.to_json order.edi_orchestrator_partner = orchestrator.partner.to_s order.edi_order_date = Date.parse(order_hash[:created_date]) order.edi_transaction_id = order_hash[:order_id] order.edi_po_number = order_hash[:order_id] order.customer_reference = "OrderNumber: #{order_hash[:order_id]}" # original currency order.currency = cust.store.currency order.single_origin = Store::PUBLIC_STORE_IDS.include?(cust.store.id) 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! # line items line_creation_result = create_line_items(order, order_hash) raise line_creation_result. unless line_creation_result.all_skus_valid adjust_shipping_cost(order, order_hash) # Roman # Revenue before taxes (for price comparison), if price differs, problem, cr hold order.line_total line_creation_result.line_total order.price_match = line_creation_result.line_total # will get save when we call the event 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).excluding(order)).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." EdiMailer.notify_edi_admin_of_warning(subj, msg).deliver_later end # simplest thing to do is to flag the issue and raise an exception, don't even create the order order end |
#set_shipping_option(order, order_hash) ⇒ Object
280 281 282 283 284 285 286 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 280 def set_shipping_option(order, order_hash) shipping_code = order_hash[:shipping_carrier_code] order.country.eu_country? order.edi_original_ship_code = shipping_code order.signature_confirmation = false order.shipping_method = 'override' end |
#shipping_invalid?(order) ⇒ Boolean
230 231 232 233 234 235 236 237 238 |
# File 'app/services/edi/mirakl_seller/order_message_processor.rb', line 230 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 |