Class: FriendlyShipping::Services::Usps::ParseRateResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/friendly_shipping/services/usps/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’ rating API

Parameters:

Returns:



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
56
57
58
59
# File 'lib/friendly_shipping/services/usps/parse_rate_response.rb', line 21

def call(request:, response:, shipment:, options:)
  # Filter out error responses and directly return a failure
  parsing_result = ParseXMLResponse.call(
    request: request,
    response: response,
    expected_root_tag: 'RateV4Response'
  )
  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 fits this package best.

        package_options = options.options_for_package(package)

        ChoosePackageRate.call(shipping_method, package_rates, package_options)
      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