Class: ActiveMerchant::Shipping::CanadaPostPWS

Inherits:
Carrier show all
Defined in:
lib/active_shipping/shipping/carriers/canada_post_pws.rb

Constant Summary collapse

SHIPPING_SERVICES =
{
  "DOM.RP"        => "Regular Parcel",
  "DOM.EP"        => "Expedited Parcel",
  "DOM.XP"        => "Xpresspost",
  "DOM.XP.CERT"   => "Xpresspost Certified",
  "DOM.PC"        => "Priority",
  "DOM.LIB"       => "Library Books",

  "USA.EP"        => "Expedited Parcel USA",
  "USA.PW.ENV"    => "Priority Worldwide Envelope USA",
  "USA.PW.PAK"    => "Priority Worldwide pak USA",
  "USA.PW.PARCEL" => "Priority Worldwide Parcel USA",
  "USA.SP.AIR"    => "Small Packet USA Air",
  "USA.SP.SURF"   => "Small Packet USA Surface",
  "USA.XP"        => "Xpresspost USA",

  "INT.XP"        => "Xpresspost International",
  "INT.IP.AIR"    => "International Parcel Air",
  "INT.IP.SURF"   => "International Parcel Surface",
  "INT.PW.ENV"    => "Priority Worldwide Envelope Int'l",
  "INT.PW.PAK"    => "Priority Worldwide pak Int'l",
  "INT.PW.PARCEL" => "Priority Worldwide parcel Int'l",
  "INT.SP.AIR"    => "Small Packet International Air",
  "INT.SP.SURF"   => "Small Packet International Surface"
}
ENDPOINT =

production

"https://soa-gw.canadapost.ca/"
SHIPMENT_MIMETYPE =
"application/vnd.cpc.ncshipment+xml"
RATE_MIMETYPE =
"application/vnd.cpc.ship.rate+xml"
TRACK_MIMETYPE =
"application/vnd.cpc.track+xml"
REGISTER_MIMETYPE =
"application/vnd.cpc.registration+xml"
LANGUAGE =
{
  'en' => 'en-CA',
  'fr' => 'fr-CA'
}
SHIPPING_OPTIONS =
[:d2po, :d2po_office_id, :cov, :cov_amount, :cod, :cod_amount, :cod_includes_shipping, 
:cod_method_of_payment, :so, :dc, :dns, :pa18, :pa19, :hfp, :lad, 
:rase, :rts, :aban]
RATES_OPTIONS =
[:cov, :cov_amount, :cod, :so, :dc, :dns, :pa18, :pa19, :hfp, :lad]
MAX_WEIGHT =

kg

30
@@name =
"Canada Post PWS"

Instance Attribute Summary collapse

Attributes inherited from Carrier

#last_request, #test_mode

Instance Method Summary collapse

Methods inherited from Carrier

#valid_credentials?

Constructor Details

#initialize(options = {}) ⇒ CanadaPostPWS

Returns a new instance of CanadaPostPWS.



57
58
59
60
61
62
63
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 57

def initialize(options = {})
  @language = LANGUAGE[options[:language]] || LANGUAGE['en']
  @endpoint = options[:endpoint] || ENDPOINT
  @platform_id = options[:platform_id]
  @customer_number = options[:customer_number]
  super(options)
end

Instance Attribute Details

#customer_numberObject

Returns the value of attribute customer_number.



55
56
57
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 55

def customer_number
  @customer_number
end

#endpointObject

Returns the value of attribute endpoint.



55
56
57
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 55

def endpoint
  @endpoint
end

#languageObject

Returns the value of attribute language.



55
56
57
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 55

def language
  @language
end

#loggerObject

Returns the value of attribute logger.



55
56
57
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 55

def logger
  @logger
end

#platform_idObject

Returns the value of attribute platform_id.



55
56
57
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 55

def platform_id
  @platform_id
end

Instance Method Details

#build_rates_request(origin, destination, line_items = [], options = {}, package = nil, services = []) ⇒ Object

rating



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 244

def build_rates_request(origin, destination, line_items = [], options = {}, package = nil, services = [])
  line_items = Array(line_items)
  xml =  XmlNode.new('mailing-scenario', :xmlns => "http://www.canadapost.ca/ws/ship/rate") do |node|
    node << customer_number_node(options)
    node << contract_id_node(options)
    node << quote_type_node(options)
    node << expected_mailing_date_node(shipping_date(options)) if options[:shipping_date]
    options_node = shipping_options_node(RATES_OPTIONS, options)
    node << options_node if options_node && !options_node.children.count.zero?
    node << parcel_node(line_items, package)
    node << origin_node(origin)
    node << destination_node(destination)
    node << services_node(services) unless services.blank?
  end
  xml.to_s
end

#build_shipment_request(origin, destination, package, line_items = [], options = {}) ⇒ Object

options :service => ‘DOM.EP’ :notification_email :packing_instructions :show_postage_rate :cod, :cod_amount, :insurance, :insurance_amount, :signature_required, :pa18, :pa19, :hfp, :dns, :lad



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 338

def build_shipment_request(origin, destination, package, line_items = [], options = {})
  origin = sanitize_location(origin)
  destination = sanitize_location(destination)

  xml = XmlNode.new('non-contract-shipment', :xmlns => "http://www.canadapost.ca/ws/ncshipment") do |root_node|
    root_node << XmlNode.new('delivery-spec') do |node|
      node << shipment_service_code_node(options)
      node << shipment_sender_node(origin, options)
      node << shipment_destination_node(destination, options)
      options_node = shipment_options_node(options)
      node << shipment_options_node(options) if options_node && !options_node.children.count.zero?
      node << shipment_parcel_node(package)
      node << shipment_notification_node(options)
      node << shipment_preferences_node(options)
      node << references_node(options)             # optional > user defined custom notes
      node << shipment_customs_node(destination, line_items, options)
      # COD Remittance defaults to sender
    end
  end
  xml.to_s
end

#build_tracking_events(events) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 314

def build_tracking_events(events)
  events.map do |event|
    date      = event.get_text('event-date').to_s
    time      = event.get_text('event-time').to_s
    zone      = event.get_text('event-time-zone').to_s
    timestamp = DateTime.parse("#{date} #{time} #{zone}")
    time      = Time.utc(timestamp.utc.year, timestamp.utc.month, timestamp.utc.day, timestamp.utc.hour, timestamp.utc.min, timestamp.utc.sec)
    message   = event.get_text('event-description').to_s
    location  = [event.get_text('event-retail-name'), event.get_text('event-site'), event.get_text('event-province')].compact.join(", ")
    name      = event.get_text('event-identifier').to_s          
    ShipmentEvent.new(name, time, location, message)
  end
end

#create_shipment(origin, destination, package, line_items = [], options = {}) ⇒ Object

line_items should be a list of PackageItem’s



92
93
94
95
96
97
98
99
100
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 92

def create_shipment(origin, destination, package, line_items = [], options = {})
  request_body = build_shipment_request(origin, destination, package, line_items, options)
  response = ssl_post(create_shipment_url(options), request_body, headers(options, SHIPMENT_MIMETYPE, SHIPMENT_MIMETYPE))
  parse_shipment_response(response)
rescue ActiveMerchant::ResponseError, ActiveMerchant::Shipping::ResponseError => e
  error_response(e.response.body, CPPWSShippingResponse)
rescue MissingCustomerNumberError => e
  CPPWSShippingResponse.new(false, "Missing Customer Number", {}, {:carrier => @@name})
end

#error_response(response, response_klass) ⇒ Object



543
544
545
546
547
548
549
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 543

def error_response(response, response_klass)
  doc = REXML::Document.new(REXML::Text::unnormalize(response))
  messages = doc.elements['messages'].elements.collect('message') {|node| node }
  message = messages.map {|m| m.get_text('description').to_s }.join(", ")
  code = messages.map {|m| m.get_text('code').to_s }.join(", ")
  response_klass.new(false, message, {}, {:carrier => @@name, :code => code})
end

#find_option_details(option_code, options = {}) ⇒ Object



150
151
152
153
154
155
156
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 150

def find_option_details(option_code, options = {})
  url = endpoint + "rs/ship/option/#{option_code}"
  response = ssl_get(url, headers(options, RATE_MIMETYPE))
  parse_option_response(response)
rescue ActiveMerchant::ResponseError, ActiveMerchant::Shipping::ResponseError => e
  error_response(e.response.body, CPPWSRateResponse)
end

#find_rates(origin, destination, line_items = [], options = {}, package = nil, services = []) ⇒ Object



69
70
71
72
73
74
75
76
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 69

def find_rates(origin, destination, line_items = [], options = {}, package = nil, services = [])
  url = endpoint + "rs/ship/price"
  request  = build_rates_request(origin, destination, line_items, options, package, services)
  response = ssl_post(url, request, headers(options, RATE_MIMETYPE, RATE_MIMETYPE))
  parse_rates_response(response, origin, destination)
rescue ActiveMerchant::ResponseError, ActiveMerchant::Shipping::ResponseError => e
  error_response(e.response.body, CPPWSRateResponse)
end

#find_service_options(service_code, country, options = {}) ⇒ Object



143
144
145
146
147
148
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 143

def find_service_options(service_code, country, options = {})
  response = ssl_get(services_url(country, service_code), headers(options, RATE_MIMETYPE))
  parse_service_options_response(response)
rescue ActiveMerchant::ResponseError, ActiveMerchant::Shipping::ResponseError => e
  error_response(e.response.body, CPPWSRateResponse)
end

#find_services(country = nil, options = {}) ⇒ Object



136
137
138
139
140
141
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 136

def find_services(country = nil, options = {})
  response = ssl_get(services_url(country), headers(options, RATE_MIMETYPE))
  parse_services_response(response)
rescue ActiveMerchant::ResponseError, ActiveMerchant::Shipping::ResponseError => e
  error_response(e.response.body, CPPWSRateResponse)
end

#find_shipment_receipt(shipping_id, options = {}) ⇒ Object



107
108
109
110
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 107

def find_shipment_receipt(shipping_id, options = {})
  response = ssl_get(shipment_receipt_url(shipping_id, options), headers(options, SHIPMENT_MIMETYPE, SHIPMENT_MIMETYPE))
  shipping_response = parse_shipment_receipt_response(response)
end

#find_tracking_info(pin, options = {}) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 78

def find_tracking_info(pin, options = {})
  response = ssl_get(tracking_url(pin), headers(options, TRACK_MIMETYPE))
  parse_tracking_response(response)
rescue ActiveMerchant::ResponseError, ActiveMerchant::Shipping::ResponseError => e
  if e.response
    error_response(e.response.body, CPPWSTrackingResponse)
  else
    CPPWSTrackingResponse.new(false, e.message, {}, {:carrier => @@name})
  end
rescue InvalidPinFormatError => e
  CPPWSTrackingResponse.new(false, "Invalid Pin Format", {}, {:carrier => @@name})
end

#log(msg) ⇒ Object



551
552
553
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 551

def log(msg)
  logger.debug(msg) if logger
end

#maximum_weightObject



158
159
160
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 158

def maximum_weight
  Mass.new(MAX_WEIGHT, :kilograms)
end

#parse_merchant_details_response(response) ⇒ Object



495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 495

def parse_merchant_details_response(response)
  doc = REXML::Document.new(REXML::Text::unnormalize(response))
  raise "No Merchant Info" unless root_node = doc.elements['merchant-info']
  raise "No Merchant Info" if root_node.get_text('customer-number').blank?
  options = {
    :customer_number => root_node.get_text('customer-number').to_s,
    :contract_number => root_node.get_text('contract-number').to_s,
    :username => root_node.get_text('merchant-username').to_s,
    :password => root_node.get_text('merchant-password').to_s,
    :has_default_credit_card => root_node.get_text('has-default-credit-card') == 'true'
  }
  CPPWSMerchantDetailsResponse.new(true, "", {}, options)
end

#parse_option_response(response) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 223

def parse_option_response(response)
  doc = REXML::Document.new(REXML::Text::unnormalize(response))
  option_node = doc.elements['option']
  conflicts = option_node.elements['conflicting-options'].elements.collect('option-code') {|node| node.get_text.to_s} unless option_node.elements['conflicting-options'].blank?
  prereqs = option_node.elements['prerequisite-options'].elements.collect('option-code') {|node| node.get_text.to_s} unless option_node.elements['prerequisite-options'].blank?
  option = {
    :code => option_node.get_text('option-code').to_s,
    :name => option_node.get_text('option-name').to_s,
    :class => option_node.get_text('option-class').to_s,
    :prints_on_label => option_node.get_text('prints-on-label').to_s == "false" ? false : true,
    :qualifier_required => option_node.get_text('qualifier-required').to_s == "false" ? false : true
  }
  option[:conflicting_options] = conflicts if conflicts
  option[:prerequisite_options] = prereqs if prereqs

  option[:qualifier_max] = option_node.get_text("qualifier-max").to_s.to_i if option_node.get_text("qualifier-max")
  option
end

#parse_rates_response(response, origin, destination) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 261

def parse_rates_response(response, origin, destination)
  doc = REXML::Document.new(REXML::Text::unnormalize(response))
  raise ActiveMerchant::Shipping::ResponseError, "No Quotes" unless doc.elements['price-quotes']

  quotes = doc.elements['price-quotes'].elements.collect('price-quote') {|node| node }
  rates = quotes.map do |node|
    service_name  = node.get_text("service-name").to_s
    service_code  = node.get_text("service-code").to_s
    total_price   = node.elements['price-details'].get_text("due").to_s
    expected_date = expected_date_from_node(node)
    options = {
      :service_code   => service_code,
      :total_price    => total_price,
      :currency       => 'CAD',
      :delivery_range => [expected_date, expected_date]
    }
    RateEstimate.new(origin, destination, @@name, service_name, options)
  end
  CPPWSRateResponse.new(true, "", {}, :rates => rates)
end

#parse_register_token_response(response) ⇒ Object



486
487
488
489
490
491
492
493
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 486

def parse_register_token_response(response)
  doc = REXML::Document.new(REXML::Text::unnormalize(response))
  raise ActiveMerchant::Shipping::ResponseError, "No Registration Token" unless root_node = doc.elements['token']      
  options = {
    :token_id => root_node.get_text('token-id').to_s
  }
  CPPWSRegisterResponse.new(true, "", {}, options)
end

#parse_service_options_response(response) ⇒ Object



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
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 182

def parse_service_options_response(response)
  doc = REXML::Document.new(REXML::Text::unnormalize(response))
  service_node = doc.elements['service']
  service_code = service_node.get_text("service-code").to_s
  service_name = service_node.get_text("service-name").to_s
  options_node = service_node.elements['options']
  unless options_node.blank?
    option_nodes = options_node.elements.collect('option') {|node| node}
    options = option_nodes.inject([]) do |result, node|
      option = {
        :code => node.get_text("option-code").to_s,
        :name => node.get_text("option-name").to_s,
        :required => node.get_text("mandatory").to_s == "false" ? false : true,
        :qualifier_required => node.get_text("qualifier-required").to_s == "false" ? false : true
      }
      option[:qualifier_max] = node.get_text("qualifier-max").to_s.to_i if node.get_text("qualifier-max")
      result << option
      result
    end
  end
  restrictions_node = service_node.elements['restrictions']
  dimensions_node = restrictions_node.elements['dimensional-restrictions']
  restrictions = {
    :min_weight => restrictions_node.elements["weight-restriction"].attributes['min'].to_i,
    :max_weight => restrictions_node.elements["weight-restriction"].attributes['max'].to_i,
    :min_length => dimensions_node.elements["length"].attributes['min'].to_f,
    :max_length => dimensions_node.elements["length"].attributes['max'].to_f,
    :min_height => dimensions_node.elements["height"].attributes['min'].to_f,
    :max_height => dimensions_node.elements["height"].attributes['max'].to_f,
    :min_width => dimensions_node.elements["width"].attributes['min'].to_f,
    :max_width => dimensions_node.elements["width"].attributes['max'].to_f,
  }

  {
    :service_code => service_code,
    :service_name => service_name,
    :options => options,
    :restrictions => restrictions
  }
end

#parse_services_response(response) ⇒ Object

service discovery



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 164

def parse_services_response(response)
  doc = REXML::Document.new(REXML::Text::unnormalize(response))
  service_nodes = doc.elements['services'].elements.collect('service') {|node| node }
  services = service_nodes.inject({}) do |result, node|
    service_code = node.get_text("service-code").to_s
    service_name = node.get_text("service-name").to_s
    service_link = node.elements["link"].attributes['href']
    service_link_media_type = node.elements["link"].attributes['media-type']
    result[service_code] = {
      :name => service_name,
      :link => service_link,
      :link_media_type => service_link_media_type
    }
    result
  end
  services
end

#parse_shipment_receipt_response(response) ⇒ Object



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
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 509

def parse_shipment_receipt_response(response)
  doc = REXML::Document.new(REXML::Text::unnormalize(response))
  root = doc.elements['non-contract-shipment-receipt']
  cc_details_node = root.elements['cc-receipt-details']
  service_standard_node = root.elements['service-standard']
  receipt = {
    :final_shipping_point => root.get_text("final-shipping-point").to_s,
    :shipping_point_name => root.get_text("shipping-point-name").to_s,
    :service_code => root.get_text("service-code").to_s,
    :rated_weight => root.get_text("rated-weight").to_s.to_f,
    :base_amount => root.get_text("base-amount").to_s.to_f,
    :pre_tax_amount => root.get_text("pre-tax-amount").to_s.to_f,
    :gst_amount => root.get_text("gst-amount").to_s.to_f,
    :pst_amount => root.get_text("pst-amount").to_s.to_f,
    :hst_amount => root.get_text("hst-amount").to_s.to_f,
    :charge_amount => cc_details_node.get_text("charge-amount").to_s.to_f,
    :currency => cc_details_node.get_text("currency").to_s,
    :expected_transit_days => service_standard_node.get_text("expected-transit-time").to_s.to_i,
    :expected_delivery_date => service_standard_node.get_text("expected-delivery-date").to_s
  }
  option_nodes = root.elements['priced-options'].elements.collect('priced-option') {|node| node} unless root.elements['priced-options'].blank?

  receipt[:priced_options] = if option_nodes
      option_nodes.inject({}) do |result, node|
      result[node.get_text("option-code").to_s] = node.get_text("option-price").to_s.to_f
      result
    end
  else
    []
  end

  receipt
end

#parse_shipment_response(response) ⇒ Object



473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 473

def parse_shipment_response(response)
  doc = REXML::Document.new(REXML::Text::unnormalize(response))
  raise ActiveMerchant::Shipping::ResponseError, "No Shipping" unless root_node = doc.elements['non-contract-shipment-info']      
  options = {
    :shipping_id      => root_node.get_text('shipment-id').to_s,
    :tracking_number  => root_node.get_text('tracking-pin').to_s,
    :details_url      => root_node.elements["links/link[@rel='details']"].attributes['href'],
    :label_url        => root_node.elements["links/link[@rel='label']"].attributes['href'],
    :receipt_url      => root_node.elements["links/link[@rel='receipt']"].attributes['href']
  }
  CPPWSShippingResponse.new(true, "", {}, options)
end

#parse_tracking_response(response) ⇒ Object

tracking



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
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 285

def parse_tracking_response(response)
  doc = REXML::Document.new(REXML::Text::unnormalize(response))
  raise ActiveMerchant::Shipping::ResponseError, "No Tracking" unless root_node = doc.elements['tracking-detail']

  events = root_node.elements['significant-events'].elements.collect('occurrence') {|node| node }

  shipment_events  = build_tracking_events(events)
  change_date      = root_node.get_text('changed-expected-date').to_s
  expected_date    = root_node.get_text('expected-delivery-date').to_s
  dest_postal_code = root_node.get_text('destination-postal-id').to_s
  destination      = Location.new(:postal_code => dest_postal_code)
  origin           = Location.new(origin_hash_for(root_node))
  options = {
    :carrier                 => @@name,
    :service_name            => root_node.get_text('service-name').to_s,
    :expected_date           => expected_date.blank? ? nil : Date.parse(expected_date),
    :changed_date            => change_date.blank? ? nil : Date.parse(change_date),
    :change_reason           => root_node.get_text('changed-expected-delivery-reason').to_s.strip,
    :destination_postal_code => root_node.get_text('destination-postal-id').to_s,
    :shipment_events         => shipment_events,
    :tracking_number         => root_node.get_text('pin').to_s,
    :origin                  => origin,
    :destination             => destination,
    :customer_number         => root_node.get_text('mailed-by-customer-number').to_s
  }
  
  CPPWSTrackingResponse.new(true, "", {}, options)
end

#references_node(options) ⇒ Object



420
421
422
423
424
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 420

def references_node(options)
  # custom values
  # XmlNode.new('references') do |node|
  # end
end

#register_merchant(options = {}) ⇒ Object



117
118
119
120
121
122
123
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 117

def register_merchant(options = {})
  url = endpoint + "ot/token"
  response = ssl_post(url, nil, headers({}, REGISTER_MIMETYPE, REGISTER_MIMETYPE).merge({"Content-Length" => "0"}))
  parse_register_token_response(response)
rescue ActiveMerchant::ResponseError, ActiveMerchant::Shipping::ResponseError => e
  error_response(e.response.body, CPPWSRegisterResponse)
end

#requirementsObject



65
66
67
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 65

def requirements
  [:api_key, :secret]
end

#retrieve_merchant_details(options = {}) ⇒ Object



125
126
127
128
129
130
131
132
133
134
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 125

def retrieve_merchant_details(options = {})
  raise MissingTokenIdError unless token_id = options[:token_id]
  url = endpoint + "ot/token/#{token_id}"
  response = ssl_get(url, headers({}, REGISTER_MIMETYPE, REGISTER_MIMETYPE))
  parse_merchant_details_response(response)
rescue ActiveMerchant::ResponseError, ActiveMerchant::Shipping::ResponseError => e
  error_response(e.response.body, CPPWSMerchantDetailsResponse)
rescue Exception => e
  raise ResponseError.new(e.message)
end

#retrieve_shipment(shipping_id, options = {}) ⇒ Object



102
103
104
105
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 102

def retrieve_shipment(shipping_id, options = {})
  response = ssl_post(shipment_url(shipping_id, options), nil, headers(options, SHIPMENT_MIMETYPE, SHIPMENT_MIMETYPE))
  shipping_response = parse_shipment_response(response)
end

#retrieve_shipping_label(shipping_response, options = {}) ⇒ Object



112
113
114
115
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 112

def retrieve_shipping_label(shipping_response, options = {})
  raise MissingShippingNumberError unless shipping_response && shipping_response.shipping_id
  ssl_get(shipping_response.label_url, headers(options, "application/pdf"))
end

#shipment_customs_node(destination, line_items, options) ⇒ Object



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
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 426

def shipment_customs_node(destination, line_items, options)
  return unless destination.country_code != 'CA'

  XmlNode.new('customs') do |node|
    currency = options[:currency] || "CAD"
    node << XmlNode.new('currency',currency)
    node << XmlNode.new('conversion-from-cad',options[:conversion_from_cad].to_s) if currency != 'CAD' && options[:conversion_from_cad]
    node << XmlNode.new('reason-for-export','SOG') # SOG - Sale of Goods
    node << XmlNode.new('other-reason',options[:customs_other_reason]) if (options[:customs_reason_for_export] && options[:customs_other_reason])
    node << XmlNode.new('additional-customs-info',options[:customs_addition_info]) if options[:customs_addition_info]
    node << XmlNode.new('sku-list') do |sku|
      line_items.each do |line_item|
        sku << XmlNode.new('item') do |item|
          item << XmlNode.new('hs-tariff-code', line_item.hs_code) if line_item.hs_code && !line_item.hs_code.empty?
          item << XmlNode.new('sku', line_item.sku) if line_item.sku && !line_item.sku.empty?
          item << XmlNode.new('customs-description', line_item.name.slice(0,44))
          item << XmlNode.new('unit-weight', '%#2.3f' % sanitize_weight_kg(line_item.kg))
          item << XmlNode.new('customs-value-per-unit', '%.2f' % sanitize_price_from_cents(line_item.value))
          item << XmlNode.new('customs-number-of-units', line_item.quantity)
          item << XmlNode.new('country-of-origin', line_item.options[:country_of_origin]) if line_item.options && line_item.options[:country_of_origin] && !line_item.options[:country_of_origin].empty?
          item << XmlNode.new('province-of-origin', line_item.options[:province_of_origin]) if line_item.options && line_item.options[:province_of_origin] && !line_item.options[:province_of_origin].empty?
        end
      end
    end
    
  end
end

#shipment_destination_node(location, options) ⇒ Object



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 381

def shipment_destination_node(location, options)
  XmlNode.new('destination') do |node|
    node << XmlNode.new('name', location.name)
    node << XmlNode.new('company', location.company) if location.company.present?
    node << XmlNode.new('client-voice-number', location.phone)
    node << XmlNode.new('address-details') do |innernode|
      innernode << XmlNode.new('address-line-1', location.address1)
      address2 = [location.address2, location.address3].reject(&:blank?).join(", ")
      innernode << XmlNode.new('address-line-2', address2) unless address2.blank?
      innernode << XmlNode.new('city', location.city)
      innernode << XmlNode.new('prov-state', location.province) unless location.province.blank?
      innernode << XmlNode.new('country-code', location.country_code)
      innernode << XmlNode.new('postal-zip-code', location.postal_code)
    end
  end
end

#shipment_notification_node(options) ⇒ Object



402
403
404
405
406
407
408
409
410
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 402

def shipment_notification_node(options)
  return unless options[:notification_email]
  XmlNode.new('notification') do |node|
    node << XmlNode.new('email', options[:notification_email])
    node << XmlNode.new('on-shipment', true)
    node << XmlNode.new('on-exception', true)
    node << XmlNode.new('on-delivery', true)
  end
end

#shipment_options_node(options) ⇒ Object



398
399
400
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 398

def shipment_options_node(options)
    shipping_options_node(SHIPPING_OPTIONS, options)
end

#shipment_parcel_node(package, options = {}) ⇒ Object



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 454

def shipment_parcel_node(package, options ={})
  weight = sanitize_weight_kg(package.kilograms.to_f)
  XmlNode.new('parcel-characteristics') do |el|
    el << XmlNode.new('weight', "%#2.3f" % weight)
    pkg_dim = package.cm
    if pkg_dim && !pkg_dim.select{|x| x != 0}.empty?
      el << XmlNode.new('dimensions') do |dim|
        dim << XmlNode.new('length', '%.1f' % ((pkg_dim[2]*10).round / 10.0)) if pkg_dim.size >= 3
        dim << XmlNode.new('width', '%.1f' % ((pkg_dim[1]*10).round / 10.0)) if pkg_dim.size >= 2
        dim << XmlNode.new('height', '%.1f' % ((pkg_dim[0]*10).round / 10.0)) if pkg_dim.size >= 1
      end
    end
    el << XmlNode.new('document', false)
    el << XmlNode.new('mailing-tube', package.tube?)
    el << XmlNode.new('unpackaged', package.unpackaged?)
  end
end

#shipment_preferences_node(options) ⇒ Object



412
413
414
415
416
417
418
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 412

def shipment_preferences_node(options)
  XmlNode.new('preferences') do |node|
    node << XmlNode.new('show-packing-instructions', options[:packing_instructions] || true)
    node << XmlNode.new('show-postage-rate', options[:show_postage_rate] || false)          
    node << XmlNode.new('show-insured-value', true)
  end
end

#shipment_sender_node(location, options) ⇒ Object



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 364

def shipment_sender_node(location, options)
  XmlNode.new('sender') do |node|
    node << XmlNode.new('name', location.name)
    node << XmlNode.new('company', location.company) if location.company.present?
    node << XmlNode.new('contact-phone', location.phone)
    node << XmlNode.new('address-details') do |innernode|
      innernode << XmlNode.new('address-line-1', location.address1)
      address2 = [location.address2, location.address3].reject(&:blank?).join(", ")
      innernode << XmlNode.new('address-line-2', address2) unless address2.blank?
      innernode << XmlNode.new('city', location.city)
      innernode << XmlNode.new('prov-state', location.province)     
      #innernode << XmlNode.new('country-code', location.country_code)
      innernode << XmlNode.new('postal-zip-code', location.postal_code)
    end
  end
end

#shipment_service_code_node(options) ⇒ Object



360
361
362
# File 'lib/active_shipping/shipping/carriers/canada_post_pws.rb', line 360

def shipment_service_code_node(options)
  XmlNode.new('service-code', options[:service])
end