Class: FriendlyShipping::Services::UspsInternational::ParseRateResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/friendly_shipping/services/usps_international/parse_rate_response.rb

Defined Under Namespace

Classes: BoxNotFoundError

Class Method Summary collapse

Class Method Details

.call(request:, response:, shipment:, options:) ⇒ Result<ApiResult<Array<FriendlyShipping::Rate>>>

Parse a response from USPS’ international rating API

Parameters:

Returns:



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
54
55
# File 'lib/friendly_shipping/services/usps_international/parse_rate_response.rb', line 20

def call(request:, response:, shipment:, options:)
  # Filter out error responses and directly return a failure
  parsing_result = FriendlyShipping::Services::Usps::ParseXMLResponse.call(
    request: request,
    response: response,
    expected_root_tag: 'IntlRateV2Response'
  )
  parsing_result.fmap do |xml|
    # Get all the possible rates for each package
    rates_by_package = rates_from_response_node(xml, shipment, options)

    rates = SHIPPING_METHODS.map do |shipping_method|
      # For every package ...
      matching_rates = rates_by_package.map do |_package, package_rates|
        # ... choose the rate that matches the shipping method for this package
        package_rates.select { |r| r.shipping_method == shipping_method }.first
      end.compact # Some shipping rates are not available for every shipping method.

      # in this case, go to the next shipping method.
      next if matching_rates.empty?

      # return one rate for all packages with the amount keys being the package IDs.
      FriendlyShipping::Rate.new(
        amounts: matching_rates.map(&:amounts).reduce({}, :merge),
        shipping_method: shipping_method,
        data: matching_rates.first.data
      )
    end.compact

    ApiResult.new(
      rates,
      original_request: request,
      original_response: response
    )
  end
end