blib/lib/USPS/RateRequest.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package USPS::RateRequest;
2 $USPS::RateRequest::VERSION = '1.0002';
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use XML::DOM;
Subroutine BEGIN: called CC=1 SCAR=2.6
6 use AnyEvent::HTTP::LWP::UserAgent;
7 use AnyEvent;
8 use Ouch;
9 use POSIX qw(ceil);
10 use XML::Simple;
11 use 5.010;
12  
13 =head1 NAME
14  
15 USPS::RateRequest - Ultra fast parallelized asyncronous USPS rate lookups.
16  
17 =head1 VERSION
18  
19 version 1.0002
20  
21 =head1 SYNOPSIS
22  
23 use USPS::RateRequest;
24 use Box::Calc;
25 use Ouch;
26  
27 my $calc = Box::Calc->new();
28 $calc->add_box_type(...);
29 $calc->add_item(...);
30 $calc->pack_items;
31  
32 my $rates = eval {
33 USPS::RateRequest->new(
34 user_id => 'usps username'
35 password => 'usps password',
36 from => 53716,
37 postal_code => 90210,
38 country => 'US',
39 )->request_rates($calc->boxes)->recv;
40 };
41  
42 if (hug) {
43 die "USPS Error: $@";
44 }
45  
46 my $priority_postage_for_first_box = $rates->{$calc->get_box(0)->id}{'USPS Priority'}{postage};
47  
48 # view the complete data structure
49 use Data::Dumper;
50 say Dumper($rates);
51  
52 =head1 DESCRIPTION
53  
54 USPS::RateRequest exists for two reasons:
55  
56 =over
57  
58 =item *
59  
60 L<Business::Shipping> is very slow when you have to request rates for varying amounts and sizes of parcels. That's because each request is done in serial. USPS::RateRequest makes all requests in parallel, thus increasing performance dramatically.
61  
62 =item *
63  
64 L<Box::Calc> does a ton of work figuring out exactly what can be packed into each parcel. USPS::RateRequest takes advantage of all that data being loaded and makes use of it to calculate very precise package dimensions and weights to get the most accurate shipping prices.
65  
66 =back
67  
68 If there are errors returned from the USPS, USPS::RateRequest will throw exceptions via L<Ouch> with the code "USPS Error" and the error returned from the USPS. If no rates are returned at all, then it will throw an exception with the code "No Rates".
69  
70 =head1 METHODS
71  
72 =head2 new( params )
73  
74 Constructor.
75  
76 =over
77  
78 =item params
79  
80 A hash of initialization parameters. An asterisk denotes required parameters.
81  
82 =over
83  
84 =item test_mode
85  
86 Boolean. If true requests will be posted to the USPS test server rather than the production server.
87  
88 =item prod_uri
89  
90 The URI to the production instance of the USPS web tools web services. Defaults to C<http://production.shippingapis.com/ShippingAPI.dll>.
91  
92 =item test_uri
93  
94 The URI to the test instance of the USPS web tools web services. Defaults to C<http://testing.shippingapis.com/ShippingAPItest.dll>.
95  
96 =item user_id (*)
97  
98 The username provided to you by signing up for USPS web tools here: L<https://www.usps.com/business/web-tools-apis/welcome.htm>
99  
100 =item password (*)
101  
102 The password that goes with C<user_id>.
103  
104 =item from (*)
105  
106 The zip code from which the parcels will ship.
107  
108 =item postal_code (*)
109  
110 The postal_code code where the parcels will be delivered.
111  
112 =item country (*)
113  
114 The name of the country where the parcels will be delivered. See the USPS web services documentation
115 for a list of valid countries. L<https://www.usps.com/business/web-tools-apis/price-calculators.htm>
116 The proper name for the USA is "United States of America".
117  
118 =item service
119  
120 Defaults to C<all>. Optionally limit the response to specific delivery services, such as C<PRIORITY>. See the USPS web service documentation for details: L<https://www.usps.com/business/web-tools-apis/price-calculators.htm>
121  
122 =item debug
123  
124 Add additional items into the returned rate request data for debugging issues with rate lookups and name sanitization. This data is not guaranteed to stay the same from release to release.
125  
126 =back
127  
128 =back
129  
130 =cut
131  
132 has 'test_mode' => (
133 is => 'rw',
134 default => 0,
135 );
136  
137 has prod_uri => (
138 is => 'rw',
139 default => 'http://production.shippingapis.com/ShippingAPI.dll'
140 );
141  
142 has test_uri => (
143 is => 'rw',
144 default => 'http://testing.shippingapis.com/ShippingAPItest.dll',
145 );
146  
147 has user_id => (
148 is => 'ro',
149 required => 1,
150 );
151  
152 has password => (
153 is => 'ro',
154 required => 1,
155 );
156  
157 has from => (
158 is => 'rw',
159 isa => 'Int',
160 required => 1,
161 );
162  
163 has postal_code => (
164 is => 'rw',
165 required => 1,
166 );
167  
168 has country => (
169 is => 'rw',
170 required => 1,
171 );
172  
173 has service => (
174 is => 'rw',
175 default => 'all',
176 );
177  
178 has debug => (
179 is => 'rw',
180 default => 0,
181 isa => 'Int',
182 );
183  
184 __PACKAGE__->meta()->make_immutable();
185  
186  
187 # this sub is almost a verbatim copy from Business::Shipping
188  
189 sub _generate_request_xml {
190 my ($self, $boxes) = @_;
191 my $rate_request_document = XML::DOM::Document->new();
192 my $rate_request_element = $rate_request_document->createElement(
193 $self->domestic() ? 'RateV4Request' : 'IntlRateV2Request');
194  
195 # Note that these are required even for test mode transactions.
196 $rate_request_element->setAttribute('USERID', $self->user_id);
197 $rate_request_element->setAttribute('PASSWORD', $self->password);
198 $rate_request_document->appendChild($rate_request_element);
199  
200 # needed for special services
201 my $revision_element = $rate_request_document->createElement('Revision');
202 $revision_element->appendChild($rate_request_document->createTextNode(2));
203 $rate_request_element->appendChild($revision_element);
204  
205 foreach my $box (@{ $boxes }) {
206 my $package_element = $rate_request_document->createElement('Package');
207 $package_element->setAttribute('ID', $box->id);
208 $rate_request_element->appendChild($package_element);
209  
210 if ($self->domestic) {
211 my $service_element = $rate_request_document->createElement('Service');
212 $service_element->appendChild($rate_request_document->createTextNode($self->service));
213 $package_element->appendChild($service_element);
214  
215 my $zip_origin_element = $rate_request_document->createElement('ZipOrigination');
216 $zip_origin_element->appendChild($rate_request_document->createTextNode($self->from));
217 $package_element->appendChild($zip_origin_element);
218  
219 my $zip_destination_element = $rate_request_document->createElement('ZipDestination');
220 ##USPS only supports ZIP, not ZIP+4 formats
221 my $zip = $self->postal_code;
222 $zip =~ s/(\d{5})-\d{4}/$1/;
223 $zip_destination_element->appendChild($rate_request_document->createTextNode($zip));
224 $package_element->appendChild($zip_destination_element);
225 }
226  
227 my $weight = $box->calculate_weight;
228 my $pounds = int($weight / 16);
229 my $ounces = $weight % 16;
230  
231 my $pounds_element = $rate_request_document->createElement('Pounds');
232 $pounds_element->appendChild($rate_request_document->createTextNode($pounds));
233 $package_element->appendChild($pounds_element);
234  
235 my $ounces_element = $rate_request_document->createElement('Ounces');
236 $ounces_element->appendChild($rate_request_document->createTextNode($ounces));
237 $package_element->appendChild($ounces_element);
238  
239 unless ($self->domestic) {
240 my $mail_type_element = $rate_request_document->createElement('MailType');
241 $mail_type_element->appendChild($rate_request_document->createTextNode($box->mail_type));
242 $package_element->appendChild($mail_type_element);
243
244 my $gxg_element = $rate_request_document->createElement('GXG');
245 my $pobox_flag_element = $rate_request_document->createElement('POBoxFlag');
246 $pobox_flag_element->appendChild($rate_request_document->createTextNode($box->mail_pobox_flag));
247 $gxg_element->appendChild($pobox_flag_element);
248 my $gift_flag_element = $rate_request_document->createElement('GiftFlag');
249 $gift_flag_element->appendChild($rate_request_document->createTextNode($box->mail_gift_flag));
250 $gxg_element->appendChild($gift_flag_element);
251 $package_element->appendChild($gxg_element);
252
253 my $value_of_contents_element = $rate_request_document->createElement('ValueOfContents');
254 $value_of_contents_element->appendChild($rate_request_document->createTextNode($box->value_of_contents));
255 $package_element->appendChild($value_of_contents_element);
256  
257 my $country_element = $rate_request_document->createElement('Country');
258 $country_element->appendChild($rate_request_document->createTextNode($self->country));
259 $package_element->appendChild($country_element);
260  
261 }
262
263 my $container_element = $rate_request_document->createElement('Container');
264 $container_element->appendChild($rate_request_document->createTextNode($self->domestic ? $box->mail_container : 'RECTANGULAR'));
265 $package_element->appendChild($container_element);
266  
267 my $oversize_element = $rate_request_document->createElement('Size');
268 $oversize_element->appendChild($rate_request_document->createTextNode($box->mail_size));
269 $package_element->appendChild($oversize_element);
270  
271 my $width_element = $rate_request_document->createElement('Width');
272 $width_element->appendChild($rate_request_document->createTextNode($box->y));
273 $package_element->appendChild($width_element);
274  
275 my $length_element = $rate_request_document->createElement('Length');
276 $length_element->appendChild($rate_request_document->createTextNode($box->x));
277 $package_element->appendChild($length_element);
278  
279 my $height_element = $rate_request_document->createElement('Height');
280 $height_element->appendChild($rate_request_document->createTextNode($box->z));
281 $package_element->appendChild($height_element);
282  
283 my $girth_element = $rate_request_document->createElement('Girth');
284 $girth_element->appendChild($rate_request_document->createTextNode($box->girth));
285 $package_element->appendChild($girth_element);
286  
287 if ($self->country eq 'Canada') {
288 my $origin_zip = $rate_request_document->createElement('OriginZip');
289 $origin_zip->appendChild($rate_request_document->createTextNode($self->from));
290 $package_element->appendChild($origin_zip);
291 }
292  
293 if ($self->domestic) {
294 if ($self->service =~ /all/i and not defined $box->mail_machinable()) {
295 $box->mail_machinable('False');
296 }
297  
298 # trying to get special services working
299 #my $special_services_element = $rate_request_document->createElement('SpecialServices');
300 #my $insurance_element = $rate_request_document->createElement('SpecialService');
301 #$insurance_element->appendChild($rate_request_document->createTextNode(1));
302 #$special_services_element->appendChild($insurance_element);
303 #$package_element->appendChild($special_services_element);
304  
305 if (defined $box->mail_machinable) {
306 my $machine_element = $rate_request_document->createElement('Machinable');
307 $machine_element->appendChild($rate_request_document->createTextNode($box->mail_machinable));
308 $package_element->appendChild($machine_element);
309 }
310 }
311
312  
313 }
314 return $rate_request_document->toString();
315 }
316  
317 sub _generate_requests {
318 my ($self, $boxes) = @_;
319 my @requests = ();
320 my @boxes = @{ $boxes };
321 my $limit = 20; # the USPS service craps out if the XML document is too big, most likely due to it being URL encoded, rather than a post body
322 my $pages = ceil( scalar(@boxes) / $limit );
323 for (1..$pages) {
324 my @temp = ();
325 my $temp_limit = scalar @boxes;
326 $temp_limit = $limit if $limit < $temp_limit;
327 for (1..$temp_limit) {
328 push @temp, shift @boxes;
329 }
330 push @requests, $self->_generate_request_xml(\@temp);
331 }
332 return \@requests;
333 }
334  
335 sub _generate_uri {
336 my $self = shift;
337 return $self->test_mode ? $self->test_uri : $self->prod_uri;
338 }
339  
340 =head2 request_rates ( boxes )
341  
342 Returns an L<AnyEvent> condition variable. When you call the C<recv> method on that variable it will send out all the requests for rates, collate and translate the responses, and return a hash reference that looks like this:
343  
344 {
345 'box-id-1' => {
346 'USPS Priority Small Flat Rate Box' => {
347 'postage' => '5.80'
348 },
349 'USPS Priority Express Hold For Pickup' => {
350 'postage' => '56.05'
351 },
352 'USPS Priority Express Flat Rate Envelope' => {
353 'postage' => '19.99'
354 },
355 'USPS Priority Medium Flat Rate Box' => {
356 'postage' => '12.35'
357 },
358 'USPS Standard Post' => {
359 'postage' => '13.34'
360 },
361 'USPS Media' => {
362 'postage' => '4.61'
363 },
364 [....]
365 },
366 'box-id-2' => {
367 [....]
368 },
369 [....]
370  
371 }
372  
373 =over
374  
375 =item boxes
376  
377 An array reference of boxes created by C<Box::Calc>.
378  
379 =back
380  
381 =cut
382  
383 sub request_rates {
384 my ($self, $boxes) = @_;
385 my @responses = ();
386 my $cv = AnyEvent->condvar;
387 $cv->begin(sub { shift->send($self->_handle_responses(\@responses)) });
388 foreach my $request_xml (@{$self->_generate_requests($boxes)}) {
389 if ($self->debug) {
390 say $request_xml;
391 }
392 $cv->begin;
393 my $content = 'API=' . ($self->domestic ? 'RateV4' : 'IntlRateV2') . '&XML=' . $request_xml;
394 my $ua = AnyEvent::HTTP::LWP::UserAgent->new;
395 $ua->timeout(30);
396 $ua->post_async($self->_generate_uri,
397 Content_Type => 'application/x-www-form-urlencoded',
398 'content-length' => CORE::length($request_xml),
399 Content => $content,
400 )->cb(sub {
401 push @responses, shift->recv;
402 $cv->end;
403 });
404 }
405 $cv->end;
406 return $cv;
407 }
408  
409 sub _handle_responses {
410 my ($self, $responses) = @_;
411 my %rates = ();
412 foreach my $response (@{$responses}) {
413 $self->_handle_response($response, \%rates);
414 }
415 unless (scalar keys %rates) {
416 ouch 'No Rates', 'No rates were returned for your packages.';
417 }
418 return \%rates;
419 }
420  
421 sub _handle_response {
422 my ($self, $response, $rates) = @_;
423  
424 unless (ref $response eq 'HTTP::Response') {
425 ouch 500, $response;
426 }
427  
428 if ($self->debug) {
429 say $response->decoded_content;
430 }
431  
432 ### Keep the root element, because USPS might return an error and 'Error' will be the root element
433 my $response_tree = XML::Simple::XMLin(
434 $response->decoded_content,
435 ForceArray => 0,
436 KeepRoot => 1
437 );
438
439 ### Discard the root element on success
440 $response_tree = $response_tree->{RateV4Response} if (exists($response_tree->{RateV4Response}));
441 $response_tree = $response_tree->{IntlRateV2Response} if (exists($response_tree->{IntlRateV2Response}));
442  
443 # Handle errors
444 ### Get all errors
445 my $errors = [];
446 push(@$errors, $response_tree->{Error}) if (exists($response_tree->{Error}));
447 if (ref $response_tree->{Package} eq 'HASH') {
448 if (exists($response_tree->{Package}{Error})) {
449 push(@$errors, $response_tree->{Package}{Error});
450 $errors->[$#{$errors}]{PackageID} = $response_tree->{Package}{ID};
451 }
452 }
453 elsif (ref $response_tree->{Package} eq 'ARRAY') {
454 foreach my $pkg (@{ $response_tree->{Package} }) {
455 if (exists($pkg->{Error})) {
456 push(@$errors, $pkg->{Error});
457 $errors->[$#{$errors}]{PackageID} = $pkg->{ID};
458 }
459 }
460 }
461
462 # throw an exception if there are errors
463 if (@$errors > 0) {
464 ouch 'USPS Error', $errors->[0]{Description}, $errors;
465 }
466
467 # normalize rates for domestic and international
468 my $packages = ref $response_tree->{Package} eq 'ARRAY' ? $response_tree->{Package} : [$response_tree->{Package}];
469 if ($self->domestic) {
470 foreach my $package (@{$packages}) {
471 my %services = ();
472 foreach my $service (@{$package->{Postage}}) {
473 my $service_name = $self->sanitize_service_name($service->{MailService});
474 $services{$service_name} = {
475 postage => $service->{Rate},
476 };
477 if ($self->debug) {
478 $services{$service_name}->{label} = $service->{MailService};
479 }
480 }
481 $rates->{$package->{ID}} = \%services;
482 }
483 }
484 else {
485 foreach my $package (@{$packages}) {
486 my %services = ();
487 foreach my $service (@{$package->{Service}}) {
488 my $service_name = $self->sanitize_service_name($service->{SvcDescription});
489 $services{$service_name} = {
490 postage => $service->{Postage},
491 };
492 if ($self->debug) {
493 $services{$service_name}->{label} = $service->{SvcDescription};
494 }
495 }
496 $rates->{$package->{ID}} = \%services;
497 }
498 }
499 }
500  
501 =head2 sanitize_service_name ( name )
502  
503 =cut
504  
505 sub sanitize_service_name {
506 my ($class, $name) = @_;
507 my $remove_tm = quotemeta('&lt;sup&gt;&amp;trade;&lt;/sup&gt;');
508 my $remove_gxg = quotemeta(' (GXG)');
509 $name =~ s/\*//g;
510 $name =~ s{&lt;sup&gt;&(?:amp;reg|amp;trade|#174|#8482);&lt;/sup&gt;}{}gi;
511 $name =~ s/$remove_gxg//gi;
512 $name =~ s/GXG/Global Express Guaranteed/gi;
513 $name =~ s/ Mail//gi;
514 $name =~ s/ \d-Day//gi;
515 $name =~ s/ APO\/FPO\/DPO//gi;
516 $name =~ s/ Military//gi;
517 $name =~ s/ International//gi;
518 $name =~ s/USPS //gi;
519 $name =~ s/Envelopes/Envelope/gi;
520 $name =~ s/Boxes/Box/gi;
521 $name =~ s/priced box/Box/gi;
522 return 'USPS '.$name;
523 }
524  
525 =head2 domestic ( )
526  
527 Returns a 1 or 0 depending upon whether the C<country> is 'United States of America'.
528  
529 =cut
530  
531 sub domestic {
532 my $self = shift;
533 return $self->country eq 'United States of America' ? 1 : 0;
534 }
535  
536 =head1 CAVEATS
537  
538 Although Box::Calc doesn't care what units you use for weights and measurements, USPS does. Make sure all your weights are in ounces and all your measurements are in inches.
539  
540 =head1 AUTHOR
541  
542 =over
543  
544 =item JT Smith <jt_at_plainblack_dot_com>
545  
546 =back
547  
548 =head1 LEGAL
549  
550 Box::Calc is Copyright 2014 Plain Black Corporation (L<http://www.plainblack.com>) and is licensed under the same terms as Perl itself.
551  
552  
553 =cut
554  
555 1;
↑ Summary