friendly_shipping 0.8.1 → 0.10.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (217) hide show
  1. checksums.yaml +4 -4
  2. data/.circleci/config.yml +1 -1
  3. data/.env.template +3 -0
  4. data/.env.test.local.template +6 -0
  5. data/.gitignore +1 -0
  6. data/.rubocop-relaxed.yml +7 -23
  7. data/.rubocop.yml +17 -2
  8. data/.rubocop_todo.yml +21 -0
  9. data/.yardopts +6 -0
  10. data/CHANGELOG.md +71 -0
  11. data/Gemfile +17 -0
  12. data/README.md +1 -1
  13. data/friendly_shipping.gemspec +8 -17
  14. data/lib/friendly_shipping/access_token.rb +24 -0
  15. data/lib/friendly_shipping/api_error.rb +8 -4
  16. data/lib/friendly_shipping/api_error_handler.rb +11 -9
  17. data/lib/friendly_shipping/api_failure.rb +2 -7
  18. data/lib/friendly_shipping/api_result.rb +26 -4
  19. data/lib/friendly_shipping/carrier.rb +28 -8
  20. data/lib/friendly_shipping/http_client.rb +25 -8
  21. data/lib/friendly_shipping/inflections.rb +10 -0
  22. data/lib/friendly_shipping/item_options.rb +3 -0
  23. data/lib/friendly_shipping/label.rb +41 -22
  24. data/lib/friendly_shipping/package_options.rb +21 -2
  25. data/lib/friendly_shipping/rate.rb +50 -15
  26. data/lib/friendly_shipping/request.rb +23 -7
  27. data/lib/friendly_shipping/response.rb +21 -6
  28. data/lib/friendly_shipping/services/rl/api_error.rb +31 -0
  29. data/lib/friendly_shipping/services/rl/bol_options.rb +103 -0
  30. data/lib/friendly_shipping/services/rl/bol_packages_serializer.rb +32 -0
  31. data/lib/friendly_shipping/services/rl/bol_structures_serializer.rb +31 -0
  32. data/lib/friendly_shipping/services/rl/item_options.rb +36 -0
  33. data/lib/friendly_shipping/services/rl/package_options.rb +38 -0
  34. data/lib/friendly_shipping/services/rl/parse_create_bol_response.rb +43 -0
  35. data/lib/friendly_shipping/services/rl/parse_invoice_response.rb +47 -0
  36. data/lib/friendly_shipping/services/rl/parse_print_bol_response.rb +44 -0
  37. data/lib/friendly_shipping/services/rl/parse_print_shipping_labels_response.rb +44 -0
  38. data/lib/friendly_shipping/services/rl/parse_rate_quote_response.rb +93 -0
  39. data/lib/friendly_shipping/services/rl/parse_transit_times_response.rb +73 -0
  40. data/lib/friendly_shipping/services/rl/rate_quote_options.rb +82 -0
  41. data/lib/friendly_shipping/services/rl/rate_quote_packages_serializer.rb +54 -0
  42. data/lib/friendly_shipping/services/rl/rate_quote_structures_serializer.rb +53 -0
  43. data/lib/friendly_shipping/services/rl/serialize_create_bol_request.rb +86 -0
  44. data/lib/friendly_shipping/services/rl/serialize_location.rb +53 -0
  45. data/lib/friendly_shipping/services/rl/serialize_rate_quote_request.rb +69 -0
  46. data/lib/friendly_shipping/services/rl/serialize_transit_times_request.rb +38 -0
  47. data/lib/friendly_shipping/services/rl/shipment_document.rb +40 -0
  48. data/lib/friendly_shipping/services/rl/shipment_information.rb +41 -0
  49. data/lib/friendly_shipping/services/rl/shipment_options.rb +48 -0
  50. data/lib/friendly_shipping/services/rl/shipping_methods.rb +28 -0
  51. data/lib/friendly_shipping/services/rl/structure_options.rb +13 -0
  52. data/lib/friendly_shipping/services/rl.rb +187 -0
  53. data/lib/friendly_shipping/services/ship_engine/api_error.rb +31 -0
  54. data/lib/friendly_shipping/services/ship_engine/customs_items_serializer.rb +36 -0
  55. data/lib/friendly_shipping/services/ship_engine/label_customs_options.rb +10 -7
  56. data/lib/friendly_shipping/services/ship_engine/label_item_options.rb +10 -7
  57. data/lib/friendly_shipping/services/ship_engine/label_options.rb +30 -17
  58. data/lib/friendly_shipping/services/ship_engine/label_package_options.rb +18 -14
  59. data/lib/friendly_shipping/services/ship_engine/parse_address_validation_response.rb +75 -0
  60. data/lib/friendly_shipping/services/ship_engine/parse_carrier_response.rb +9 -2
  61. data/lib/friendly_shipping/services/ship_engine/parse_label_response.rb +4 -2
  62. data/lib/friendly_shipping/services/ship_engine/{parse_rate_estimate_response.rb → parse_rate_estimates_response.rb} +27 -9
  63. data/lib/friendly_shipping/services/ship_engine/parse_rates_response.rb +99 -0
  64. data/lib/friendly_shipping/services/ship_engine/parse_void_response.rb +5 -1
  65. data/lib/friendly_shipping/services/ship_engine/rate_estimates_options.rb +17 -6
  66. data/lib/friendly_shipping/services/ship_engine/rates_item_options.rb +26 -0
  67. data/lib/friendly_shipping/services/ship_engine/rates_options.rb +59 -0
  68. data/lib/friendly_shipping/services/ship_engine/rates_package_options.rb +18 -0
  69. data/lib/friendly_shipping/services/ship_engine/serialize_address_residential_indicator.rb +27 -0
  70. data/lib/friendly_shipping/services/ship_engine/serialize_address_validation_request.rb +31 -0
  71. data/lib/friendly_shipping/services/ship_engine/serialize_label_shipment.rb +22 -27
  72. data/lib/friendly_shipping/services/ship_engine/serialize_rate_estimate_request.rb +41 -16
  73. data/lib/friendly_shipping/services/ship_engine/serialize_rates_request.rb +126 -0
  74. data/lib/friendly_shipping/services/ship_engine.rb +89 -33
  75. data/lib/friendly_shipping/services/ship_engine_ltl/api_error.rb +12 -0
  76. data/lib/friendly_shipping/services/ship_engine_ltl/item_options.rb +24 -5
  77. data/lib/friendly_shipping/services/ship_engine_ltl/package_options.rb +39 -4
  78. data/lib/friendly_shipping/services/ship_engine_ltl/parse_carrier_response.rb +4 -2
  79. data/lib/friendly_shipping/services/ship_engine_ltl/parse_quote_response.rb +10 -2
  80. data/lib/friendly_shipping/services/ship_engine_ltl/quote_options.rb +29 -11
  81. data/lib/friendly_shipping/services/ship_engine_ltl/serialize_packages.rb +7 -2
  82. data/lib/friendly_shipping/services/ship_engine_ltl/serialize_quote_request.rb +50 -16
  83. data/lib/friendly_shipping/services/ship_engine_ltl/serialize_structures.rb +42 -0
  84. data/lib/friendly_shipping/services/ship_engine_ltl/shipment_options.rb +47 -0
  85. data/lib/friendly_shipping/services/ship_engine_ltl/structure_options.rb +17 -0
  86. data/lib/friendly_shipping/services/ship_engine_ltl.rb +47 -39
  87. data/lib/friendly_shipping/services/tforce_freight/access_token.rb +28 -0
  88. data/lib/friendly_shipping/services/tforce_freight/api_error.rb +40 -0
  89. data/lib/friendly_shipping/services/tforce_freight/bol_options.rb +180 -0
  90. data/lib/friendly_shipping/services/tforce_freight/document_options.rb +100 -0
  91. data/lib/friendly_shipping/services/tforce_freight/generate_commodity_information.rb +92 -0
  92. data/lib/friendly_shipping/services/tforce_freight/generate_create_bol_request_hash.rb +153 -0
  93. data/lib/friendly_shipping/services/tforce_freight/generate_document_options_hash.rb +36 -0
  94. data/lib/friendly_shipping/services/tforce_freight/generate_handling_units_hash.rb +51 -0
  95. data/lib/friendly_shipping/services/tforce_freight/generate_location_hash.rb +25 -0
  96. data/lib/friendly_shipping/services/tforce_freight/generate_pickup_request_hash.rb +111 -0
  97. data/lib/friendly_shipping/services/tforce_freight/generate_rates_request_hash.rb +63 -0
  98. data/lib/friendly_shipping/services/tforce_freight/generate_reference_hash.rb +28 -0
  99. data/lib/friendly_shipping/services/tforce_freight/item_options.rb +93 -0
  100. data/lib/friendly_shipping/services/tforce_freight/package_options.rb +119 -0
  101. data/lib/friendly_shipping/services/tforce_freight/parse_create_bol_response.rb +90 -0
  102. data/lib/friendly_shipping/services/tforce_freight/parse_pickup_response.rb +45 -0
  103. data/lib/friendly_shipping/services/tforce_freight/parse_rates_response.rb +50 -0
  104. data/lib/friendly_shipping/services/tforce_freight/parse_shipment_document.rb +29 -0
  105. data/lib/friendly_shipping/services/tforce_freight/pickup_options.rb +82 -0
  106. data/lib/friendly_shipping/services/tforce_freight/rates_item_options.rb +10 -0
  107. data/lib/friendly_shipping/services/tforce_freight/rates_options.rb +159 -0
  108. data/lib/friendly_shipping/services/tforce_freight/rates_package_options.rb +10 -0
  109. data/lib/friendly_shipping/services/tforce_freight/shipment_document.rb +38 -0
  110. data/lib/friendly_shipping/services/tforce_freight/shipment_information.rb +104 -0
  111. data/lib/friendly_shipping/services/tforce_freight/shipment_options.rb +47 -0
  112. data/lib/friendly_shipping/services/tforce_freight/shipping_methods.rb +25 -0
  113. data/lib/friendly_shipping/services/tforce_freight/structure_options.rb +44 -0
  114. data/lib/friendly_shipping/services/tforce_freight.rb +176 -0
  115. data/lib/friendly_shipping/services/ups/label_item_options.rb +0 -2
  116. data/lib/friendly_shipping/services/ups/label_options.rb +14 -5
  117. data/lib/friendly_shipping/services/ups/label_package_options.rb +1 -3
  118. data/lib/friendly_shipping/services/ups/parse_address_validation_response.rb +1 -1
  119. data/lib/friendly_shipping/services/ups/parse_modifier_element.rb +29 -0
  120. data/lib/friendly_shipping/services/ups/parse_rate_response.rb +11 -3
  121. data/lib/friendly_shipping/services/ups/parse_shipment_accept_response.rb +0 -3
  122. data/lib/friendly_shipping/services/ups/parse_shipment_confirm_response.rb +0 -2
  123. data/lib/friendly_shipping/services/ups/parse_time_in_transit_response.rb +1 -1
  124. data/lib/friendly_shipping/services/ups/parse_void_shipment_response.rb +0 -2
  125. data/lib/friendly_shipping/services/ups/parse_xml_response.rb +1 -1
  126. data/lib/friendly_shipping/services/ups/rate_estimate_options.rb +14 -3
  127. data/lib/friendly_shipping/services/ups/rate_estimate_package_options.rb +0 -2
  128. data/lib/friendly_shipping/services/ups/serialize_access_request.rb +0 -2
  129. data/lib/friendly_shipping/services/ups/serialize_rating_service_selection_request.rb +10 -5
  130. data/lib/friendly_shipping/services/ups/serialize_shipment_accept_request.rb +1 -1
  131. data/lib/friendly_shipping/services/ups/serialize_shipment_confirm_request.rb +2 -4
  132. data/lib/friendly_shipping/services/ups/shipping_methods.rb +1 -1
  133. data/lib/friendly_shipping/services/ups.rb +2 -24
  134. data/lib/friendly_shipping/services/ups_freight/api_error.rb +8 -7
  135. data/lib/friendly_shipping/services/ups_freight/generate_commodity_information.rb +65 -19
  136. data/lib/friendly_shipping/services/ups_freight/generate_freight_rate_request_hash.rb +2 -23
  137. data/lib/friendly_shipping/services/ups_freight/generate_freight_ship_request_hash.rb +1 -27
  138. data/lib/friendly_shipping/services/ups_freight/generate_handling_units_hash.rb +54 -0
  139. data/lib/friendly_shipping/services/ups_freight/label_options.rb +36 -10
  140. data/lib/friendly_shipping/services/ups_freight/label_structure_options.rb +13 -0
  141. data/lib/friendly_shipping/services/ups_freight/parse_freight_label_response.rb +2 -5
  142. data/lib/friendly_shipping/services/ups_freight/parse_freight_rate_response.rb +0 -4
  143. data/lib/friendly_shipping/services/ups_freight/parse_shipment_document.rb +1 -3
  144. data/lib/friendly_shipping/services/ups_freight/rates_item_options.rb +18 -9
  145. data/lib/friendly_shipping/services/ups_freight/rates_options.rb +30 -24
  146. data/lib/friendly_shipping/services/ups_freight/rates_package_options.rb +79 -10
  147. data/lib/friendly_shipping/services/ups_freight/rates_structure_options.rb +44 -0
  148. data/lib/friendly_shipping/services/ups_freight/shipment_information.rb +7 -3
  149. data/lib/friendly_shipping/services/ups_freight/shipment_options.rb +47 -0
  150. data/lib/friendly_shipping/services/ups_freight.rb +2 -20
  151. data/lib/friendly_shipping/services/ups_json/access_token.rb +20 -0
  152. data/lib/friendly_shipping/services/ups_json/api_error.rb +27 -0
  153. data/lib/friendly_shipping/services/ups_json/generate_address_classification_payload.rb +29 -0
  154. data/lib/friendly_shipping/services/ups_json/generate_address_hash.rb +30 -0
  155. data/lib/friendly_shipping/services/ups_json/generate_city_state_lookup_payload.rb +23 -0
  156. data/lib/friendly_shipping/services/ups_json/generate_labels_payload.rb +208 -0
  157. data/lib/friendly_shipping/services/ups_json/generate_package_hash.rb +76 -0
  158. data/lib/friendly_shipping/services/ups_json/generate_rates_payload.rb +84 -0
  159. data/lib/friendly_shipping/services/ups_json/generate_timings_payload.rb +44 -0
  160. data/lib/friendly_shipping/services/ups_json/label.rb +20 -0
  161. data/lib/friendly_shipping/services/ups_json/label_billing_options.rb +41 -0
  162. data/lib/friendly_shipping/services/ups_json/label_item_options.rb +75 -0
  163. data/lib/friendly_shipping/services/ups_json/label_options.rb +174 -0
  164. data/lib/friendly_shipping/services/ups_json/label_package_options.rb +49 -0
  165. data/lib/friendly_shipping/services/ups_json/parse_address_classification_response.rb +31 -0
  166. data/lib/friendly_shipping/services/ups_json/parse_city_state_lookup_response.rb +44 -0
  167. data/lib/friendly_shipping/services/ups_json/parse_json_response.rb +51 -0
  168. data/lib/friendly_shipping/services/ups_json/parse_labels_response.rb +71 -0
  169. data/lib/friendly_shipping/services/ups_json/parse_money_hash.rb +128 -0
  170. data/lib/friendly_shipping/services/ups_json/parse_rate_modifier_hash.rb +28 -0
  171. data/lib/friendly_shipping/services/ups_json/parse_rates_response.rb +107 -0
  172. data/lib/friendly_shipping/services/ups_json/parse_timings_response.rb +56 -0
  173. data/lib/friendly_shipping/services/ups_json/parse_void_response.rb +32 -0
  174. data/lib/friendly_shipping/services/ups_json/rates_item_options.rb +20 -0
  175. data/lib/friendly_shipping/services/ups_json/rates_options.rb +111 -0
  176. data/lib/friendly_shipping/services/ups_json/rates_package_options.rb +17 -0
  177. data/lib/friendly_shipping/services/ups_json/shipping_methods.rb +111 -0
  178. data/lib/friendly_shipping/services/ups_json/timings_options.rb +33 -0
  179. data/lib/friendly_shipping/services/ups_json.rb +216 -0
  180. data/lib/friendly_shipping/services/usps/choose_package_rate.rb +3 -3
  181. data/lib/friendly_shipping/services/usps/machinable_package.rb +1 -1
  182. data/lib/friendly_shipping/services/usps/parse_package_rate.rb +6 -6
  183. data/lib/friendly_shipping/services/usps/parse_rate_response.rb +0 -4
  184. data/lib/friendly_shipping/services/usps/parse_time_in_transit_response.rb +6 -9
  185. data/lib/friendly_shipping/services/usps/parse_xml_response.rb +1 -1
  186. data/lib/friendly_shipping/services/usps/rate_estimate_options.rb +1 -3
  187. data/lib/friendly_shipping/services/usps/rate_estimate_package_options.rb +6 -3
  188. data/lib/friendly_shipping/services/usps/serialize_rate_request.rb +2 -4
  189. data/lib/friendly_shipping/services/usps/shipping_methods.rb +4 -3
  190. data/lib/friendly_shipping/services/usps.rb +2 -13
  191. data/lib/friendly_shipping/services/usps_international/parse_package_rate.rb +3 -3
  192. data/lib/friendly_shipping/services/usps_international/parse_rate_response.rb +0 -3
  193. data/lib/friendly_shipping/services/usps_international/rate_estimate_options.rb +1 -3
  194. data/lib/friendly_shipping/services/usps_international/rate_estimate_package_options.rb +0 -2
  195. data/lib/friendly_shipping/services/usps_international/serialize_rate_request.rb +1 -3
  196. data/lib/friendly_shipping/services/usps_international.rb +2 -6
  197. data/lib/friendly_shipping/services/usps_ship/access_token.rb +22 -0
  198. data/lib/friendly_shipping/services/usps_ship/api_error.rb +27 -0
  199. data/lib/friendly_shipping/services/usps_ship/machinable_package.rb +55 -0
  200. data/lib/friendly_shipping/services/usps_ship/parse_rate_estimates_response.rb +80 -0
  201. data/lib/friendly_shipping/services/usps_ship/parse_timings_response.rb +82 -0
  202. data/lib/friendly_shipping/services/usps_ship/rate_estimate_options.rb +45 -0
  203. data/lib/friendly_shipping/services/usps_ship/rate_estimate_package_options.rb +122 -0
  204. data/lib/friendly_shipping/services/usps_ship/serialize_rate_estimates_request.rb +53 -0
  205. data/lib/friendly_shipping/services/usps_ship/shipping_methods.rb +38 -0
  206. data/lib/friendly_shipping/services/{ship_engine_ltl/bad_request.rb → usps_ship/timing_options.rb} +2 -2
  207. data/lib/friendly_shipping/services/usps_ship.rb +185 -0
  208. data/lib/friendly_shipping/shipment_options.rb +13 -1
  209. data/lib/friendly_shipping/shipping_method.rb +38 -11
  210. data/lib/friendly_shipping/structure_options.rb +38 -0
  211. data/lib/friendly_shipping/timing.rb +42 -7
  212. data/lib/friendly_shipping/version.rb +1 -1
  213. data/lib/friendly_shipping.rb +20 -15
  214. metadata +143 -174
  215. data/lib/friendly_shipping/services/ship_engine/bad_request.rb +0 -29
  216. data/lib/friendly_shipping/services/ship_engine/bad_request_handler.rb +0 -33
  217. data/lib/friendly_shipping/services/ship_engine_ltl/bad_request_handler.rb +0 -33
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FriendlyShipping
4
+ module Services
5
+ class USPSShip
6
+ class ParseRateEstimatesResponse
7
+ extend Dry::Monads::Result::Mixin
8
+ CURRENCY = Money::Currency.new('USD').freeze
9
+
10
+ class << self
11
+ # Parse a rate estimates response.
12
+ #
13
+ # @param request [Request] the request that was used to obtain this response
14
+ # @param response [Response] the response that USPS returned
15
+ # @return [Success<ApiResult<Array<Rate>>>, Failure<ApiResult<String>>]
16
+ def call(request:, response:)
17
+ rates = JSON.parse(response.body)['rates'].map do |rate|
18
+ shipping_method = SHIPPING_METHODS.detect { |sm| sm.service_code == rate['mailClass'] }
19
+ amounts = { price: money(rate['price']) }
20
+
21
+ # Add any additional fees to the amounts hash
22
+ rate['fees'].each_with_object(amounts) do |fee, result|
23
+ result[fee['name']] = money(fee['price'])
24
+ end
25
+
26
+ FriendlyShipping::Rate.new(
27
+ amounts: amounts,
28
+ shipping_method: shipping_method,
29
+ data: {
30
+ description: rate['description'],
31
+ zone: rate['zone']
32
+ }
33
+ )
34
+ end
35
+
36
+ success(rates, request, response)
37
+ rescue JSON::ParserError, KeyError => e
38
+ failure(e.message, request, response)
39
+ end
40
+
41
+ private
42
+
43
+ # @param value [Numeric]
44
+ # @return [Money]
45
+ def money(value)
46
+ Money.new(value * CURRENCY.subunit_to_unit, CURRENCY)
47
+ end
48
+
49
+ # @param rates [Array<Rate>]
50
+ # @param request [Request]
51
+ # @param response [Response]
52
+ # @return [Success<ApiResult<Array<Rate>>]
53
+ def success(rates, request, response)
54
+ Success(
55
+ ApiResult.new(
56
+ rates,
57
+ original_request: request,
58
+ original_response: response
59
+ )
60
+ )
61
+ end
62
+
63
+ # @param message [String]
64
+ # @param request [Request]
65
+ # @param response [Response]
66
+ # @return [Failure<ApiResult<String>>]
67
+ def failure(message, request, response)
68
+ Failure(
69
+ ApiResult.new(
70
+ message,
71
+ original_request: request,
72
+ original_response: response
73
+ )
74
+ )
75
+ end
76
+ end
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FriendlyShipping
4
+ module Services
5
+ class USPSShip
6
+ class ParseTimingsResponse
7
+ extend Dry::Monads::Result::Mixin
8
+
9
+ class << self
10
+ # Parse a timings response.
11
+ #
12
+ # @param request [Request] the request that was used to obtain this response
13
+ # @param response [Response] the response that USPS returned
14
+ # @return [Success<ApiResult<Array<Timing>>>, Failure<ApiResult<String>>]
15
+ def call(request:, response:)
16
+ timings = JSON.parse(response.body).map do |timing|
17
+ shipping_method = SHIPPING_METHODS.detect { |sm| sm.service_code == timing['mailClass'] }
18
+
19
+ # The delivery estimate is blank if an invalid destination zip code was used
20
+ delivery = timing.dig('delivery', 'scheduledDeliveryDateTime')
21
+ next unless delivery
22
+
23
+ FriendlyShipping::Timing.new(
24
+ shipping_method: shipping_method,
25
+ pickup: Time.parse(timing['acceptanceDateTime']),
26
+ delivery: Time.parse(delivery),
27
+ guaranteed: timing['delivery']['guaranteedDelivery'],
28
+ data: {
29
+ notes: timing['notes'],
30
+ service_standard: timing['serviceStandard'],
31
+ service_standard_message: timing['serviceStandardMessage']
32
+ }
33
+ )
34
+ end.compact
35
+
36
+ if timings.empty?
37
+ failure(api_error("No timings were returned. Is the destination zip correct?"), request, response)
38
+ else
39
+ success(timings, request, response)
40
+ end
41
+ rescue JSON::ParserError => e
42
+ failure(e, request, response)
43
+ end
44
+
45
+ # @param timings [Array<Timing>]
46
+ # @param request [Request]
47
+ # @param response [Response]
48
+ # @return [Success<ApiResult<Array<Timing>>]
49
+ def success(timings, request, response)
50
+ Success(
51
+ ApiResult.new(
52
+ timings,
53
+ original_request: request,
54
+ original_response: response
55
+ )
56
+ )
57
+ end
58
+
59
+ # @param error [JSON::ParserError, FriendlyShipping::ApiError]
60
+ # @param request [Request]
61
+ # @param response [Response]
62
+ # @return [Failure<ApiResult>]
63
+ def failure(error, request, response)
64
+ Failure(
65
+ ApiResult.new(
66
+ error,
67
+ original_request: request,
68
+ original_response: response
69
+ )
70
+ )
71
+ end
72
+
73
+ private
74
+
75
+ def api_error(message)
76
+ FriendlyShipping::ApiError.new(nil, message)
77
+ end
78
+ end
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FriendlyShipping
4
+ module Services
5
+ class USPSShip
6
+ class RateEstimateOptions < FriendlyShipping::ShipmentOptions
7
+ DESTINATION_ENTRY_FACILITY_TYPES = {
8
+ none: "NONE",
9
+ destination_network_distribution_center: "DESTINATION_NETWORK_DISTRIBUTION_CENTER",
10
+ destination_sectional_center_facility: "DESTINATION_SECTIONAL_CENTER_FACILITY",
11
+ destination_delivery_unit: "DESTINATION_DELIVERY_UNIT",
12
+ destination_service_hub: "DESTINATION_SERVICE_HUB"
13
+ }.freeze
14
+
15
+ # @return [ShippingMethod]
16
+ attr_reader :shipping_method
17
+
18
+ # @return [String]
19
+ attr_reader :destination_entry_facility_type
20
+
21
+ # @return [#strftime]
22
+ attr_reader :mailing_date
23
+
24
+ # @param shipping_method [ShippingMethod] the shipping method for which we want a rate
25
+ # @param destination_entry_facility_type [Symbol] one of {DESTINATION_ENTRY_FACILITY_TYPES}
26
+ # @param mailing_date [#strftime] the date on which we want to ship
27
+ # @param package_options_class [Class] the class to use for package options
28
+ # @param kwargs [Hash]
29
+ # @option kwargs [Array<PackageOptions>] :package_options the options for packages in this shipment
30
+ def initialize(
31
+ shipping_method:,
32
+ destination_entry_facility_type: :none,
33
+ mailing_date: Date.today,
34
+ package_options_class: FriendlyShipping::Services::USPSShip::RateEstimatePackageOptions,
35
+ **kwargs
36
+ )
37
+ @shipping_method = shipping_method
38
+ @destination_entry_facility_type = DESTINATION_ENTRY_FACILITY_TYPES.fetch(destination_entry_facility_type)
39
+ @mailing_date = mailing_date
40
+ super(**kwargs.reverse_merge(package_options_class: package_options_class))
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FriendlyShipping
4
+ module Services
5
+ class USPSShip
6
+ class RateEstimatePackageOptions < FriendlyShipping::PackageOptions
7
+ PROCESSING_CATEGORIES = {
8
+ letters: "LETTERS",
9
+ flats: "FLATS",
10
+ machinable: "MACHINABLE",
11
+ irregular: "IRREGULAR",
12
+ non_machinable: "NON_MACHINABLE"
13
+ }.freeze
14
+
15
+ RATE_INDICATORS = {
16
+ three_digit: "3D",
17
+ three_digit_dimensional_rectangular: "3N",
18
+ three_digit_dimensional_nonrectangular: "3R",
19
+ five_digit: "5D",
20
+ basic: "BA",
21
+ mixed_ndc: "BB",
22
+ ndc: "BM",
23
+ cubic_pricing_tier_1: "C1",
24
+ cubic_pricing_tier_2: "C2",
25
+ cubic_pricing_tier_3: "C3",
26
+ cubic_pricing_tier_4: "C4",
27
+ cubic_pricing_tier_5: "C5",
28
+ cubic_parcel: "CP",
29
+ usps_connect_local_mail: "CM",
30
+ ndc_2: "DC",
31
+ scf: "DE",
32
+ five_digit_2: "DF",
33
+ dimensional_nonrectangular: "DN",
34
+ dimensional_rectangular: "DR",
35
+ priority_mail_express_flat_rate_envelope_post_office_to_addressee: "E4",
36
+ priority_mail_express_legal_flat_rate_envelope: "E6",
37
+ priority_mail_express_legal_flat_rate_envelope_sunday_holiday: "E7",
38
+ legal_flat_rate_envelope: "FA",
39
+ medium_flat_rate_box_large_flat_rate_bag: "FB",
40
+ flat_rate_envelope: "FE",
41
+ padded_flat_rate_envelope: "FP",
42
+ small_flat_rate_box: "FS",
43
+ usps_connect_same_day_single_piece: "L1",
44
+ usps_connect_same_day_small_flat_rate_bag: "L2",
45
+ usps_connect_same_day_large_flat_rate_bag: "L3",
46
+ usps_connect_same_day_flat_rate_box: "L4",
47
+ usps_connect_same_day_oversized: "L5",
48
+ usps_connect_local_single_piece: "LC",
49
+ flat_rate_box: "LF",
50
+ large_flat_rate_bag: "LL",
51
+ usps_connect_local_oversized: "LO",
52
+ small_flat_rate_bag: "LS",
53
+ non_presorted: "NP",
54
+ full_tray_box: "O1",
55
+ half_tray_box: "O2",
56
+ emm_tray_box: "O3",
57
+ flat_tub_tray_box: "O4",
58
+ surface_transported_pallet: "O5",
59
+ full_pallet_box: "O6",
60
+ half_pallet_box: "O7",
61
+ oversized: "OS",
62
+ cubic_soft_pack_tier_1: "P5",
63
+ cubic_soft_pack_tier_2: "P6",
64
+ cubic_soft_pack_tier_3: "P7",
65
+ cubic_soft_pack_tier_4: "P8",
66
+ cubic_soft_pack_tier_5: "P9",
67
+ cubic_soft_pack_tier_6: "Q6",
68
+ cubic_soft_pack_tier_7: "Q7",
69
+ cubic_soft_pack_tier_8: "Q8",
70
+ cubic_soft_pack_tier_9: "Q9",
71
+ cubic_soft_pack_tier_10: "Q0",
72
+ priority_mail_express_single_piece: "PA",
73
+ large_flat_rate_box: "PL",
74
+ large_flat_rate_box_apo_fpo_dpo: "PM",
75
+ presorted: "PR",
76
+ usps_connect_next_day_single_piece: "R1",
77
+ usps_connect_next_day_dimensional_nonrectangular: "R2",
78
+ usps_connect_next_day_dimensional_rectangular: "R3",
79
+ usps_connect_next_day_oversized: "R4",
80
+ small_flat_rate_bag_2: "SB",
81
+ scf_dimensional_nonrectangular: "SN",
82
+ single_piece: "SP",
83
+ scf_dimensional_rectangular: "SR"
84
+ }.freeze
85
+
86
+ PRICE_TYPES = {
87
+ retail: "RETAIL",
88
+ commercial: "COMMERCIAL",
89
+ contract: "CONTRACT"
90
+ }.freeze
91
+
92
+ # @return [String]
93
+ attr_reader :processing_category
94
+
95
+ # @return [String]
96
+ attr_reader :rate_indicator
97
+
98
+ # @return [String]
99
+ attr_reader :price_type
100
+
101
+ # @param processing_category [Symbol] one of {PROCESSING_CATEGORIES}
102
+ # @param rate_indicator [Symbol] one of {RATE_INDICATORS}
103
+ # @param price_type [Symbol] one of {PRICE_TYPES}
104
+ # @param kwargs [Hash]
105
+ # @option [String] :package_id the ID for the package that belongs to these options
106
+ # @option [Array<ItemOptions>] :item_options the options for items in this package
107
+ # @option [Class] :item_options_class the class to use for item options when none are provided
108
+ def initialize(
109
+ processing_category: :machinable,
110
+ rate_indicator: :single_piece,
111
+ price_type: :retail,
112
+ **kwargs
113
+ )
114
+ @processing_category = PROCESSING_CATEGORIES.fetch(processing_category)
115
+ @rate_indicator = RATE_INDICATORS.fetch(rate_indicator)
116
+ @price_type = PRICE_TYPES.fetch(price_type)
117
+ super(**kwargs)
118
+ end
119
+ end
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FriendlyShipping
4
+ module Services
5
+ class USPSShip
6
+ class SerializeRateEstimatesRequest
7
+ class << self
8
+ # Serialize a rate estimates request.
9
+ #
10
+ # @param shipment [Physical::Shipment]
11
+ # @param package [Physical::Package]
12
+ # @param options [RateEstimateOptions]
13
+ # @return [Hash]
14
+ def call(shipment:, package:, options:)
15
+ length, width, height = package.dimensions.sort.reverse
16
+ package_options = options.options_for_package(package)
17
+ {
18
+ originZIPCode: shipment.origin.zip,
19
+ destinationZIPCode: shipment.destination.zip,
20
+ weight: package.weight.convert_to(:lbs).value.to_f.round(2),
21
+ length: length.convert_to(:in).value.to_f.round(2),
22
+ width: width.convert_to(:in).value.to_f.round(2),
23
+ height: height.convert_to(:in).value.to_f.round(2),
24
+ mailClass: options.shipping_method.service_code,
25
+ processingCategory: processing_category(package, package_options),
26
+ rateIndicator: package_options.rate_indicator,
27
+ destinationEntryFacilityType: options.destination_entry_facility_type,
28
+ priceType: package_options.price_type,
29
+ mailingDate: options.mailing_date.strftime("%Y-%m-%d")
30
+ }
31
+ end
32
+
33
+ private
34
+
35
+ # If the processing category is machinable (or non-machinable), we can programmatically
36
+ # verify if the package is actually machinable (or non-machinable). If the processing
37
+ # category was specified incorrectly, we return the correct value instead.
38
+ #
39
+ # @param package [Physical::Package]
40
+ # @param package_options [RateEstimatePackageOptions]
41
+ # @return [String]
42
+ def processing_category(package, package_options)
43
+ if %w[MACHINABLE NON_MACHINABLE].include?(package_options.processing_category)
44
+ MachinablePackage.new(package).machinable? ? "MACHINABLE" : "NON_MACHINABLE"
45
+ else
46
+ package_options.processing_category
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FriendlyShipping
4
+ module Services
5
+ class USPSShip
6
+ SHIPPING_METHODS = [
7
+ ["BOUND_PRINTED_MATTER", "Bound Printed Matter"],
8
+ ["FIRST-CLASS_PACKAGE_RETURN_SERVICE", "First-Class Package Return Service"],
9
+ ["FIRST-CLASS_PACKAGE_SERVICE", "First-Class Package Service"],
10
+ ["GROUND_RETURN_SERVICE", "Ground Return Service"],
11
+ ["LIBRARY_MAIL", "Library Mail"],
12
+ ["MEDIA_MAIL", "Media Mail"],
13
+ ["PARCEL_SELECT", "Parcel Select"],
14
+ ["PARCEL_SELECT_LIGHTWEIGHT", "Parcel Select Lightweight"],
15
+ ["PRIORITY_MAIL", "Priority Mail"],
16
+ ["PRIORITY_MAIL_EXPRESS", "Priority Mail Express"],
17
+ ["PRIORITY_MAIL_EXPRESS_RETURN_SERVICE", "Priority Mail Express Return Service"],
18
+ ["PRIORITY_MAIL_RETURN_SERVICE", "Priority Mail Return Service"],
19
+ ["USPS_CONNECT_LOCAL", "USPS Connect Local"],
20
+ ["USPS_CONNECT_MAIL", "USPS Connect Mail"],
21
+ ["USPS_CONNECT_NEXT_DAY", "USPS Connect Next Day"],
22
+ ["USPS_CONNECT_REGIONAL", "USPS Connect Regional"],
23
+ ["USPS_CONNECT_SAME_DAY", "USPS Connect Same Day"],
24
+ ["USPS_GROUND_ADVANTAGE", "USPS Ground Advantage"],
25
+ ["USPS_GROUND_ADVANTAGE_RETURN_SERVICE", "USPS Ground Advantage Return Service"],
26
+ ["USPS_RETAIL_GROUND", "USPS Retail Ground"]
27
+ ].map do |code, name|
28
+ FriendlyShipping::ShippingMethod.new(
29
+ origin_countries: [Carmen::Country.coded("US")],
30
+ name: name,
31
+ service_code: code,
32
+ domestic: true,
33
+ international: false
34
+ )
35
+ end.freeze
36
+ end
37
+ end
38
+ end
@@ -2,8 +2,8 @@
2
2
 
3
3
  module FriendlyShipping
4
4
  module Services
5
- class ShipEngineLTL
6
- class BadRequest < ShipEngine::BadRequest; end
5
+ class USPSShip
6
+ TimingOptions = RateEstimateOptions
7
7
  end
8
8
  end
9
9
  end
@@ -0,0 +1,185 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'nokogiri'
4
+
5
+ module FriendlyShipping
6
+ module Services
7
+ class USPSShip
8
+ include Dry::Monads::Result::Mixin
9
+ include Dry::Monads::Do.for(:rate_estimates)
10
+
11
+ # @return [AccessToken] the access token
12
+ attr_reader :access_token
13
+
14
+ # @return [Boolean] whether to use the test API version
15
+ attr_reader :test
16
+
17
+ # @return [HttpClient] the HTTP client
18
+ attr_reader :client
19
+
20
+ # The USPS carrier
21
+ CARRIER = FriendlyShipping::Carrier.new(
22
+ id: 'usps',
23
+ name: 'United States Postal Service',
24
+ code: 'usps',
25
+ shipping_methods: SHIPPING_METHODS
26
+ )
27
+
28
+ # The base URL for USPS Ship requests
29
+ BASE_URL = 'https://api.usps.com'
30
+
31
+ # The USPS Ship API endpoints
32
+ RESOURCES = {
33
+ token: 'oauth2/v3/token',
34
+ rates: 'prices/v3/base-rates/search',
35
+ timings: 'service-standards/v3/estimates'
36
+ }.freeze
37
+
38
+ # @param access_token [AccessToken] the access token
39
+ # @param test [Boolean] whether to use the test API version
40
+ # @param client [HttpClient] optional HTTP client to use for requests
41
+ def initialize(access_token:, test: true, client: nil)
42
+ @access_token = access_token
43
+ @test = test
44
+ error_handler = ApiErrorHandler.new(api_error_class: USPSShip::ApiError)
45
+ @client = client || HttpClient.new(error_handler: error_handler)
46
+ end
47
+
48
+ # @return [Array<Carrier>]
49
+ def carriers
50
+ Success([CARRIER])
51
+ end
52
+
53
+ # Creates an access token that can be used for future API requests.
54
+ # @see https://developer.usps.com/api/81 OAuth 2.0 docs
55
+ #
56
+ # @param client_id [String] the Client ID of your application from the OAuth Client dialog
57
+ # @param client_secret [String] the secret you created in the OAuth Client Secrets section of the OAuth Client dialog
58
+ # @param grant_type [String] defaults to "client_credentials" to indicate you wish to obtain a token representing your confidential client application
59
+ # @param debug [Boolean] whether to append debug information to the API result
60
+ # @return [ApiResult<AccessToken>] the {AccessToken} wrapped in an {ApiResult} object
61
+ def create_access_token(
62
+ client_id:,
63
+ client_secret:,
64
+ grant_type: "client_credentials",
65
+ debug: false
66
+ )
67
+ request = FriendlyShipping::Request.new(
68
+ url: "#{BASE_URL}/#{RESOURCES[:token]}",
69
+ http_method: "POST",
70
+ body: "client_id=#{client_id}&" \
71
+ "client_secret=#{client_secret}&" \
72
+ "grant_type=#{grant_type}",
73
+ headers: {
74
+ Content_Type: "application/x-www-form-urlencoded",
75
+ Accept: "application/json"
76
+ },
77
+ debug: debug
78
+ )
79
+ client.post(request).fmap do |response|
80
+ hash = JSON.parse(response.body)
81
+ FriendlyShipping::ApiResult.new(
82
+ AccessToken.new(
83
+ token_type: hash['token_type'],
84
+ expires_in: hash['expires_in'],
85
+ raw_token: hash['access_token']
86
+ ),
87
+ original_request: request,
88
+ original_response: response
89
+ )
90
+ end
91
+ end
92
+
93
+ # Get rate estimates.
94
+ # @see https://developer.usps.com/api/73#tag/Resources/operation/post-base-rates-search API documentation
95
+ #
96
+ # NOTE: Since USPS Ship does not support returning multiple rates at the same time, we have to
97
+ # make multiple API calls for shipments with more than one package and sum the results.
98
+ #
99
+ # @param shipment [Physical::Shipment] the shipment for which we want to get rates
100
+ # @param options [RateEstimateOptions] options for obtaining rates for this shipment
101
+ # @param debug [Boolean] whether to append debug information to the API result
102
+ # @return [Result<ApiResult<Array<Rate>>>] the {Rate}s wrapped in an {ApiResult} object
103
+ def rate_estimates(shipment, options:, debug: false)
104
+ api_results = shipment.packages.map do |package|
105
+ yield begin
106
+ rate_request = SerializeRateEstimatesRequest.call(shipment: shipment, package: package, options: options)
107
+ request = build_request(api: :rates, payload: rate_request, debug: debug)
108
+
109
+ client.post(request).bind do |response|
110
+ ParseRateEstimatesResponse.call(response: response, request: request)
111
+ end
112
+ end
113
+ end
114
+
115
+ rates = api_results.flat_map(&:data)
116
+ amounts = rates.each_with_object({}) do |rate, result|
117
+ rate.amounts.each do |name, amount|
118
+ result[name] ||= 0
119
+ result[name] += amount
120
+ end
121
+ end
122
+
123
+ Success(
124
+ ApiResult.new(
125
+ [
126
+ FriendlyShipping::Rate.new(
127
+ amounts: amounts,
128
+ shipping_method: rates.first.shipping_method,
129
+ data: rates.first.data
130
+ )
131
+ ],
132
+ original_request: api_results.first.original_request,
133
+ original_response: api_results.first.original_response
134
+ )
135
+ )
136
+ end
137
+
138
+ # Get timing estimates.
139
+ # @see https://developer.usps.com/api/85#tag/Resources/operation/get-estimates API documentation
140
+ #
141
+ # @param shipment [Physical::Shipment] the shipment for which we want to get timings
142
+ # @param options [TimingOptions] options for the timing estimate call
143
+ # @return [Result<ApiResult<Array<Timing>>>] the {Timing}s wrapped in an {ApiResult} object
144
+ def timings(shipment, options:, debug: false)
145
+ request = FriendlyShipping::Request.new(
146
+ url: "#{BASE_URL}/#{RESOURCES[:timings]}?" \
147
+ "originZIPCode=#{shipment.origin.zip}&" \
148
+ "destinationZIPCode=#{shipment.destination.zip}&" \
149
+ "mailClass=#{options.shipping_method.service_code}&" \
150
+ "acceptanceDate=#{options.mailing_date.strftime('%Y-%m-%d')}",
151
+ http_method: "GET",
152
+ debug: debug,
153
+ headers: {
154
+ Accept: "application/json",
155
+ Authorization: "Bearer #{access_token.raw_token}"
156
+ }
157
+ )
158
+
159
+ client.get(request).bind do |response|
160
+ ParseTimingsResponse.call(response: response, request: request)
161
+ end
162
+ end
163
+
164
+ private
165
+
166
+ # @param api [Symbol]
167
+ # @param payload [Hash]
168
+ # @param debug [Boolean]
169
+ # @return [Request]
170
+ def build_request(api:, payload:, debug:)
171
+ FriendlyShipping::Request.new(
172
+ url: "#{BASE_URL}/#{RESOURCES[api]}",
173
+ http_method: "POST",
174
+ body: payload.to_json,
175
+ debug: debug,
176
+ headers: {
177
+ Content_Type: "application/json",
178
+ Accept: "application/json",
179
+ Authorization: "Bearer #{access_token.raw_token}"
180
+ }
181
+ )
182
+ end
183
+ end
184
+ end
185
+ end
@@ -1,7 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FriendlyShipping
4
+ # Base class for shipment options. Used when serializing API requests.
4
5
  class ShipmentOptions
6
+ # @param package_options [Array<PackageOptions>] the options for packages in this shipment
7
+ # @param package_options_class [Class] the class to use for package options when none are provided
5
8
  def initialize(
6
9
  package_options: Set.new,
7
10
  package_options_class: PackageOptions
@@ -10,6 +13,11 @@ module FriendlyShipping
10
13
  @package_options_class = package_options_class
11
14
  end
12
15
 
16
+ # Finds and returns package options for the given item. If options cannot be
17
+ # found, the `package_options_class` is used to construct new options.
18
+ #
19
+ # @param package [#id] the package for which to get options
20
+ # @return [PackageOptions]
13
21
  def options_for_package(package)
14
22
  package_options.detect do |package_option|
15
23
  package_option.package_id == package.id
@@ -18,6 +26,10 @@ module FriendlyShipping
18
26
 
19
27
  private
20
28
 
21
- attr_reader :package_options, :package_options_class
29
+ # @return [Array<PackageOptions>]
30
+ attr_reader :package_options
31
+
32
+ # @return [Class]
33
+ attr_reader :package_options_class
22
34
  end
23
35
  end