Sha256: c8af7bb963b93665070b58cd358c0e4af6657cc96ac1b4ada44fbbdd7f50b544

Contents?: true

Size: 1.96 KB

Versions: 3

Compression:

Stored size: 1.96 KB

Contents

# frozen_string_literal: true

require 'friendly_shipping/services/ups/parse_xml_response'

module FriendlyShipping
  module Services
    class Ups
      class ParseRateResponse
        def self.call(request:, response:, shipment:)
          parsing_result = ParseXMLResponse.call(response.body, 'RatingServiceSelectionResponse')
          parsing_result.fmap do |xml|
            FriendlyShipping::ApiResult.new(
              build_rates(xml, shipment),
              original_request: request,
              original_response: response
            )
          end
        end

        def self.build_rates(xml, shipment)
          xml.root.css('> RatedShipment').map do |rated_shipment|
            service_code = rated_shipment.at('Service/Code').text
            shipping_method = CARRIER.shipping_methods.detect do |sm|
              sm.service_code == service_code && shipment.origin.country.in?(sm.origin_countries)
            end
            days_to_delivery = rated_shipment.at('GuaranteedDaysToDelivery').text.to_i
            currency = Money::Currency.new(rated_shipment.at('TotalCharges/CurrencyCode').text)
            total_cents = rated_shipment.at('TotalCharges/MonetaryValue').text.to_d * currency.subunit_to_unit
            insurance_price = rated_shipment.at('ServiceOptionsCharges/MonetaryValue').text.to_f
            negotiated_rate = rated_shipment.at(
              'NegotiatedRates/NetSummaryCharges/GrandTotal/MonetaryValue'
            )&.text.to_f

            FriendlyShipping::Rate.new(
              shipping_method: shipping_method,
              amounts: { total: Money.new(total_cents, currency) },
              warnings: [rated_shipment.at("RatedShipmentWarning")&.text].compact,
              errors: [],
              data: {
                insurance_price: insurance_price,
                negotiated_rate: negotiated_rate,
                days_to_delivery: days_to_delivery
              }
            )
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
friendly_shipping-0.3.4 lib/friendly_shipping/services/ups/parse_rate_response.rb
friendly_shipping-0.3.3 lib/friendly_shipping/services/ups/parse_rate_response.rb
friendly_shipping-0.3.0 lib/friendly_shipping/services/ups/parse_rate_response.rb