Class: FriendlyShipping::Services::TForceFreight::ParseRatesResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/friendly_shipping/services/tforce_freight/parse_rates_response.rb

Overview

Parses a rates response into an ApiResult.

Class Method Summary collapse

Class Method Details

.call(request:, response:) ⇒ ApiResult<Array<Rate>>

Returns the parsed result.

Parameters:

  • request (Request)

    the original request

  • response (RestClient::Response)

    the response to parse

Returns:



12
13
14
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
# File 'lib/friendly_shipping/services/tforce_freight/parse_rates_response.rb', line 12

def call(request:, response:)
  json = JSON.parse(response.body)
  transaction_id = json.dig("summary", "transactionReference", "transactionId")

  rates = json['detail'].map do |detail|
    service_code = detail.dig("service", "code")
    shipping_method = SHIPPING_METHODS.detect { |sm| sm.service_code == service_code }

    total_amount = detail.dig("shipmentCharges", "total", "value")
    total_currency = detail.dig("shipmentCharges", "total", "currency")
    total = Money.new(total_amount.to_f * 100, total_currency)

    data = {
      customer_context: transaction_id,
      commodities: Array.wrap(json['commodities']),
      cost_breakdown: detail['rate'].map { |rate| rate.slice(*%w[code description value unit]) }
    }

    days_in_transit = detail.dig("timeInTransit", "timeInTransit")
    data[:days_in_transit] = days_in_transit.to_i if days_in_transit

    FriendlyShipping::Rate.new(
      amounts: { total: total },
      shipping_method: shipping_method,
      data: data
    )
  end

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