summaryrefslogtreecommitdiff
path: root/httemplate/misc/xmlhttp-cust_main-address_standardize.html
blob: 3b9e142f55f495a6e5df3356e0f91424be63f49a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<% objToJson($return) %>
<%init>

my $DEBUG = 0;

my $conf = new FS::Conf;

my $sub = $cgi->param('sub');

my $return = {};

if ( $sub eq 'address_standardize' ) {

  my %arg = $cgi->param('arg');
  $return = \%arg;
  warn join('', map "$_: $arg{$_}\n", keys %arg )
    if $DEBUG;

  my $userid   = $conf->config('usps_webtools-userid');
  my $password = $conf->config('usps_webtools-password');

  if ( length($userid) && length($password) ) {

    my $verifier = Business::US::USPS::WebTools::AddressStandardization->new( {
      UserID   => $userid,   #$ENV{USPS_WEBTOOLS_USERID},
      Password => $password, #$ENV{USPS_WEBTOOLS_PASSWORD},
      #Testing  => 1,
    } );

    foreach my $pre ( '', 'ship_' ) {

      my($zip5, $zip4) = split('-',$arg{$pre.'zip'});

      my %usps_args = (
        FirmName => $arg{$pre.'company'},
        Address2 => $arg{$pre.'address1'},
        Address1 => $arg{$pre.'address2'},
        City     => $arg{$pre.'city'},  
        State    => $arg{$pre.'state'},
        Zip5     => $zip5,
        Zip4     => $zip4,
      );
      warn join('', map "$_: $usps_args{$_}\n", keys %usps_args )
        if $DEBUG;

      my $hash = $verifier->verify_address( %usps_args );

      warn $verifier->response
        if $DEBUG;

      unless ( $verifier->is_error ) {

        my $zip = $hash->{Zip5};
        $zip .= '-'. $hash->{Zip4} if $hash->{Zip4} =~ /\d/;

        $return = {
          %$return,
          "new_$pre".'company'  => $hash->{FirmName},
          "new_$pre".'address1' => $hash->{Address2},
          "new_$pre".'address2' => $hash->{Address1},
          "new_$pre".'city'     => $hash->{City},
          "new_$pre".'state'    => $hash->{State},
          "new_$pre".'zip'      => $zip,
        };

        my @fields = (qw( company address1 address2 city state zip )); #hmm

        my $changed =
          scalar( grep { $return->{$pre.$_} ne $return->{"new_$pre$_"} }
                       @fields
                )
            ? 1 : 0;

        $return->{$pre.'address_standardized'} = $changed;

      } else {

        $return->{$pre.'error'} = "USPS WebTools error: ".
                                  $verifier->{error}{description};


      }

    }

  }

  $return;

}

</%init>