append-email.pl untested

filter: Statementstmt 0.0% 0 / 200 Branchbran 0.0% 0 / 56 Conditioncond 0.0% 0 / 23 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 311 CC 21 SCAR 30.3
CC
21
Cov
0%
lookup_email
56.0
get_data
42.0
reindex_order
30.0
CRAP 20.8
1 use strict;
2 use warnings;
3  
4 use lib (
5 $ENV{'DATAFINDER_HOME'}
6 ? $ENV{'DATAFINDER_HOME'}
7 : $FindBin::Bin
8 );
9  
10 use WWW::Datafinder;
11 use Data::Dumper;
12 use Carp qw(croak cluck confess);
13 use Config::IniFiles;
14 use Getopt::Long;
15 use Storable qw(nstore retrieve dclone);
16 use Try::Tiny;
17 use POSIX;
18 use Search::Elasticsearch;
19 use DateTime::Format::ISO8601;
20 use MCE;
21 use Scalar::Util qw(reftype);
22 use Text::CSV_XS;
23  
24  
25 my %mws2datafiner = (
26 'd_zip' => sub { my ($x) = @_; unless ($x->{PostalCode}) { return undef; } my ($z) = split('-', $x->{PostalCode}); return $z; },
27 'd_fulladdr' => sub { my ($x) = @_;
28 return undef unless defined($x->{AddressLine1});
29 return $x->{AddressLine1} .
30 ($x->{AddressLine2} ? ' '.$x->{AddressLine2} : ''); },
31 'd_state' => sub { my ($x) = @_; return $x->{StateOrRegion}; },
32 'd_city' => sub { my ($x) = @_; return $x->{City}; },
33 'd_first' => sub { my ($x) = @_; return first_name($x->{BuyerName}); },
34 'd_last' => sub { my ($x) = @_; return last_name($x->{BuyerName}); },
35 );
36 my $df = WWW::Datafinder->new( {
37 # api_key => 'gmnglsc3koi5yzmtte5sss6i',
38 api_key => 'XXX',
39 cache_time => 0
40 # cache_time => 3600*1000
41 }) or die 'Cannot create Datafinder object';
42  
43  
44 use Readonly;
45 Readonly my $ORDERS_CACHE => '../mws/orders.cache2';
46  
47 Readonly my $CONFIG_ELASTIC_SECTION => 'Elastic';
48  
49 use vars qw($config_file $conf_obj $debug %orders $interval);
50  
51 if (@ARGV == 0) {
52 print_usage();
53 exit(1);
54 }
55  
56 GetOptions(
57 'c|config=s' => \$config_file,
58 'd|debug' => \$debug
59 );
60  
61 $config_file //= "$FindBin::Bin/etc/update-usage.conf";
62 $conf_obj = Config::IniFiles->new( -file => $config_file )
63 || croak( "Config file error:\n" . join( "\n", @Config::IniFiles::errors ) );
64  
65 my $nodelist = $conf_obj->val( $CONFIG_ELASTIC_SECTION, 'Nodes' );
66 unless ($nodelist) {
67 confess('No elastic node list is provided');
68 }
69 my $index = $conf_obj->val( $CONFIG_ELASTIC_SECTION, 'Index', 'amazon_mws' );
70 my $elastic_type = $conf_obj->val( $CONFIG_ELASTIC_SECTION, 'Type', 'order_item' );
71  
72 my $es = Search::Elasticsearch->new(
73 {
74 cxn_pool => 'Static',
75 nodes => [ split q{,}, $nodelist ],
76 # trace_to => [ 'File', $self->config->val( 'Global', 'Log_File' ) ],
77 # log_to => [ 'File', $self->config->val( 'Global', 'Log_File' ) ],
78 }
79 );
80  
81 my $params = {
82 query => {
83 match_all => {}
84 },
85 # filter => [
86 #
87 # ]
88 # }
89 };
90  
91 my $scroll = $es->scroll_helper(
92 scroll => '120m',
93 search_type => 'scan',
94 size => 1000,
95 index => $index,
96 type => $elastic_type,
97 body => $params
98 );
99 my $count = 0;
100 my $x;
101  
102 my %asin = (
103 'B01CV7HLO2' => 1,
104 'B00L3QWJBI' => 1,
105 'B00PUX0A52' => 1,
106 'B00HFD0QTK' => 1,
107 'B01HQFTW00' => 1,
108 'B012UKTVTS' => 1,
109 'B01CUZ8J3C' => 1,
110 'B01L7EZ048' => 1,
111 'B01L7L3HKU' => 1
112 );
113 my $c = 0;
114 my @result;
115  
116 my $bulk = $es->bulk_helper(
117 max_count => 100,
118 max_size => 0,
119 index => $index,
120 type => $elastic_type,
121 on_error => sub {
122 my ($action, $response, $i) = @_;
123 print STDERR "Error in elastic $action ". Dumper($response)."\n";
124 }
125 );
126  
127 my $mce = eval {
128 MCE->new(
129 max_workers => 10,
130 chunk_size => 1,
131 input_data => \&get_data,
132 user_func => \&lookup_email,
133 user_end => \&flush,
134 gather => \&reindex_order
135 )
136 };
137  
138 if ($@) {
139 print STDERR "Cannot create parallel workers: $@";
140 exit;
141 }
142  
143 eval { $mce->run(); };
144 print "Error $@" if $@;
145 print "Flushing buffer\n";
146 $bulk->flush;
147  
148 print "$count total records\n";
149  
150 my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });
151 open my $fh, ">:encoding(utf8)", "res2.csv" or die "new.csv: $!";
152 foreach my $z (@result) {
153 $csv->print($fh, $z);
154 print $fh "\r\n";
155 }
156 close($fh);
157 exit;
158  
159  
160 sub get_data {
161 return undef if $c > 5;
162 while (my $x = get_next($scroll)) {
163 #print Dumper($x);
164 my $asin = $x->{Item}->{ASIN};
165 unless ($asin && exists($asin{$asin})) {
166 #print "Skipping - wrong product\n";
167 next;
168 }
169 unless ($x->{PurchaseDate} gt '2016-10-01T00:00:00') {
170 #print "Skipping - too old order\n";
171 next;
172 }
173 unless ($x->{ShippingAddress} && $x->{ShippingAddress}->{AddressLine1}) {
174 #print "Skipping - no address\n";
175 next;
176 }
177 if ($x->{AppendedData} || $x->{NoAppendMatch}) {
178 next;
179 }
180 $x->{ShippingAddress}->{BuyerName} = $x->{BuyerName}; # it seems to be cleaner
181 print "Returning ".$x->{SellerOrderId}."\n";
182 $c++;
183 return $x;
184 }
185 return undef;
186 }
187  
188 sub lookup_email {
189 my ( $mce, $chunk_ref, $chunk_id ) = @_;
190  
191 my $worker_id = 'worker #' . MCE->wid;
192 #print "worker $worker_id\n";
193 my $x = $chunk_ref->[0];
194 print "$worker_id got ".Dumper($x);
195  
196 return unless reftype($x) eq 'HASH';
197 if ($x->{AppendedData} || $x->{NoAppendMatch}) {
198 MCE->gather( $chunk_id, 1, $x );
199 return 0;
200 }
201  
202 my $data = {};
203 while ( my ($field, $code) = each %mws2datafiner) {
204 my $val = &{$code}($x->{ShippingAddress});
205 $data->{$field} = $val if $val;
206 }
207 #print Dumper($data);
208 my $d = $df->append_email($data);
209 my $status = 0;
210 if ($d) {
211 $d = $d->{datafinder} if $d->{datafinder};
212 #print "$worker_id got email append result ".Dumper($d);
213 $status = 1;
214  
215 if ($d->{'num-results'}) {
216 $x->{AppendedData} = $d;
217 print "$worker_id appended email to ".$x->{SellerOrderId}."\n";
218 } else {
219 $x->{NoAppendMatch} = 'Y';
220 print "$worker_id could not find email for ".$x->{SellerOrderId}."\n";
221 }
222 }
223
224 MCE->gather( $chunk_id, $status, $x );
225 }
226  
227 sub reindex_order {
228 my ( $chunk_id, $status, $x ) = @_;
229  
230 return unless reftype($x) eq 'HASH';
231  
232 if ($status) {
233 $count++;
234 my $id = $x->{_id};
235 delete($x->{_id});
236 #$bulk->index( { index => $index, id => $id, source => $x } );
237 print "Reindexing $id ".$x->{AmazonOrderId}." $count\n";
238 if ($x->{AppendedData}) {
239 foreach my $ap (@{$x->{AppendedData}->{results}}) {
240 push @result, [
241 $x->{AmazonOrderId},
242 $x->{BuyerName},
243 first_name($x->{BuyerName}),
244 last_name($x->{BuyerName}),
245 $x->{PurchaseDate},
246 $x->{OrderStatus},
247 $x->{Item}->{ASIN},
248 $x->{Item}->{SellerSKU},
249 $x->{Item}->{ItemPrice}->{Amount},
250 $x->{Item}->{ItemPrice}->{FinalAmount},
251 $x->{Item}->{QuantityOrdered},
252 $ap->{FirstName},
253 $ap->{LastName},
254 $ap->{Address},
255 $ap->{City},
256 $ap->{State},
257 $ap->{Zip} . ($ap->{Zip4} ? '-'.$ap->{Zip4} : ''),
258 $ap->{EmailAddr},
259 $ap->{EmailAddrUsable}
260 ];
261 }
262 }
263 }
264  
265 return 1;
266 }
267  
268 sub flush {
269  
270 }
271  
272 sub get_next {
273 my ($scroll) = @_;
274  
275 my ( $data, $error );
276 try {
277 $data = $scroll->next();
278 }
279 catch {
280 $error = $_;
281 };
282  
283 if ( defined $error ) {
284 my $last_scroll_id = $scroll->_scroll_id;
285 # prevents 'finish' call for missed scroll_id
286 $scroll->_set_is_finished(1);
287  
288 if ( ref($error) && $error->is('Missing') ) {
289 print qq{[elastic]: Renewing expired scroll $last_scroll_id\n};
290 return get_next($scroll);
291 } else {
292 print qq{Elastic error: $error\n};
293 }
294 }
295 if ($data) {
296 my $x = $data->{_source};
297 $x->{_id} = $data->{_id};
298 return $x;
299 }
300 return undef;
301 }
302  
303 sub first_name {
304 my ($x) = @_;
305 if ($x =~ m/^(\w+)\,\s*([\w\-]+)/) {
306 # lastname, first
307 return $2;
308 }
309 my ($n) = split(/\s+/, $x);
310 return $n;
311 }
312  
313 sub last_name {
314 my ($x) = @_;
315 if ($x =~ m/^(\w+)\,\s*([\w\-]+)/) {
316 # lastname, first
317 return $1;
318 }
319 my @n = split(/\s+/, $x);
320 return $n[-1];
321 }