Class: FriendlyShipping::Services::UpsFreight::ParseFreightLabelResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/friendly_shipping/services/ups_freight/parse_freight_label_response.rb

Class Method Summary collapse

Class Method Details

.call(request:, response:) ⇒ Object



11
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/friendly_shipping/services/ups_freight/parse_freight_label_response.rb', line 11

def call(request:, response:)
  json = JSON.parse(response.body)

  warnings_json = Array.wrap(json.dig("FreightShipResponse", "Response", "Alert"))
  warnings = warnings_json.map do |detailed_warning|
    status = detailed_warning['Code']
    desc = detailed_warning['Description']
    [status, desc].compact.join(": ")
  end.join("\n")

  shipment_results = json.dig("FreightShipResponse", "ShipmentResults")

  service_code = shipment_results.dig("Service", "Code")
  shipping_method = SHIPPING_METHODS.detect { |sm| sm.service_code == service_code }

  total_shipment_charge = shipment_results["TotalShipmentCharge"]
  if total_shipment_charge
    currency = Money::Currency.new(total_shipment_charge['CurrencyCode'])
    amount = total_shipment_charge['MonetaryValue'].to_f
    total_money = Money.new(amount * currency.subunit_to_unit, currency)
  end

  images_data = Array.wrap(shipment_results.dig("Documents", "Image"))

  bol_id = shipment_results["BOLID"]
  shipment_number = shipment_results["ShipmentNumber"]
  pickup_request_number = shipment_results["PickupRequestConfirmationNumber"]

  documents = images_data.map { |image_data| ParseShipmentDocument.call(image_data: image_data) }

  cost_breakdown = build_cost_breakdown(shipment_results)

  FriendlyShipping::ApiResult.new(
    ShipmentInformation.new(
      total: total_money,
      bol_id: bol_id,
      number: shipment_number,
      pickup_request_number: pickup_request_number,
      shipping_method: shipping_method,
      warnings: warnings,
      documents: documents,
      data: {
        cost_breakdown: cost_breakdown
      }
    ),
    original_request: request,
    original_response: response
  )
end