Class: Shipping::UpsFreight

Inherits:
Base
  • Object
show all
Defined in:
app/services/shipping/ups_freight.rb

Constant Summary collapse

DIR =
File.dirname(__FILE__)
WSDL_PATHS =
{
  rate: "wsdl/ups_freight/#{UPS_LTL_FREIGHT_RATE_WSDL}",
  ship: "wsdl/ups_freight/#{UPS_LTL_FREIGHT_SHIP_WSDL}"
}
ServiceTypes =
{
  'ups_freight_ltl' => '308',
  'ups_freight_ltl_guaranteed' => '309'
}
CODFundsCode =
{
  'check' => 'M',
  'no_check' => 'R'
}
FREIGHT_CLASS_BY_PCF =
{
  '500' => { lower: 0.0, upper: 0.5 },
  '400' => { lower: 0.5, upper: 1.0 },
  '300' => { lower: 1.0, upper: 2.0 },
  '250' => { lower: 2.0, upper: 3.0 },
  '200' => { lower: 3.0, upper: 4.0 },
  '175' => { lower: 4.0, upper: 5.0 },
  '150' => { lower: 5.0, upper: 6.0 },
  '125' => { lower: 6.0, upper: 7.0 },
  '110' => { lower: 7.0, upper: 8.0 },
  '100' => { lower: 8.0, upper: 9.0 },
  '92.5' => { lower: 9.0, upper: 10.5 },
  '85' => { lower: 10.5, upper: 12.0 },
  '77.5' => { lower: 12.0, upper: 13.5 },
  '70' => { lower: 13.5, upper: 15.0 },
  '65' => { lower: 15.0, upper: 22.5 },
  '60' => { lower: 22.5, upper: 30.0 },
  '55' => { lower: 30.0, upper: 35.0 },
  '50' => { lower: 35.0, upper: 50.0 }
}

Instance Attribute Summary

Attributes inherited from Base

#address, #address2, #address3, #address_residential, #attention_name, #billing_account, #billing_country, #billing_zip, #ci_comments, #city, #close_report_only, #cod_amount, #cod_collection_type, #company, #country, #currency_code, #data, #debug, #declared_value, #delivery_instructions, #delivery_total_value, #description, #discount_price, #dropoff_type, #email, #eta, #export_reason, #freight_class, #freightquote_authorization_url, #freightquote_client_id, #freightquote_client_secret, #freightquote_customer_code, #freightquote_events_url, #freightquote_rating_url, #freightquote_shipping_url, #freightquote_voiding_url, #handling_instructions, #has_loading_dock, #image_type, #include_first_class_mail_options, #insured_value, #is_construction_site, #is_trade_show, #label_type, #limited_access, #line_items, #master_tracking_number, #measure_height, #measure_length, #measure_units, #measure_width, #media_mail, #multiple_piece_shipping, #negotiated_rates, #package, #package_count, #package_sequence_number, #package_total, #packages, #packaging_type, #pay_type, #phone, #pickup_datetime, #pickup_instructions, #plain_response, #price, #rate_data, #reference_number_1, #reference_number_2, #reference_number_3, #reference_number_code_1, #reference_number_code_2, #required, #requires_appointment, #requires_inside_delivery, #requires_liftgate, #response, #return_to_address, #return_to_address2, #return_to_address3, #return_to_address_residential, #return_to_attention_name, #return_to_city, #return_to_company, #return_to_country, #return_to_email, #return_to_has_loading_dock, #return_to_is_construction_site, #return_to_is_trade_show, #return_to_limited_access, #return_to_name, #return_to_phone, #return_to_requires_appointment, #return_to_requires_inside_delivery, #return_to_requires_liftgate, #return_to_state, #return_to_zip, #rl_carriers_api_key, #rl_carriers_shipping_url, #saturday_delivery, #sender_address, #sender_address2, #sender_address3, #sender_address_residential, #sender_attention_name, #sender_city, #sender_company, #sender_country, #sender_email, #sender_has_loading_dock, #sender_is_construction_site, #sender_is_trade_show, #sender_limited_access, #sender_name, #sender_phone, #sender_requires_appointment, #sender_requires_inside_delivery, #sender_requires_liftgate, #sender_state, #sender_tax_identification_number, #sender_zip, #service_code, #service_type, #services, #ship_date, #shipengine_api_key, #shipengine_canadapost_account_id, #shipengine_canadapost_parent_account_number, #shipengine_canpar_account_id, #shipengine_dhl_express_account_id, #shipengine_fed_ex_account_id, #shipengine_fed_ex_ca_account_id, #shipengine_purolator_account_id, #shipengine_ups_account_id, #shipengine_ups_ca_account_id, #shipengine_usps_account_id, #shipper_address, #shipper_address2, #shipper_address3, #shipper_address_residential, #shipper_attention_name, #shipper_city, #shipper_company, #shipper_country, #shipper_email, #shipper_has_loading_dock, #shipper_is_construction_site, #shipper_is_trade_show, #shipper_limited_access, #shipper_name, #shipper_phone, #shipper_requires_appointment, #shipper_requires_inside_delivery, #shipper_requires_liftgate, #shipper_state, #shipper_zip, #signature_confirmation, #skip_png_download, #skip_rate_test, #special_instructions, #state, #tax_identification_number, #time_in_transit, #total_shipment_weight, #transaction_type, #weight, #weight_units, #zip

Instance Method Summary collapse

Methods inherited from Base

#fedex, #initialize, #purolator, state_from_zip, #ups, #ups_freight

Constructor Details

This class inherits a constructor from Shipping::Base

Instance Method Details

#find_ratesObject



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'app/services/shipping/ups_freight.rb', line 69

def find_rates
  logger ||= Rails.logger
  @required = %i[zip country sender_company sender_state sender_zip sender_country packages]
  @required += %i[ups_license_number ups_user ups_password ups_shipper_number]

  @country ||= 'US'
  @sender_country ||= 'US'

  # see: https://stackoverflow.com/questions/4394620/how-do-i-use-savon-nested-attributes-hash/28462391#28462391
  ups_security = { 'n1:UPSSecurity' => {
    '@xmlns:n1' => 'http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0',
    '@env:mustUnderstand' => '0',
    'n1:UsernameToken' => { 'n1:Username' => @ups_user, 'n1:Password' => @ups_password },
    'n1:ServiceAccessToken' => { 'n1:AccessLicenseNumber' => @ups_license_number }
  } }

  # path = File.expand_path(DIR + '/' + WSDL_PATHS[:rate])
  # # logger.info "create_driver, path: #{path}"
  # wsdl = SOAP::WSDLDriverFactory.new(path)
  # driver = wsdl.create_rpc_driver
  # driver.wiredump_dev = STDOUT # if @debug
  # driver.headerhandler << UpssAuthHeader.new(ups_security)
  # driver.return_response_as_xml = true

  freight_rate_request = {}
  freight_rate_request['n3:Request'] = { 'n3:RequestOption' => '1' } # 1 = Ground, 2 = Air
  freight_rate_request[:ShipFrom] = {}
  freight_rate_request[:ShipFrom][:Name] = @sender_company[0..34]
  freight_rate_request[:ShipFrom][:Address] = {}
  freight_rate_request[:ShipFrom][:Address][:AddressLine] = get_address_line_array(@sender_address, @sender_address2)
  freight_rate_request[:ShipFrom][:Address][:City] = @sender_city # required
  freight_rate_request[:ShipFrom][:Address][:StateProvinceCode] = @sender_state # required
  freight_rate_request[:ShipFrom][:Address][:PostalCode] = @sender_zip # required
  freight_rate_request[:ShipFrom][:Address][:CountryCode] = @sender_country # required
  freight_rate_request[:ShipFrom][:AttentionName] = @sender_attention_name[0..34] if @sender_attention_name.present?

  freight_rate_request[:ShipTo] = {}
  freight_rate_request[:ShipTo][:Name] = (@company || ' ')[0..34] # required
  freight_rate_request[:ShipTo][:Address] = {}
  freight_rate_request[:ShipTo][:Address][:AddressLine] = get_address_line_array(@address, @address2)
  freight_rate_request[:ShipTo][:Address][:City] = (@city || ' ')[0..29] # required
  freight_rate_request[:ShipTo][:Address][:StateProvinceCode] = (state || ' ') # required
  freight_rate_request[:ShipTo][:Address][:PostalCode] = @zip
  freight_rate_request[:ShipTo][:Address][:CountryCode] = @country
  freight_rate_request[:ShipTo][:AttentionName] = @attention_name[0..34] if @attention_name.present?
  freight_rate_request[:PaymentInformation] = {}
  freight_rate_request[:PaymentInformation][:Payer] = {}
  freight_rate_request[:PaymentInformation][:Payer][:Name] = @sender_company[0..34]
  freight_rate_request[:PaymentInformation][:Payer][:Address] = {}
  freight_rate_request[:PaymentInformation][:Payer][:Address][:AddressLine] = get_address_line_array(@sender_address, @sender_address2)
  freight_rate_request[:PaymentInformation][:Payer][:Address][:City] = @sender_city # required
  freight_rate_request[:PaymentInformation][:Payer][:Address][:StateProvinceCode] = @sender_state # required
  freight_rate_request[:PaymentInformation][:Payer][:Address][:PostalCode] = @sender_zip # required
  freight_rate_request[:PaymentInformation][:Payer][:Address][:CountryCode] = @sender_country # required
  freight_rate_request[:PaymentInformation][:Payer][:ShipperNumber] = @ups_shipper_number
  freight_rate_request[:PaymentInformation][:Payer][:AttentionName] = @sender_attention_name[0..34] if @attention_name.present?
  freight_rate_request[:PaymentInformation][:ShipmentBillingOption] = {}
  freight_rate_request[:PaymentInformation][:ShipmentBillingOption][:Code] = '10' # Prepaid
  freight_rate_request[:PaymentInformation][:ShipmentBillingOption][:Description] = 'Prepaid'

  freight_rate_request[:Service] = {}
  freight_rate_request[:Service][:Code] = @service_code || ServiceTypes[@service_type] || '308' # default to ltl (not guaranteed)
  freight_rate_request[:Service][:Description] = "UPS Ground Freight LTL#{' Guaranteed' if freight_rate_request[:Service][:Code] == '309'}"
  # We generally use pallets when shipping LTL, # there are some complex rules about this in the spec, ie first handling unit must be a skid or pallet, loose boxes can only be the second handling unit. So we will let this one be, regardless of the actual freight packaging
  freight_rate_request[:HandlingUnitOne] = {}
  freight_rate_request[:HandlingUnitOne][:Quantity] = @packages.select { |p| p.pallet? }.length # Here we assume we have at least one pallet
  freight_rate_request[:HandlingUnitOne][:Type] = {}
  freight_rate_request[:HandlingUnitOne][:Type][:Code] = 'PLT'
  freight_rate_request[:Commodity] = []
  imperial = %w[US LR MM].include?(@sender_country)
  imperial = true if @sender_country.blank?
  tot_weight = 0.0
  @packages.each_with_index do |package, i|
    freight_rate_request[:Commodity] << {}
    # logger.info "imperial: #{imperial}"
    # logger.info "package.lbs: #{package.lbs}"
    # logger.info "package.kgs: #{package.kgs}"
    value = (imperial ? package.lbs : package.kgs)
    # logger.info "value: #{value}"
    package_weight = [value, 1.0].max
    tot_weight += package_weight
    # logger.info "package_weight: #{package_weight}"
    freight_rate_request[:Commodity][i][:Description] = 'Radiant Heating Elements and Controls'
    freight_rate_request[:Commodity][i][:Weight] = {}
    freight_rate_request[:Commodity][i][:Weight][:Value] = package_weight.to_f.round(2) # 2 decimals
    freight_rate_request[:Commodity][i][:Weight][:UnitOfMeasurement] = {}
    freight_rate_request[:Commodity][i][:Weight][:UnitOfMeasurement][:Code] = (imperial ? 'LBS' : 'KGS')
    value = (imperial ? package.inches(:length) : package.cm(:length))
    package_length = [value, 0.1].max
    value = (imperial ? package.inches(:width) : package.cm(:width))
    package_width = [value, 0.1].max
    value = (imperial ? package.inches(:height) : package.cm(:height))
    package_height = [value, 0.1].max
    freight_rate_request[:Commodity][i][:Dimensions] = {}
    freight_rate_request[:Commodity][i][:Dimensions][:UnitOfMeasurement] = {}
    freight_rate_request[:Commodity][i][:Dimensions][:UnitOfMeasurement][:Code] = (imperial ? 'IN' : 'CM')
    freight_rate_request[:Commodity][i][:Dimensions][:Length] = package_length.to_f.round(2) # 2 decimals
    freight_rate_request[:Commodity][i][:Dimensions][:Width] = package_width.to_f.round(2) # 2 decimals
    freight_rate_request[:Commodity][i][:Dimensions][:Height] = package_height.to_f.round(2) # 2 decimals
    freight_rate_request[:Commodity][i][:NumberOfPieces] = 1
    freight_rate_request[:Commodity][i][:PackagingType] = {}
    freight_rate_request[:Commodity][i][:PackagingType][:Code] = if package.pallet?
                                                                   'PLT'
                                                                 else
                                                                   (package.crate? ? 'CRT' : 'CTN')
                                                                 end
    freight_rate_request[:Commodity][i][:FreightClass] = get_freight_class_from_package(package)
    freight_rate_request[:Commodity][i][:NMFCCommodityCode] = package.nmfc_code if package.nmfc_code.present?
  end

  if @limited_access || @requires_appointment || @requires_liftgate || @saturday_delivery || @address_residential || @requires_inside_delivery || @is_construction_site || @cod_amount || @insured_value
    freight_rate_request[:ShipmentServiceOptions] = {}
    if @limited_access || @requires_appointment || @requires_liftgate || @saturday_delivery || @address_residential || @requires_inside_delivery || @is_construction_site
      freight_rate_request[:ShipmentServiceOptions][:DeliveryOptions] = {}
      freight_rate_request[:ShipmentServiceOptions][:DeliveryOptions][:LiftGateRequiredIndicator] = '' if @requires_liftgate
      freight_rate_request[:ShipmentServiceOptions][:DeliveryOptions][:SaturdayDeliveryIndicator] = '' if @saturday_delivery
      freight_rate_request[:ShipmentServiceOptions][:DeliveryOptions][:ResidentialDeliveryIndicator] = '' if @address_residential # Here we will assume the following service options if the address is residential
      freight_rate_request[:ShipmentServiceOptions][:DeliveryOptions][:InsideDeliveryIndicator] = '' if @requires_inside_delivery
      freight_rate_request[:ShipmentServiceOptions][:DeliveryOptions][:ConstructionSiteDeliveryIndicator] = '' if @is_construction_site
      freight_rate_request[:ShipmentServiceOptions][:DeliveryOptions][:CallBeforeDeliveryIndicator] = '' if @requires_appointment && !@address_residential
      freight_rate_request[:ShipmentServiceOptions][:DeliveryOptions][:LimitedAccessDeliveryIndicator] = '' if @limited_access
    end
    if @cod_amount
      freight_rate_request[:ShipmentServiceOptions][:COD] = {}
      freight_rate_request[:ShipmentServiceOptions][:COD][:CODValue] = {}
      freight_rate_request[:ShipmentServiceOptions][:COD][:CODValue][:CurrencyCode] = @currency_code || 'USD'
      freight_rate_request[:ShipmentServiceOptions][:COD][:CODValue][:MonetaryValue] = format('%.2f', @cod_amount)
      freight_rate_request[:ShipmentServiceOptions][:COD][:CODPaymentMethod] = {}
      freight_rate_request[:ShipmentServiceOptions][:COD][:CODPaymentMethod][:Code] = CODFundsCode[@cod_collection_type] || 'R' # default to ‘R’ = cashier’s check or money order - no cash allowed
      freight_rate_request[:ShipmentServiceOptions][:COD][:CODBillingOption] = {}
      freight_rate_request[:ShipmentServiceOptions][:COD][:CODBillingOption][:Code] = '01' # Prepaid only we don't do freight collect
      freight_rate_request[:ShipmentServiceOptions][:COD][:RemitTo] = {}
      freight_rate_request[:ShipmentServiceOptions][:COD][:RemitTo][:Name] = @sender_company[0..34]
      freight_rate_request[:ShipmentServiceOptions][:COD][:RemitTo][:Address] = {}
      freight_rate_request[:ShipmentServiceOptions][:COD][:RemitTo][:Address][:AddressLine] = get_address_line_array(@sender_address, @sender_address2)
      freight_rate_request[:ShipmentServiceOptions][:COD][:RemitTo][:Address][:City] = @sender_city[0..29] # required
      freight_rate_request[:ShipmentServiceOptions][:COD][:RemitTo][:Address][:StateProvinceCode] = @sender_state # required
      freight_rate_request[:ShipmentServiceOptions][:COD][:RemitTo][:Address][:PostalCode] = @sender_zip # required
      freight_rate_request[:ShipmentServiceOptions][:COD][:RemitTo][:Address][:CountryCode] = @sender_country # required
      freight_rate_request[:ShipmentServiceOptions][:COD][:RemitTo][:AttentionName] = @sender_attention_name[0..34] if @sender_attention_name.present?
    end
    if @insured_value
      @insured_value = tot_weight * 2.5 if @insured_value.to_f > tot_weight * 2.5 # UPS Freight limits declared value liability to $2.50 per lbs
      @insured_value = 100_000.0 if @insured_value.to_f > 100_000.0 # UPS Freight limits this to 100000.0
      freight_rate_request[:ShipmentServiceOptions][:DeclaredValue] = {}
      freight_rate_request[:ShipmentServiceOptions][:DeclaredValue][:CurrencyCode] = @currency_code || 'USD'
      freight_rate_request[:ShipmentServiceOptions][:DeclaredValue][:MonetaryValue] = format('%.2f', @insured_value)
    end
  end

  # rate_options = {:FreightRateRequest => freight_rate_request}
  # logger.info "Shipping UPS LTL freight find_rates request/response:" # driver.wiredump_dev = STDOUT will have it trace the request/response
  # res = driver.ProcessFreightRate(freight_rate_request, ups_security)
  # result = REXML::Document.new("<?xml version='1.0'?>#{res}")
  # rates = []
  # rate_estimates = []
  # successful, msg = nil

  # if (REXML::XPath.first(result, "soapenv:Envelope/soapenv:Body/freightRate:FreightRateResponse/common:Response/common:ResponseStatus/common:Code").text rescue nil) == "1"
  #   successful = true
  #   msg = ""
  # #elsif handle soap fault...
  # else
  #   successful = false
  #   msg = (REXML::XPath.first(result, "soapenv:Envelope/soapenv:Body/freightRate:FreightRateResponse/common:Response/common:Alert/common:Description").text rescue nil) || "No shipping rates could be found for the destination address"
  # end

  ups_freight_observer = Observer.new
  Savon.observers << ups_freight_observer

  service_key = :rate
  client = get_client(service_key, ups_security.deep_stringify_keys)

  logger.info 'Shipping UPSFreight find_rates request:'
  request_str = String.new
  rate_options = freight_rate_request.deep_stringify_keys
  begin
    savon_response = client.call(:process_freight_rate, message: rate_options, attributes: { 'xmlns:frt' => 'http://www.ups.com/XMLSchema/XOLTWS/FreightRate/v1.0', 'xmlns:n3' => 'http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0' })
    request_str = ups_freight_observer.request_xml
    Savon.observers.clear
    logger.info "#{request_str}"
  rescue Savon::Error => e
    request_str = ups_freight_observer.request_xml
    Savon.observers.clear
    logger.info "Shipping UPSFreight find_rates request, ERROR: #{e.to_hash}"
    logger.info "#{request_str}"
    response = { success: false, message: "UPSFreight: #{e.to_hash}", request: request_str, xml: '' }
    def response.method_missing(name, *args)
      has_key?(name) ? self[name] : super
    end
    return response
  end

  logger.debug 'Shipping UPSFreight find_rates response received'

  rate_estimates = []
  successful, msg = nil
  result = REXML::Document.new("<?xml version='1.0'?>#{savon_response.to_xml}")

  if begin
    REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightRate:FreightRateResponse/common:Response/common:ResponseStatus/common:Code').text
  rescue StandardError
    nil
  end == '1'
    successful = true
    msg = ''
  # elsif handle soap fault...
  else
    successful = false
    msg = begin
      REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightRate:FreightRateResponse/common:Response/common:Alert/common:Description').text
    rescue StandardError
      nil
    end || 'No shipping rates could be found for the destination address'
  end

  if successful
    service_code = REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightRate:FreightRateResponse/freightRate:Service/freightRate:Code').text
    price = REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightRate:FreightRateResponse/freightRate:TotalShipmentCharge/freightRate:MonetaryValue').text.to_f
    currency = REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightRate:FreightRateResponse/freightRate:TotalShipmentCharge/freightRate:CurrencyCode').text
    rate_schedule_code = REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightRate:FreightRateResponse/freightRate:RatingSchedule/freightRate:Code').text
    if price and currency and service_code
      special_options_codes = %w[HOL_WE_PU_DEL COD] # these are considered non-transportation service options charges for our purposes
      service_options_charges = 0.0
      REXML::XPath.each(result, 'soapenv:Envelope/soapenv:Body/freightRate:FreightRateResponse/freightRate:Rate') do |fr|
        rate_code = REXML::XPath.first(fr, 'freightRate:Type/freightRate:Code').text
        rate_amount = REXML::XPath.first(fr, 'freightRate:Factor/freightRate:Value').text.to_f
        # logger.info "Rate code: #{rate_code}, amount: #{rate_amount}"
        if special_options_codes.include?(rate_code)
          service_options_charges += rate_amount
          # logger.info "Rate code: #{rate_code}, amount: #{rate_amount} added to service_options_charges: #{service_options_charges}"
        end
      end
      transportation_charges = price - service_options_charges
      estimate = {}
      estimate[:service_code] = service_code
      estimate[:price] = price
      estimate[:transportation_charges] = transportation_charges
      estimate[:service_options_charges] = service_options_charges
      estimate[:insured_value] = @insured_value.to_f.round(2)
      estimate[:currency] = currency
      # allows for things like estimate.service_code
      def estimate.method_missing(name, *args)
        has_key?(name) ? self[name] : super
      end
      rate_estimates << estimate
    end
  end

  response = {}
  response[:success] = successful
  response[:message] = "UPS LTL Freight: #{msg}"
  response[:request] = freight_rate_request.inspect.to_s
  response[:xml] = result.to_s
  response[:rates] = rate_estimates

  # allows for things like fedex.success?
  def response.method_missing(name, *args)
    has_key?(name) ? self[name] : super
  end

  # logger.info "Shipping UPS find_rates response:"
  # logger.info "#{response.inspect}"

  response
end

#get_address_line_array(add1, add2) ⇒ Object



804
805
806
807
808
# File 'app/services/shipping/ups_freight.rb', line 804

def get_address_line_array(add1, add2)
  res = [(add1.blank? ? nil : add1[0..34]), (add2.blank? ? nil : add2[0..34])].compact
  res = res.first if res.length == 1
  res
end

#get_client(service_key, ups_security) ⇒ Object



810
811
812
813
# File 'app/services/shipping/ups_freight.rb', line 810

def get_client(service_key, ups_security)
  path = File.expand_path(DIR + '/' + WSDL_PATHS[service_key])
  Savon.client(wsdl: File.expand_path(path, __FILE__), element_form_default: :qualified, ssl_verify_mode: :none, ssl_version: :TLSv1_2, soap_header: ups_security)
end

#get_freight_class_from_package(package) ⇒ Object



792
793
794
795
796
797
798
799
800
801
802
# File 'app/services/shipping/ups_freight.rb', line 792

def get_freight_class_from_package(package)
  # get total weight in lbs and cubic feet of package, and figure out density in lbs per cubic foot or PCF
  total_weight = package.lbs.to_f
  total_cubic_ft = package.inches(:length).to_f * package.inches(:width).to_f * package.inches(:height).to_f / 1728.0
  pcf = total_weight / total_cubic_ft
  UpsFreight::FREIGHT_CLASS_BY_PCF.each do |freight_class, pcf_limits|
    return freight_class if pcf >= pcf_limits[:lower] and pcf < pcf_limits[:upper]
  end
  # worst case return the highest freight class
  UpsFreight::FREIGHT_CLASS_BY_PCF.to_a.last.first.to_f
end

#label(return_label = false, logger = nil) ⇒ Object

Raises:



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
# File 'app/services/shipping/ups_freight.rb', line 336

def label(return_label = false, logger = nil)
  logger ||= Rails.logger
  # Ground Freight does not offer void, label recovery or return services.

  international_shipment = false
  international_shipment = true if @sender_country and @country and (@sender_country != @country)

  @required = %i[ups_license_number ups_shipper_number ups_user ups_password]
  @required += %i[phone company address city state zip]
  @required += %i[sender_phone sender_email sender_company sender_address sender_city sender_state sender_zip]
  @required += [:sender_email]
  @required += [:packages]
  @required += [:line_items] if international_shipment

  @country ||= 'US'
  @sender_country ||= 'US'

  ups_security = { 'n1:UPSSecurity' => {
    '@xmlns:n1' => 'http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0',
    '@env:mustUnderstand' => '0',
    'n1:UsernameToken' => { 'n1:Username' => @ups_user, 'n1:Password' => @ups_password },
    'n1:ServiceAccessToken' => { 'n1:AccessLicenseNumber' => @ups_license_number }
  } }

  # path = File.expand_path(DIR + '/' + WSDL_PATHS[:ship])
  # #logger.info "create_driver, path: #{path}"
  # wsdl = SOAP::WSDLDriverFactory.new(path)
  # driver = wsdl.create_rpc_driver
  # driver.wiredump_dev = STDOUT # if @debug
  # driver.headerhandler << UpssAuthHeader.new(ups_security)
  # driver.return_response_as_xml = true

  freight_ship_request = {}
  freight_ship_request['n3:Request'] = { 'n3:RequestOption' => '1' } # 1 = Ground, 2 = Air
  freight_ship_request[:Shipment] = {}
  freight_ship_request[:Shipment][:ShipFrom] = {}
  freight_ship_request[:Shipment][:ShipFrom][:Name] = @sender_company[0..34]
  freight_ship_request[:Shipment][:ShipFrom][:TaxIdentificationNumber] = @sender_tax_identification_number[0..14] if @sender_tax_identification_number.present?
  freight_ship_request[:Shipment][:ShipFrom][:Address] = {}
  freight_ship_request[:Shipment][:ShipFrom][:Address][:AddressLine] = get_address_line_array(@sender_address, @sender_address2)
  freight_ship_request[:Shipment][:ShipFrom][:Address][:City] = @sender_city[0..29] # required
  freight_ship_request[:Shipment][:ShipFrom][:Address][:StateProvinceCode] = @sender_state # required
  freight_ship_request[:Shipment][:ShipFrom][:Address][:PostalCode] = @sender_zip # required
  freight_ship_request[:Shipment][:ShipFrom][:Address][:CountryCode] = @sender_country # required
  freight_ship_request[:Shipment][:ShipFrom][:AttentionName] = (@sender_attention_name || 'Warehouse Staff')[0..34] # required
  freight_ship_request[:Shipment][:ShipFrom][:Phone] = {}
  freight_ship_request[:Shipment][:ShipFrom][:Phone][:Number] = @sender_phone
  freight_ship_request[:Shipment][:ShipFrom][:EMailAddress] = @sender_email[0..49]
  freight_ship_request[:Shipment][:ShipperNumber] = @ups_shipper_number

  freight_ship_request[:Shipment][:ShipTo] = {}
  freight_ship_request[:Shipment][:ShipTo][:Name] = @company[0..34] # required
  freight_ship_request[:Shipment][:ShipTo][:Address] = {}
  freight_ship_request[:Shipment][:ShipTo][:Address][:AddressLine] = get_address_line_array(@address, @address2)
  freight_ship_request[:Shipment][:ShipTo][:Address][:City] = @city[0..29] # required
  freight_ship_request[:Shipment][:ShipTo][:Address][:StateProvinceCode] = @state # required
  freight_ship_request[:Shipment][:ShipTo][:Address][:PostalCode] = @zip
  freight_ship_request[:Shipment][:ShipTo][:Address][:CountryCode] = @country
  freight_ship_request[:Shipment][:ShipTo][:AttentionName] = (@attention_name || 'Customer')[0..34] # required
  freight_ship_request[:Shipment][:ShipTo][:Phone] = {}
  freight_ship_request[:Shipment][:ShipTo][:Phone][:Number] = @phone || @sender_phone # required
  freight_ship_request[:Shipment][:ShipTo][:EMailAddress] = (@email || @sender_email)[0..49] # required

  freight_ship_request[:Shipment][:PaymentInformation] = {}
  freight_ship_request[:Shipment][:PaymentInformation][:Payer] = {}
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:Name] = @sender_company[0..34]
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:Address] = {}
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:Address][:AddressLine] = get_address_line_array(@sender_address, @sender_address2)
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:Address][:City] = @sender_city[0..29] # required
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:Address][:StateProvinceCode] = @sender_state # required
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:Address][:PostalCode] = @sender_zip # required
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:Address][:CountryCode] = @sender_country # required
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:ShipperNumber] = @ups_shipper_number
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:AttentionName] = (@sender_attention_name || 'Warehouse Staff')[0..34]
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:Phone] = {}
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:Phone][:Number] = @sender_phone
  freight_ship_request[:Shipment][:PaymentInformation][:Payer][:EMailAddress] = @sender_email[0..49]
  freight_ship_request[:Shipment][:PaymentInformation][:ShipmentBillingOption] = {}
  freight_ship_request[:Shipment][:PaymentInformation][:ShipmentBillingOption][:Code] = '10' # Prepaid
  freight_ship_request[:Shipment][:PaymentInformation][:ShipmentBillingOption][:Description] = 'Prepaid'

  freight_ship_request[:Shipment][:Service] = {}
  freight_ship_request[:Shipment][:Service][:Code] = @service_code || ServiceTypes[@service_type] || '308' # default to ltl (not guaranteed)
  freight_ship_request[:Shipment][:Service][:Description] = "UPS Ground Freight LTL #{'Guaranteed' unless freight_ship_request[:Shipment][:Service][:Code] == '309'}"
  # We generally use pallets when shipping LTL, # there are some complex rules about this in the spec, ie first handling unit must be a skid or pallet, loose boxes can only be the second handling unit. So we will let this one be, regardless of the actual freight packaging
  freight_ship_request[:Shipment][:HandlingUnitOne] = {}
  freight_ship_request[:Shipment][:HandlingUnitOne][:Quantity] = @packages.select { |p| p.pallet? }.length # Here we assume we have at least one pallet
  freight_ship_request[:Shipment][:HandlingUnitOne][:Type] = {}
  freight_ship_request[:Shipment][:HandlingUnitOne][:Type][:Code] = 'PLT'
  freight_ship_request[:Shipment][:Commodity] = []
  imperial = %w[US LR MM].include?(@sender_country)
  imperial = true if @sender_country.blank?
  tot_weight = 0.0
  @packages.each_with_index do |package, i|
    freight_ship_request[:Shipment][:Commodity] << {}
    freight_ship_request[:Shipment][:Commodity][i][:Description] = 'Radiant Heating Elements and Controls'
    value = (imperial ? package.lbs : package.kgs)
    package_weight = [value, 1.0].max
    tot_weight += package_weight
    freight_ship_request[:Shipment][:Commodity][i][:Weight] = {}
    freight_ship_request[:Shipment][:Commodity][i][:Weight][:Value] = package_weight.to_f.round(2) # 2 decimals
    freight_ship_request[:Shipment][:Commodity][i][:Weight][:UnitOfMeasurement] = {}
    freight_ship_request[:Shipment][:Commodity][i][:Weight][:UnitOfMeasurement][:Code] = (imperial ? 'LBS' : 'KGS')
    value = (imperial ? package.inches(:length) : package.cm(:length))
    package_length = [value, 0.1].max
    value = (imperial ? package.inches(:width) : package.cm(:width))
    package_width = [value, 0.1].max
    value = (imperial ? package.inches(:height) : package.cm(:height))
    package_height = [value, 0.1].max
    freight_ship_request[:Shipment][:Commodity][i][:Dimensions] = {}
    freight_ship_request[:Shipment][:Commodity][i][:Dimensions][:UnitOfMeasurement] = {}
    freight_ship_request[:Shipment][:Commodity][i][:Dimensions][:UnitOfMeasurement][:Code] = (imperial ? 'IN' : 'CM')
    freight_ship_request[:Shipment][:Commodity][i][:Dimensions][:Length] = package_length.to_f.round(2) # 2 decimals
    freight_ship_request[:Shipment][:Commodity][i][:Dimensions][:Width] = package_width.to_f.round(2) # 2 decimals
    freight_ship_request[:Shipment][:Commodity][i][:Dimensions][:Height] = package_height.to_f.round(2) # 2 decimals
    freight_ship_request[:Shipment][:Commodity][i][:NumberOfPieces] = 1
    freight_ship_request[:Shipment][:Commodity][i][:PackagingType] = {}
    freight_ship_request[:Shipment][:Commodity][i][:PackagingType][:Code] = if package.pallet?
                                                                              'PLT'
                                                                            else
                                                                              (package.crate? ? 'CRT' : 'CTN')
                                                                            end
    freight_ship_request[:Shipment][:Commodity][i][:FreightClass] = get_freight_class_from_package(package) # required
    freight_ship_request[:Shipment][:Commodity][i][:NMFCCommodityCode] = package.nmfc_code if package.nmfc_code.present?
  end
  if @reference_number_1.present?
    freight_ship_request[:Shipment][:Reference] = []
    freight_ship_request[:Shipment][:Reference] << {}
    freight_ship_request[:Shipment][:Reference][0][:Number] = {}
    freight_ship_request[:Shipment][:Reference][0][:Number][:Code] = '28' # only for PO and SO
    freight_ship_request[:Shipment][:Reference][0][:Number][:Value] = @reference_number_1[0..34]
    if @reference_number_2.present?
      freight_ship_request[:Shipment][:Reference] << {}
      freight_ship_request[:Shipment][:Reference][1][:Number] = {}
      freight_ship_request[:Shipment][:Reference][1][:Number][:Code] = 'OTHER' # only for PO and SO
      freight_ship_request[:Shipment][:Reference][1][:Number][:Value] = @reference_number_2[0..34]
    end
  end

  freight_ship_request[:Shipment][:PickupRequest] = {}
  freight_ship_request[:Shipment][:PickupRequest][:Requester] = {}
  freight_ship_request[:Shipment][:PickupRequest][:Requester][:AttentionName] = (@sender_attention_name || 'Warehouse Staff')[0..34]
  freight_ship_request[:Shipment][:PickupRequest][:Requester][:EMailAddress] = @sender_email
  freight_ship_request[:Shipment][:PickupRequest][:Requester][:Name] = @sender_company[0..34]
  freight_ship_request[:Shipment][:PickupRequest][:Requester][:Phone] = {}
  freight_ship_request[:Shipment][:PickupRequest][:Requester][:Phone][:Number] = @sender_phone
  date = ''
  et = ''
  lt = ''
  pickup_dt = @pickup_datetime
  Time.use_zone('America/Chicago') do
    pickup_dt = 30.minutes.from_now if pickup_dt.nil?
    if pickup_dt > Time.zone.parse('3:00pm') # needs to be before 3pm for same day, if after then go to next business day at 10am
      e = Employee.find(105) # Julia Billen, this is to find a non holiday business day
      pickup_dt = Time.zone.parse("#{(e.next_business_day || 1.working.day.from_now).strftime('%Y%m%d')} 1000")
    end
    latest_pickup_dt = pickup_dt + 91.minutes # need 90 minute window at least
    if latest_pickup_dt < (new_lpdt = Time.zone.parse("#{latest_pickup_dt.strftime('%Y%m%d')} 18:00"))
      latest_pickup_dt = new_lpdt
    end
    date = pickup_dt.strftime('%Y%m%d')
    et = pickup_dt.strftime('%H%M')
    lt = latest_pickup_dt.strftime('%H%M')
  end
  freight_ship_request[:Shipment][:PickupRequest][:PickupDate] = date
  freight_ship_request[:Shipment][:PickupRequest][:EarliestTimeReady] = et
  freight_ship_request[:Shipment][:PickupRequest][:LatestTimeReady] = lt

  freight_ship_request[:Shipment][:Documents] = {}
  freight_ship_request[:Shipment][:Documents][:Image] = []
  freight_ship_request[:Shipment][:Documents][:Image] << {}
  freight_ship_request[:Shipment][:Documents][:Image][0][:Type] = {}
  freight_ship_request[:Shipment][:Documents][:Image][0][:Type][:Code] = '20' # UPS Bill Of Lading (BOL)
  freight_ship_request[:Shipment][:Documents][:Image][0][:Format] = {}
  freight_ship_request[:Shipment][:Documents][:Image][0][:Format][:Code] = '01' # PDF
  freight_ship_request[:Shipment][:Documents][:Image] << {}
  freight_ship_request[:Shipment][:Documents][:Image][1][:Type] = {}
  freight_ship_request[:Shipment][:Documents][:Image][1][:Type][:Code] = '30' # UPS Label
  freight_ship_request[:Shipment][:Documents][:Image][1][:LabelsPerPage] = '1'
  freight_ship_request[:Shipment][:Documents][:Image][1][:Format] = {}
  freight_ship_request[:Shipment][:Documents][:Image][1][:Format][:Code] = '01' # PDF
  freight_ship_request[:Shipment][:Documents][:Image][1][:PrintFormat] = {}
  freight_ship_request[:Shipment][:Documents][:Image][1][:PrintFormat][:Code] = '02' # Thermal
  freight_ship_request[:Shipment][:Documents][:Image][1][:PrintSize] = {}
  freight_ship_request[:Shipment][:Documents][:Image][1][:PrintSize][:Length] = '4'
  freight_ship_request[:Shipment][:Documents][:Image][1][:PrintSize][:Width] = '6'

  if international_shipment
    freight_ship_request[:Shipment][:Documents][:InternationalForms] = { '@xmlns:fsp' => 'http://www.ups.com/XMLSchema/XOLTWS/IF/v1.0' }
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:FormType] = '01' # here we do commercial invoice only
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts] = {}
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo] = {}
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:TaxIdentificationNumber] = @tax_identification_number[0..14] if @tax_identification_number.present?
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:Name] = @company[0..34] # required
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:AttentionName] = (@attention_name || 'Customer')[0..34] # required
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:Phone] = {}
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:Phone][:Number] = @phone || @sender_phone # required
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:Address] = {}
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:Address][:AddressLine] = get_address_line_array(@address, @address2)
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:Address][:City] = @city[0..29] # required
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:Address][:StateProvinceCode] = @state # required
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:Address][:PostalCode] = @zip
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Contacts][:SoldTo][:Address][:CountryCode] = @country
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product] = []
    @line_items.each_with_index do |line_item, i|
      freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product] << {}
      freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product][i][:Description] = line_item[:description]
      freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product][i][:Unit] = {}
      freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product][i][:Unit][:Number] = line_item[:quantity].to_i
      freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product][i][:Unit][:UnitOfMeasurement] = {}
      freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product][i][:Unit][:UnitOfMeasurement][:Code] = 'PCS' # lets use pieces here
      freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product][i][:Unit][:Value] = line_item[:price].to_f.round(2) # 2 decimals
      freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product][i][:CommodityCode] = line_item[:commodity_code]
      freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product][i][:PartNumber] = line_item[:part_number].to_s[0..9]
      freight_ship_request[:Shipment][:Documents][:InternationalForms][:Product][i][:OriginCountryCode] = line_item[:origin_country_code]
    end
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:InvoiceNumber] = @reference_number_1 if @reference_number_1.present? # follow convention of reference_number_1 = order reference number
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:InvoiceDate] = Date.current.strftime('%Y%m%d')
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:PurchaseOrderNumber] = @reference_number_2 if @reference_number_2.present? # follow convention of reference_number_2 = PO number
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:TermsOfShipment] = 'DDP'
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:ReasonForExport] = (@export_reason || 'SALE')[0..19]
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:Comments] = @ci_comments[0..149] if @ci_comments.present?
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:DeclarationStatement] = 'I hereby certify that the information on this invoice is true and correct and the contents and value of this shipment is as stated above.'
    freight_ship_request[:Shipment][:Documents][:InternationalForms][:CurrencyCode] = @currency_code || 'USD'
    freight_ship_request[:Shipment][:HandlingInstructions] = @handling_instructions[0..499] if @handling_instructions.present?
    freight_ship_request[:Shipment][:DeliveryInstructions] = @delivery_instructions[0..499] if @delivery_instructions.present?
    freight_ship_request[:Shipment][:PickupInstructions] = @pickup_instructions[0..499] if @pickup_instructions.present?
    freight_ship_request[:Shipment][:SpecialInstructions] = @special_instructions[0..149] if @special_instructions.present?

    # This is a workaround to the issue of UPS Freight not returning Commercial Invoice
    # ---------- Forwarded message ----------
    # From: <mruffino@ups.com>
    # Date: Fri, Nov 2, 2012 at 3:48 PM
    # Subject: HDFS 33842394 | Transient - 9370000 - Freight Shipping Web Service is Unavailable. [Request: 121019-018328]
    # To: rblatt@warmlyyours.com
    # Cc: tkubsh@ups.com, jdye@ups.com, sferowich@ups.com
    #
    #
    # Ramie,
    #
    # This is a follow up to the voicemails I left today. While we do not anticipate a code fix until January, we have found a workaround in the interim. The work around for this is to add the shipment total weight to the request as show below:
    #
    #         <n2:ShipmentTotalWeight>
    #                         <n2:Value>156.0</n2:Value>
    #                         <n2:UnitOfMeasurement>
    #                           <n2:Code>LBS</n2:Code>
    #                           <n2:Description>String</n2:Description>
    #                         </n2:UnitOfMeasurement>
    #              </n2:ShipmentTotalWeight>
    #
    # The XPath for the ‘ShipmentTotalWeight’ container is as follows:
    #
    # /FreightShipRequest/Shipment/ShipmentTotalWeight.
    #
    # Please reply directly to this message if you have any questions.
    #
    # Thank you,
    # Michael Ruffino
    # UPS Third Level Production Support
    # mruffino@ups.com
    # 702-408-3773 ext. 53050

    freight_ship_request[:Shipment][:ShipmentTotalWeight] = {}
    freight_ship_request[:Shipment][:ShipmentTotalWeight][:Value] = tot_weight.to_f.round # can accept 2 decimals, but we round to avoid weird display, since decimal point does not appear on commercial invoice, for e.g. 748.45 lbs appears as 74845 lbs
    freight_ship_request[:Shipment][:ShipmentTotalWeight][:UnitOfMeasurement] = {}
    freight_ship_request[:Shipment][:ShipmentTotalWeight][:UnitOfMeasurement][:Code] = (imperial ? 'LBS' : 'KGS')

  end

  freight_ship_request[:Shipment][:ShipmentServiceOptions] = {}
  freight_ship_request[:Shipment][:ShipmentServiceOptions][:EMailInformation] = []
  freight_ship_request[:Shipment][:ShipmentServiceOptions][:EMailInformation] << {}
  freight_ship_request[:Shipment][:ShipmentServiceOptions][:EMailInformation][0][:EMailType] = {}
  freight_ship_request[:Shipment][:ShipmentServiceOptions][:EMailInformation][0][:EMailType][:Code] = '003' # Exception Notification, here we send to both warehouse and customer
  freight_ship_request[:Shipment][:ShipmentServiceOptions][:EMailInformation][0][:EMail] = {}
  freight_ship_request[:Shipment][:ShipmentServiceOptions][:EMailInformation][0][:EMail][:EMailAddress] = []
  freight_ship_request[:Shipment][:ShipmentServiceOptions][:EMailInformation][0][:EMail][:EMailAddress] << @sender_email
  freight_ship_request[:Shipment][:ShipmentServiceOptions][:EMailInformation][0][:EMail][:EMailAddress] << @email[0..49] if @email
  freight_ship_request[:Shipment][:ShipmentServiceOptions][:EMailInformation][0][:EMail][:UndeliverableEMailAddress] = @sender_email

  if @limited_access || @requires_appointment || @requires_liftgate || @saturday_delivery || @address_residential || @requires_inside_delivery || @is_construction_site || @cod_amount || @insured_value
    if @limited_access || @requires_appointment || @requires_liftgate || @saturday_delivery || @address_residential || @requires_inside_delivery || @is_construction_site
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:DeliveryOptions] = {}
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:DeliveryOptions][:LiftGateRequiredIndicator] = '' if @requires_liftgate
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:DeliveryOptions][:SaturdayDeliveryIndicator] = '' if @saturday_delivery
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:DeliveryOptions][:ResidentialDeliveryIndicator] = '' if @address_residential
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:DeliveryOptions][:InsideDeliveryIndicator] = '' if @requires_inside_delivery
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:DeliveryOptions][:ConstructionSiteDeliveryIndicator] = '' if @is_construction_site
      freight_rate_request[:ShipmentServiceOptions][:DeliveryOptions][:CallBeforeDeliveryIndicator] = '' if @requires_appointment && !@address_residential
      freight_rate_request[:ShipmentServiceOptions][:DeliveryOptions][:LimitedAccessDeliveryIndicator] = '' if @limited_access
    end
    if @cod_amount
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD] = {}
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:CODValue] = {}
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:CODValue][:CurrencyCode] = @currency_code || 'USD'
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:CODValue][:MonetaryValue] = format('%.2f', @cod_amount)
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:CODPaymentMethod] = {}
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:CODPaymentMethod][:Code] = CODFundsCode[@cod_collection_type] || 'R' # default to ‘R’ = cashier’s check or money order - no cash allowed
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:CODBillingOption] = {}
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:CODBillingOption][:Code] = '01' # Prepaid only we don't do freight collect
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo] = {}
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:Name] = @sender_company[0..34]
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:Address] = {}
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:Address][:AddressLine] = get_address_line_array(@sender_address, @sender_address2)
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:Address][:City] = @sender_city[0..29] # required
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:Address][:StateProvinceCode] = @sender_state # required
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:Address][:PostalCode] = @sender_zip # required
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:Address][:CountryCode] = @sender_country # required
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:AttentionName] = (@sender_attention_name || 'Accounting Staff')[0..34] # required
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:Phone] = {}
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:Phone][:Number] = @sender_phone
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:COD][:RemitTo][:EMailAddress] = @sender_email[0..49]
    end
    if @insured_value
      @insured_value = tot_weight * 2.5 if @insured_value.to_f > tot_weight * 2.5 # UPS Freight limits declared value liability to $2.50 per lbs
      @insured_value = 100_000.0 if @insured_value.to_f > 100_000.0 # UPS Freight limits this to 100000.0
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:DeclaredValue] = {}
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:DeclaredValue][:CurrencyCode] = @currency_code || 'USD'
      freight_ship_request[:Shipment][:ShipmentServiceOptions][:DeclaredValue][:MonetaryValue] = format('%.2f', @insured_value)
    end
  end
  # ship_options = {:FreightShipRequest => freight_ship_request}
  # logger.info "Shipping UPS LTL freight label request/response:" # driver.wiredump_dev = STDOUT will have it trace the request/response
  # res = driver.ProcessShipment(freight_ship_request, ups_security)
  # result = REXML::Document.new("<?xml version='1.0'?>#{res}")

  ups_freight_observer = Observer.new
  Savon.observers << ups_freight_observer

  service_key = :ship
  client = get_client(service_key, ups_security.deep_stringify_keys)

  logger.info 'Shipping UPSFreight label request:'
  request_str = String.new
  ship_options = freight_ship_request.deep_stringify_keys
  begin
    savon_response = client.call(:process_shipment, message: ship_options, attributes: { 'xmlns:fsp' => 'http://www.ups.com/XMLSchema/XOLTWS/FreightShip/v1.0', 'xmlns:n3' => 'http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0' })
    request_str = ups_freight_observer.request_xml
    Savon.observers.clear
    logger.info "#{request_str}"
  rescue Savon::Error => e
    request_str = ups_freight_observer.request_xml
    Savon.observers.clear
    logger.info "Shipping UPSFreight label request, ERROR: #{e.to_hash}"
    logger.info "#{request_str}"
    raise ShippingError, "#{e.to_hash}"
  end

  logger.debug 'Shipping UPSFreight label response received'

  rate_estimates = []
  successful, msg = nil
  result = REXML::Document.new("<?xml version='1.0'?>#{savon_response.to_xml}")

  successful, msg = nil

  if begin
    REXML::XPath.first(result,
                       'soapenv:Envelope/soapenv:Body/freightShip:FreightShipResponse/common:Response/common:ResponseStatus/common:Code').text
  rescue StandardError
    nil
  end == '1' && begin
    REXML::XPath.first(result,
                       'soapenv:Envelope/soapenv:Body/freightShip:FreightShipResponse/common:Response/common:Alert/common:Code').text
  rescue StandardError
    nil
  end != '9369056'
    successful = true
    msg = ''
  # elsif handle soap fault...
  else
    successful = false
    msg = begin
      REXML::XPath.first(result,
                         'soapenv:Envelope/soapenv:Body/freightShip:FreightShipResponse/common:Response/common:Alert/common:Description').text
    rescue StandardError
      nil
    end || begin
      REXML::XPath.first(result,
                         'soapenv:Fault/detail/err:Errors/err:ErrorDetail/err:PrimaryErrorCode/err:Description').text
    rescue StandardError
      nil
    end || 'There were errors getting the shipping label.'
  end

  response = {}
  raise ShippingError, "Unable to get label from UPSFreight: #{msg}" unless successful

  total_price = REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightShip:FreightShipResponse/freightShip:ShipmentResults/freightShip:TotalShipmentCharge/freightShip:MonetaryValue').text.to_f
  # logger.info "total_price: #{total_price}"
  shipment_identification_number = REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightShip:FreightShipResponse/freightShip:ShipmentResults/freightShip:ShipmentNumber').text
  bol_id = REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightShip:FreightShipResponse/freightShip:ShipmentResults/freightShip:BOLID').text
  pickup_confirmation_number = REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightShip:FreightShipResponse/freightShip:ShipmentResults/freightShip:PickupRequestConfirmationNumber').text
  # logger.info "shipment_identification_number: #{shipment_identification_number}"
  enc_label_image = ''
  enc_bol_image = ''
  REXML::XPath.each(result, 'soapenv:Envelope/soapenv:Body/freightShip:FreightShipResponse/freightShip:ShipmentResults/freightShip:Documents/freightShip:Image') do |image|
    # logger.info "image: #{image.to_s[0..150]}"
    image_type = REXML::XPath.first(image, 'freightShip:Type/freightShip:Code').text
    # logger.info "image_type: #{image_type}"
    graphic_image = REXML::XPath.first(image, 'freightShip:GraphicImage').text
    # logger.info "graphic_image: #{graphic_image[0..50]}"
    if image_type == '20'
      enc_bol_image = graphic_image
      # logger.info "enc_bol_image: #{enc_bol_image[0..50]}"
    end
    if image_type == '30'
      enc_label_image = graphic_image
      # logger.info "enc_label_image: #{enc_label_image[0..50]}"
    end
  end
  response[:tracking_number] = shipment_identification_number
  response[:encoded_image] = enc_label_image
  response[:image] = Tempfile.new('shipping_label')
  response[:image].binmode
  response[:image].write Base64.decode64(response[:encoded_image])
  response[:image].rewind
  response[:image].flush
  response[:image].fsync
  response[:encoded_bol_image] = enc_bol_image
  response[:bol_image] = Tempfile.new('bol')
  response[:bol_image].binmode
  response[:bol_image].write Base64.decode64(response[:encoded_bol_image])
  response[:bol_image].rewind
  response[:bol_image].flush
  response[:bol_image].fsync

  ci = nil
  enc_ci_image = ''
  image = REXML::XPath.first(result, 'soapenv:Envelope/soapenv:Body/freightShip:FreightShipResponse/freightShip:ShipmentResults/freightShip:Documents/freightShip:Forms')
  # puts "image: #{image.to_s[0..150]}"
  if image
    image_type = REXML::XPath.first(image, 'freightShip:Type/freightShip:Code').text
    # puts "image_type: #{image_type}"
    graphic_image = REXML::XPath.first(image, 'freightShip:GraphicImage').text
    # puts "graphic_image: #{graphic_image[0..50]}"
    enc_ci_image = graphic_image
    ci = {}
    ci[:encoded_image] = enc_ci_image
    ci[:image] = Tempfile.new('ci')
    ci[:image].binmode
    ci[:image].write Base64.decode64(ci[:encoded_image])
    ci[:image].rewind
    ci[:image].flush
    ci[:image].fsync
  end

  # allows for things like fedex.success?
  def response.method_missing(name, *args)
    has_key?(name) ? self[name] : super
  end

  { labels: [response], shipment_identification_number:, carrier_bol: bol_id, pickup_confirmation_number:, ci:, total_charges: total_price,
    ship_request_xml: ship_options.inspect.to_s, ship_reply_xml: result.to_s }
end