MWS/Uploader.pm

filter: Statementstmt 10.6% 106 / 998 Branchbran 0.0% 0 / 454 Conditioncond 0.0% 0 / 99 MC/DCmcdc 0.0% 0 / 57 Subroutinesub 16.7% 22 / 131 Podpod 100% 49 / 49 totaltotal 9.9% 177 / 1788 CC 296 SCAR 47.1
CC
296
Cov
7%
product_needs_upload
600.0
_build_products_to_upload
420.0
upload_feed
420.0
CRAP 110.9
↑ Summary MWS/XML/Product.pm »
1 package Amazon::MWS::Uploader;
2  
3 6 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 6 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use Amazon::MWS::XML::Feed;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 6 ▶use Amazon::MWS::XML::Order;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 6 ▶use Amazon::MWS::Client;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 6 ▶use Amazon::MWS::XML::Response::FeedSubmissionResult;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 6 ▶use Amazon::MWS::XML::Response::OrderReport;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 6 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 6 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 6 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 6 ▶use SQL::Abstract;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 6 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 6 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 6 ▶use Scalar::Util qw/blessed/;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 6 ▶use XML::Compile::Schema;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 6 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 6 ▶use MooX::Types::MooseLike::Base qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
24 6 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 6 our $VERSION = '0.18';
27  
28 6 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
29 AMW_ORDER_WILDCARD_ERROR => 999999,
30 DEBUG => $ENV{AMZ_UPLOADER_DEBUG},
31 6 };
32  
33 =head1 NAME
34  
35 Amazon::MWS::Uploader -- high level agent to upload products to AMWS
36  
37 =head1 DESCRIPTION
38  
39 This module provide an high level interface to the upload process. It
40 has to keep track of the state to resume the uploading, which could
41 get stuck on the Amazon's side processing, so database credentials
42 have to be provided (or the database handle itself).
43  
44 The table structure needed is defined and commented in sql/amazon.sql
45  
46 =head1 SYNOPSIS
47  
48 my $agent = Amazon::MWS::Uploader->new(
49 db_dsn => 'DBI:mysql:database=XXX',
50 db_username => 'xxx',
51 db_password => 'xxx',
52 db_options => \%options
53 # or dbh => $dbh,
54
55 schema_dir => '/path/to/xml_schema',
56 feed_dir => '/path/to/directory/for/xml',
57
58 merchant_id => 'xxx',
59 access_key_id => 'xxx',
60 secret_key => 'xxx',
61
62 marketplace_id => 'xxx',
63 endpoint => 'xxx',
64
65 products => \@products,
66 );
67
68 # say once a day, retrieve the full batch and send it up
69 $agent->upload;
70
71 # every 10 minutes or so, continue the work started with ->upload, if any
72 $agent->resume;
73  
74  
75 =head1 UPGRADE NOTES
76  
77 When migrating from 0.05 to 0.06 please execute this SQL statement
78  
79 ALTER TABLE amazon_mws_products ADD COLUMN listed BOOLEAN;
80 UPDATE amazon_mws_products SET listed = 1 WHERE status = 'ok';
81  
82 When upgrading to 0.16, please execute this SQL statement:
83  
84 ALTER TABLE amazon_mws_products ADD COLUMN warnings TEXT;
85  
86 =head1 ACCESSORS
87  
88 The following keys must be passed at the constructor and can be
89 accessed read-only:
90  
91 =over 4
92  
93 =item dbh
94  
95 The DBI handle. If not provided will be built using the following
96 self-describing accessor:
97  
98 =item db_dsn
99  
100 =item db_username
101  
102 =item db_password
103  
104 =item db_options
105  
106 E.g.
107  
108 {
109 mysql_enable_utf8 => 1,
110 }
111  
112 AutoCommit and RaiseError are set by us.
113  
114 =cut
115  
116 6 has db_dsn => (is => 'ro');
117 6 has db_password => (is => 'ro');
118 6 has db_username => (is => 'ro');
119 6 has db_options => (is => 'ro',
120 isa => AnyOf[Undef,HashRef],
121 );
122 6 has dbh => (is => 'lazy');
123  
124 =item skus_warnings_modes
125  
126 Determines how to treat warnings. This is a hash reference with the
127 code of the warning as key and one of the following modes as value:
128  
129 =over 4
130  
131 =item warn
132  
133 Prints warning from Amazon with C<warn> function (default mode).
134  
135 =item print
136  
137 Prints warning from Amazon with C<print> function (default mode).
138  
139 =item skip
140  
141 Ignores warning from Amazon.
142  
143 =back
144  
145 =cut
146  
147 has skus_warnings_modes => (is => 'rw',
148 isa => HashRef,
149 0 ▶ default => sub {{}},
Subroutine __ANON__: not called CC=1 SCAR=6.9
150 6 );
151  
152 =item order_days_range
153  
154 When calling get_orders, check the orders for the last X days. It
155 accepts an integer which should be in the range 1-30. Defaults to 7.
156  
157 Keep in mind that if you change the default and you have a lot of
158 orders, you will get throttled because for each order we retrieve the
159 orderline as well.
160  
161 DEVEL NOTE: a possible smart fix would be to store this object in the
162 order (or into a closure) and make the orderline a lazy attribute
163 which will call C<ListOrderItems>.
164  
165 =cut
166  
167 has order_days_range => (is => 'rw',
168 0 ▶ default => sub { 7 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
169 0 ▶ isa => sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
170 0 my $days = $_[0];
171 0 ▶ die "Not an integer"
Branch: 1 branch
BranchTrueFalseTotal
unless is_Int($days) 0 0 0
172 unless is_Int($days);
173 0 ▶ die "$days is out of range 1-30"
Branch: 1 branch
BranchTrueFalseTotal
unless $days > 0 and $days < 31 0 0 0
Condition0%0/3
$days > 0 and $days < 31
!ll&&!rl&&r
000
MC/DC0%0/2
$days > 0 and $days < 31
$days > 0 $days < 31
Truth table0%0/3
A and B
A= $days > 0B= $days < 31
ABresult
0X0
100
111
174 unless $days > 0 && $days < 31;
175 6 });
176  
177 =item shop_id
178  
179 You can pass an arbitrary identifier to the constructor which will be
180 used to keep the database records separated if you have multiple
181 amazon accounts. If not provided, the merchant id will be used, which
182 will work, but it's harder (for the humans) to spot and debug.
183  
184 =cut
185  
186 6 has shop_id => (is => 'ro');
187  
188 6 has _unique_shop_id => (is => 'lazy');
189  
190 0 ▶sub _build__unique_shop_id {
Subroutine _build__unique_shop_id: not called CC=2 SCAR=17.9
191 0 my $self = shift;
192 0 ▶ if (my $id = $self->shop_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = $self->shop_id) { } 0 0 0
193 0 return $id;
194 }
195 else {
196 0 return $self->merchant_id;
197 }
198 }
199  
200 =item debug
201  
202 Print out additional information.
203  
204 =item logfile
205  
206 Passed to L<Amazon::MWS::Client> constructor.
207  
208 =cut
209  
210 6 has debug => (is => 'ro');
211  
212 6 has logfile => (is => 'ro');
213  
214 =item quiet
215  
216 Boolean. Do not warn on timeouts and aborts (just print) if set to
217 true.
218  
219 =cut
220  
221 6 has quiet => (is => 'ro');
222  
223 0 ▶sub _build_dbh {
Subroutine _build_dbh: not called CC=4 SCAR=30.0
224 0 my $self = shift;
225 0 my $dsn = $self->db_dsn;
226 0 ▶ die "Missing dns" unless $dsn;
Branch: 1 branch
BranchTrueFalseTotal
unless $dsn 0 0 0
227 0 ▶ my $options = $self->db_options || {};
Condition0%0/2
$self->db_options || {}
l!l
00
MC/DC0%0/1
$self->db_options || {}
$self->db_options
Truth table0%0/2
A
A= $self->db_options
Aresult
11
00
228 # forse raise error and auto-commit
229 0 $options->{RaiseError} = 1;
230 0 $options->{AutoCommit} = 1;
231 0 ▶ my $dbh = DBI->connect($dsn, $self->db_username, $self->db_password,
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = "DBI"->connect($dsn, $self->db_username, $self->db_password, $options) or die "Couldn't connect to $dsn!" 0 0 0
232 $options) or die "Couldn't connect to $dsn!";
233 0 return $dbh;
234 }
235  
236 =item purge_missing_products
237  
238 If true, the first time C<products_to_upload> is called, products not
239 passed to the C<products> constructor will be purged from the
240 C<amazon_mws_products> table. Default to false.
241  
242 This setting is DEPRECATED because can have some unwanted
243 side-effects. You are recommended to delete the obsoleted products
244 yourself.
245  
246 =cut
247  
248 6 has purge_missing_products => (is => 'rw');
249  
250  
251 =item reset_all_errors
252  
253 If set to a true value, don't skip previously failed items and
254 effectively reset all of them.
255  
256 Also, when the accessor is set for send_shipping_confirmation, try to
257 upload again previously failed orders.
258  
259 =cut
260  
261 6 has reset_all_errors => (is => 'ro');
262  
263 =item reset_errors
264  
265 A string containing a comma separated list of error codes, optionally
266 prefixed with a "!" (to reverse its meaning).
267  
268 Example:
269  
270 "!6024,6023"
271  
272 Meaning: reupload all the products whose error code is B<not> 6024 or
273 6023.
274  
275 "6024,6023"
276  
277 Meaning: reupload the products whose error code was 6024 or 6023
278  
279 =cut
280  
281 has reset_errors => (is => 'ro',
282 0 ▶ isa => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
283 0 my $string = $_[0];
284 # undef/0/'' is fine
285 0 ▶ if ($string) {
Branch: 1 branch
BranchTrueFalseTotal
if ($string) 0 0 0
286 0 ▶ die "reset_errors must be a comma separated list of error code, optionally prefixed by a '!' to negate its meaning"
Branch: 1 branch
BranchTrueFalseTotal
if not $string =~ /^\s*!?\s*(([0-9]+)(\s*,\s*)?)+/ 0 0 0
287 if $string !~ m/^\s*!?\s*(([0-9]+)(\s*,\s*)?)+/;
288 }
289 6 });
290  
291  
292 6 has _reset_error_structure => (is => 'lazy');
293  
294 0 ▶sub _build__reset_error_structure {
Subroutine _build__reset_error_structure: not called CC=5 SCAR=34.0
295 0 my $self = shift;
296 0 ▶ my $reset_string = $self->reset_errors || '';
Condition0%0/2
$self->reset_errors || ''
l!l
00
MC/DC0%0/1
$self->reset_errors || ''
$self->reset_errors
Truth table0%0/2
A
A= $self->reset_errors
Aresult
11
00
297 0 $reset_string =~ s/^\s*//;
298 0 $reset_string =~ s/\s*$//;
299 0 ▶ return unless $reset_string;
Branch: 1 branch
BranchTrueFalseTotal
unless $reset_string 0 0 0
300  
301 0 my $negate = 0;
302 0 ▶ if ($reset_string =~ m/^\s*!\s*(.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($reset_string =~ /^\s*!\s*(.+)/) 0 0 0
303 0 $reset_string = $1;
304 0 $negate = 1;
305 }
306 0 my %codes = map { $_ => 1 } grep { $_ } split(/\s*,\s*/, $reset_string);
307 0 ▶ return unless %codes;
Branch: 1 branch
BranchTrueFalseTotal
unless %codes 0 0 0
308 return {
309 0 negate => $negate,
310 codes => \%codes,
311 };
312 }
313  
314  
315 =item force
316  
317 Same as above, but only for the selected items. An arrayref is
318 expected here with the B<skus>.
319  
320 =cut
321  
322 6 has force => (is => 'ro',
323 isa => ArrayRef,
324 );
325  
326  
327 6 has _force_hashref => (is => 'lazy');
328  
329 0 ▶sub _build__force_hashref {
Subroutine _build__force_hashref: not called CC=2 SCAR=17.9
330 0 my $self = shift;
331 0 my %forced;
332 0 ▶ if (my $arrayref = $self->force) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $arrayref = $self->force) 0 0 0
333 0 %forced = map { $_ => 1 } @$arrayref;
334 }
335 0 return \%forced;
336 }
337  
338 =item limit_inventory
339  
340 If set to an integer, limit the inventory to this value. Setting this
341 to 0 will disable it.
342  
343 =item job_hours_timeout
344  
345 If set to an integer, abort the job after X hours are elapsed since
346 the job was started. Default to 3 hours. Set to 0 to disable (not
347 recommended).
348  
349 This doesn't affect jobs for order acknowledgements (C<order_ack>), see below.
350  
351 =item order_ack_days_timeout
352  
353 Order acknowlegments times out at different rate, because it's somehow
354 sensitive.
355  
356 =cut
357  
358 has job_hours_timeout => (is => 'ro',
359 isa => Int,
360 0 ▶ default => sub { 3 });
Subroutine __ANON__: not called CC=1 SCAR=1.2
361  
362 has order_ack_days_timeout => (is => 'ro',
363 isa => Int,
364 0 ▶ default => sub { 30 });
Subroutine __ANON__: not called CC=1 SCAR=1.2
365  
366 6 has limit_inventory => (is => 'ro',
367 isa => Int);
368  
369 =item schema_dir
370  
371 The directory where the xsd files for the feed building can be found.
372  
373 =item feeder
374  
375 A L<Amazon::MWS::XML::Feed> object. Lazy attribute, you shouldn't pass
376 this to the constructor, it is lazily built using C<products>,
377 C<merchant_id> and C<schema_dir>.
378  
379 =item feed_dir
380  
381 A working directory where to stash the uploaded feeds for inspection
382 if problems are detected.
383  
384 =item schema
385  
386 The L<XML::Compile::Schema> object, built lazily from C<feed_dir>
387  
388 =item xml_writer
389  
390 The xml writer, built lazily.
391  
392 =item xml_reader
393  
394 The xml reader, built lazily.
395  
396 =cut
397  
398 has schema_dir => (is => 'ro',
399 required => 1,
400 0 ▶ isa => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
401 0 ▶ die "$_[0] is not a directory" unless -d $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless -d $_[0] 0 0 0
402 6 });
403  
404 has feed_dir => (is => 'ro',
405 required => 1,
406 0 ▶ isa => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
407 0 ▶ die "$_[0] is not a directory" unless -d $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless -d $_[0] 0 0 0
408 6 });
409  
410 6 has schema => (is => 'lazy');
411  
412 0 ▶sub _build_schema {
Subroutine _build_schema: not called CC=1 SCAR=1.7
413 0 my $self = shift;
414 0 my $files = File::Spec->catfile($self->schema_dir, '*.xsd');
415 0 ▶ my $schema = XML::Compile::Schema->new([glob $files]);
Subroutine BEGIN: called CC=1 SCAR=0.2
416 0 return $schema;
417 }
418  
419 6 has xml_writer => (is => 'lazy');
420  
421 0 ▶sub _build_xml_writer {
Subroutine _build_xml_writer: not called CC=1 SCAR=6.9
422 0 my $self = shift;
423 0 return $self->schema->compile(WRITER => 'AmazonEnvelope');
424 }
425  
426 6 has xml_reader => (is => 'lazy');
427  
428 0 ▶sub _build_xml_reader {
Subroutine _build_xml_reader: not called CC=1 SCAR=6.9
429 0 my $self = shift;
430 0 return $self->schema->compile(READER => 'AmazonEnvelope');
431 }
432  
433  
434 =item generic_feeder
435  
436 Return a L<Amazon::MWS::XML::GenericFeed> object to build a feed using
437 the XML writer.
438  
439 =cut
440  
441 0 ▶sub generic_feeder {
Subroutine generic_feeder: not called CC=1 SCAR=6.9
Pod documented
442 0 my $self = shift;
443 0 return Amazon::MWS::XML::GenericFeed->new(
444 xml_writer => $self->xml_writer,
445 merchant_id => $self->merchant_id,
446 );
447 }
448  
449  
450 =item merchant_id
451  
452 The merchant ID provided by Amazon.
453  
454 =item access_key_id
455  
456 Provided by Amazon.
457  
458 =item secret_key
459  
460 Provided by Amazon.
461  
462 =item marketplace_id
463  
464 L<http://docs.developer.amazonservices.com/en_US/dev_guide/DG_Endpoints.html>
465  
466 =item endpoint
467  
468 Ditto.
469  
470 =cut
471  
472 6 has merchant_id => (is => 'ro', required => 1);
473 6 has access_key_id => (is => 'ro', required => 1);
474 6 has secret_key => (is => 'ro', required => 1);
475 6 has marketplace_id => (is => 'ro', required => 1);
476 6 has endpoint => (is => 'ro', required => 1);
477  
478 =item products
479  
480 An arrayref of L<Amazon::MWS::XML::Product> objects, or anything that
481 (properly) responds to C<as_product_hash>, C<as_inventory_hash>,
482 C<as_price_hash>. See L<Amazon::MWS::XML::Product> for details.
483  
484 B<This is set as read-write, so you can set the product after the
485 object construction, but if you change it afterward, you will get
486 unexpected results>.
487  
488 This routine also check if the product needs upload and delete
489 disappeared products. If you are doing the check yourself, use
490 C<checked_products>.
491  
492 =item checked_products
493  
494 As C<products>, but no check is performed. This takes precedence.
495  
496 =item sqla
497  
498 Lazy attribute to hold the C<SQL::Abstract> object.
499  
500 =cut
501  
502 6 has products => (is => 'rw',
503 isa => ArrayRef);
504  
505 has sqla => (
506 is => 'ro',
507 0 ▶ default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
508 0 return SQL::Abstract->new;
509 }
510 6 );
511  
512 6 has existing_products => (is => 'lazy');
513  
514 0 ▶sub _build_existing_products {
Subroutine _build_existing_products: not called CC=3 SCAR=24.8
515 0 my $self = shift;
516 0 my $sth = $self->_exe_query($self->sqla->select(amazon_mws_products => [qw/sku
517 timestamp_string
518 status
519 listed
520 error_code
521 /],
522 {
523 status => { -not_in => [qw/deleted/] },
524 shop_id => $self->_unique_shop_id,
525 }));
526 0 my %uploaded;
527 0 ▶ while (my $row = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 0 0 0
528 0 ▶ $row->{timestamp_string} ||= 0;
Condition0%0/2
$row->{"timestamp_string"} ||= 0
l!l
00
MC/DC0%0/1
$row->{"timestamp_string"} ||= 0
$row->{"timestamp_string"}
Truth table0%0/2
A
A= $row->{"timestamp_string"}
Aresult
11
00
529 0 $uploaded{$row->{sku}} = $row;
530 }
531 0 return \%uploaded;
532 }
533  
534 6 has products_to_upload => (is => 'lazy');
535  
536 6 has checked_products => (is => 'rw', isa => ArrayRef);
537  
538 0 ▶sub _build_products_to_upload {
Subroutine _build_products_to_upload: not called CC=20 SCAR=60.4
539 0 my $self = shift;
540 0 ▶ if (my $checked = $self->checked_products) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $checked = $self->checked_products) 0 0 0
541 0 return $checked;
542 }
543 0 my $product_arrayref = $self->products;
544 0 ▶ return [] unless $product_arrayref && @$product_arrayref;
Branch: 1 branch
BranchTrueFalseTotal
unless $product_arrayref and @$product_arrayref 0 0 0
Condition0%0/3
$product_arrayref and @$product_arrayref
!ll&&!rl&&r
000
MC/DC0%0/2
$product_arrayref and @$product_arrayref
$product_arrayref @$product_arrayref
Truth table0%0/3
A and B
A= $product_arrayrefB= @$product_arrayref
ABresult
0X0
100
111
545 0 my @products = @$product_arrayref;
546 0 my $existing = $self->existing_products;
547 0 my @todo;
548 0 foreach my $product (@products) {
549 0 my $sku = $product->sku;
550 0 ▶ if (my $exists = $existing->{$sku}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $exists = $existing->{$sku}) 0 0 0
551 # mark the item as visited
552 0 $exists->{_examined} = 1;
553 }
554 0 ▶ print "Checking $sku\n" if $self->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 0 0
555 0 ▶ next unless $self->product_needs_upload($product->sku, $product->timestamp_string);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->product_needs_upload($product->sku, $product->timestamp_string) 0 0 0
556  
557 0 print "Scheduling product " . $product->sku . " for upload\n";
558 0 ▶ if (my $limit = $self->limit_inventory) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $limit = $self->limit_inventory) 0 0 0
559 0 my $real = $product->inventory;
560 0 ▶ if ($real > $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($real > $limit) 0 0 0
561 0 ▶ print "Limiting the $sku inventory from $real to $limit\n" if $self->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 0 0
562 0 $product->inventory($limit);
563 }
564 }
565 0 ▶ if (my $children = $product->children) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $children = $product->children) 0 0 0
566 0 my @good_children;
567 0 foreach my $child (@$children) {
568 # skip failed children, but if the current status of
569 # parent is failed, and we reached this point, retry.
570 0 ▶ if (! exists $self->_force_hashref->{$child} and
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $self->_force_hashref->{$child} and $existing->{$child} and $existing->{$sku} and $existing->{$sku}{'status'} ne 'failed' and $existing->{$child}{'status'} eq 'failed') { } 0 0 0
Condition0%0/12
not exists $self->_force_hashref->{$child} and $existing->{$child} and $existing->{$sku} and $existing->{$sku}{"status"} ne "failed" and $existing->{$child}{"status"} eq "failed"
!ll&&!rl&&r
000
not exists $self->_force_hashref->{$child} and $existing->{$child} and $existing->{$sku} and $existing->{$sku}{"status"} ne "failed"
!ll&&!rl&&r
000
not exists $self->_force_hashref->{$child} and $existing->{$child} and $existing->{$sku}
!ll&&!rl&&r
000
not exists $self->_force_hashref->{$child} and $existing->{$child}
!ll&&!rl&&r
000
MC/DC0%0/5
not exists $self->_force_hashref->{$child} and $existing->{$child} and $existing->{$sku} and $existing->{$sku}{"status"} ne "failed" and $existing->{$child}{"status"} eq "failed"
not exists $self->_force_hashref->{$child} $existing->{$child} $existing->{$sku} $existing->{$sku}{"status"} ne "failed" $existing->{$child}{"status"} eq "failed"
Truth table0%0/6
not(A) and B and C and D and E
A= not exists $self->_force_hashref->{$child}B= $existing->{$child}C= $existing->{$sku}D= $existing->{$sku}{"status"} ne "failed"E= $existing->{$child}{"status"} eq "failed"
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
571 $existing->{$child} and
572 $existing->{$sku} and
573 $existing->{$sku}->{status} ne 'failed' and
574 $existing->{$child}->{status} eq 'failed') {
575 0 print "Ignoring failed variant $child\n";
576 }
577 else {
578 0 push @good_children, $child;
579 }
580 }
581 0 $product->children(\@good_children);
582 }
583 0 push @todo, $product;
584 }
585 0 ▶ if ($self->purge_missing_products) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->purge_missing_products) 0 0 0
586 # nuke the products not passed
587 # print Dumper($existing);
588 0 my @deletions = map { $_->{sku} }
589 0 grep { !$_->{_examined} }
590 values %$existing;
591 0 ▶ if (@deletions) {
Branch: 1 branch
BranchTrueFalseTotal
if (@deletions) 0 0 0
592 0 $self->delete_skus(@deletions);
593 }
594 }
595 0 return \@todo;
596 }
597  
598  
599 =item client
600  
601 An L<Amazon::MWS::Client> object, built lazily, so you don't have to
602 pass it.
603  
604 =back
605  
606 =cut
607  
608 6 has client => (is => 'lazy');
609  
610 0 ▶sub _build_client {
Subroutine _build_client: not called CC=1 SCAR=6.9
611 0 my $self = shift;
612 0 my %mws_args = map { $_ => $self->$_ } (qw/merchant_id
613 marketplace_id
614 access_key_id
615 secret_key
616 debug
617 logfile
618 endpoint/);
619  
620 0 return Amazon::MWS::Client->new(%mws_args);
621 }
622  
623 6 has _mismatch_patterns => (is => 'lazy', isa => HashRef);
624  
625 0 ▶sub _build__mismatch_patterns {
Subroutine _build__mismatch_patterns: not called CC=1 SCAR=6.9
626 0 my $self = shift;
627 0 my $merchant_re = qr{\s+\((?:Merchant|Verkäufer):\s+'(.*?)'\s+/};
628 0 my $amazon_re = qr{\s+.*?/\s*Amazon:\s+'(.*?)'\)};
629 0 my %patterns = (
630 # informative only
631 asin => qr{ASIN(?:\s+überein)?\s+([0-9A-Za-z]+)},
632  
633 shop_part_number => qr{part_number$merchant_re},
634 amazon_part_number => qr{part_number$amazon_re},
635  
636 shop_title => qr{item_name$merchant_re},
637 amazon_title => qr{item_name$amazon_re},
638  
639 shop_manufacturer => qr{manufacturer$merchant_re},
640 amazon_manufacturer => qr{manufacturer$amazon_re},
641  
642 shop_brand => qr{brand$merchant_re},
643 amazon_brand => qr{brand$amazon_re},
644  
645 shop_color => qr{color$merchant_re},
646 amazon_color => qr{color$amazon_re},
647  
648 shop_size => qr{size$merchant_re},
649 amazon_size => qr{size$amazon_re},
650  
651 );
652 0 return \%patterns;
653 }
654  
655  
656 =head1 MAIN METHODS
657  
658 =head2 upload
659  
660 If the products is set, begin the routine to upload them. Because of
661 the asynchronous way AMWS works, at some point it will bail out,
662 saving the state in the database. You should reinstantiate the object
663 and call C<resume> on it every 10 minutes or so.
664  
665 The workflow is described here:
666 L<http://docs.developer.amazonservices.com/en_US/feeds/Feeds_Overview.html>
667  
668 This has to be done for each feed: Product, Inventory, Price, Image,
669 Relationship (for variants).
670  
671 This method first generate the feeds in the feed directory, and then
672 calls C<resume>, which is in charge for the actual uploading.
673  
674 =head2 resume
675  
676 Restore the state and resume where it was left.
677  
678 This method accepts an optional list of parameters. Each parameter may be:
679  
680 =over 4
681  
682 =item a scalar
683  
684 This is considered a job id.
685  
686 =item a hashref
687  
688 This will be merged in the query to retrieve the pending jobs. A
689 sample usage could be:
690  
691 $upload->resume({ task => [qw/upload product_deletion/] });
692  
693 to resume only those specific tasks.
694  
695 =back
696  
697 =head2 get_pending_jobs
698  
699 Return the list of hashref with the pending jobs out of the database.
700 Accepts the same parameters as C<resume> (which actually calls this
701 method).
702  
703 =cut
704  
705 =head1 INTERNAL METHODS
706  
707 =head2 prepare_feeds($type, { name => $feed_name, content => "<xml>..."}, { name => $feed_name2, content => "<xml>..."}, ....)
708  
709 Prepare the feed of type $type with the feeds provided as additional
710 arguments.
711  
712 Return the job id
713  
714  
715 =cut
716  
717 0 ▶sub _feed_job_dir {
Subroutine _feed_job_dir: not called CC=7 SCAR=40.3
718 0 my ($self, $job_id, $create) = @_;
719 0 ▶ die unless $job_id;
Branch: 1 branch
BranchTrueFalseTotal
unless $job_id 0 0 0
720 0 my $shop_id = $self->_unique_shop_id;
721 0 $shop_id =~ s/[^0-9A-Za-z_-]//g;
722 0 ▶ die "The shop id without word characters results in an empty string"
Branch: 1 branch
BranchTrueFalseTotal
unless $shop_id 0 0 0
723 unless $shop_id;
724 0 my $feed_root = File::Spec->catdir($self->feed_dir,
725 $shop_id);
726 0 ▶ if ($create) {
Branch: 1 branch
BranchTrueFalseTotal
if ($create) 0 0 0
727 0 ▶ mkdir $feed_root unless -d $feed_root;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $feed_root 0 0 0
728 }
729  
730 0 my $feed_subdir = File::Spec->catdir($feed_root,
731 $job_id);
732 0 ▶ if ($create) {
Branch: 1 branch
BranchTrueFalseTotal
if ($create) 0 0 0
733 0 ▶ mkdir $feed_subdir unless -d $feed_subdir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $feed_subdir 0 0 0
734 }
735 0 return $feed_subdir;
736 }
737  
738 0 ▶sub _feed_file_for_method {
Subroutine _feed_file_for_method: not called CC=3 SCAR=24.8
739 0 my ($self, $job_id, $feed_type) = @_;
740 0 ▶ die unless $job_id && $feed_type;
Branch: 1 branch
BranchTrueFalseTotal
unless $job_id and $feed_type 0 0 0
Condition0%0/3
$job_id and $feed_type
!ll&&!rl&&r
000
MC/DC0%0/2
$job_id and $feed_type
$job_id $feed_type
Truth table0%0/3
A and B
A= $job_idB= $feed_type
ABresult
0X0
100
111
741 0 my $feed_subdir = $self->_feed_job_dir($job_id, "create");
742 0 my $file = File::Spec->catfile($feed_subdir, $feed_type . '.xml');
743 0 return File::Spec->rel2abs($file);
744 }
745  
746 0 ▶sub _slurp_file {
Subroutine _slurp_file: not called CC=2 SCAR=17.9
747 0 my ($self, $file) = @_;
748 0 ▶ open (my $fh, '<', $file) or die "Couldn't open $file $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or die "Couldn't open $file $!" 0 0 0
749 0 local $/ = undef;
750 0 my $content = <$fh>;
751 0 close $fh;
752 0 return $content;
753 }
754  
755 0 ▶sub upload {
Subroutine upload: not called CC=5 SCAR=34.0
Pod documented
756 0 my $self = shift;
757 # create the feeds to be uploaded using the products
758 0 my @products = @{ $self->products_to_upload };
759  
760 0 ▶ unless (@products) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@products) 0 0 0
761 0 print "No products, can't upload anything\n";
762 0 return;
763 }
764 0 my $feeder = Amazon::MWS::XML::Feed->new(
765 products => \@products,
766 xml_writer => $self->xml_writer,
767 merchant_id => $self->merchant_id,
768 );
769 0 my @feeds;
770 0 foreach my $feed_name (qw/product
771 inventory
772 price
773 image
774 variants
775 /) {
776 0 my $method = $feed_name . "_feed";
777 0 ▶ if (my $content = $feeder->$method) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $content = $feeder->$method) 0 0 0
778 0 push @feeds, {
779 name => $feed_name,
780 content => $content,
781 };
782 }
783 }
784 0 ▶ if (my $job_id = $self->prepare_feeds(upload => \@feeds)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $job_id = $self->prepare_feeds("upload", \@feeds)) 0 0 0
785 0 $self->_mark_products_as_pending($job_id, @products);
786 0 return $job_id;
787 }
788 0 return;
789 }
790  
791 0 ▶sub _mark_products_as_pending {
Subroutine _mark_products_as_pending: not called CC=4 SCAR=30.0
792 0 my ($self, $job_id, @products) = @_;
793 0 ▶ die "Bad usage" unless $job_id;
Branch: 1 branch
BranchTrueFalseTotal
unless $job_id 0 0 0
794 # these skus were cleared up when asking for the products to upload
795 0 foreach my $p (@products) {
796 0 my %identifier = (
797 sku => $p->sku,
798 shop_id => $self->_unique_shop_id,
799 );
800 0 my %data = (
801 amws_job_id => $job_id,
802 status => 'pending',
803 warnings => '', # clear out
804 timestamp_string => $p->timestamp_string,
805 );
806 0 my $check = $self
807 ->_exe_query($self->sqla->select(amazon_mws_products => [qw/sku/], { %identifier }));
808 0 my $existing = $check->fetchrow_hashref;
809 0 $check->finish;
810 0 ▶ if ($existing) {
Branch: 1 branch
BranchTrueFalseTotal
if ($existing) { } 0 0 0
811 0 $self->_exe_query($self->sqla->update(amazon_mws_products => \%data, \%identifier));
812 }
813 else {
814 0 $self->_exe_query($self->sqla->insert(amazon_mws_products => { %identifier, %data }));
815 }
816 }
817 }
818  
819  
820 0 ▶sub prepare_feeds {
Subroutine prepare_feeds: not called CC=8 SCAR=42.8
Pod documented
821 0 my ($self, $task, $feeds) = @_;
822 0 ▶ die "Missing task ($task) and feeds ($feeds)" unless $task && $feeds;
Branch: 1 branch
BranchTrueFalseTotal
unless $task and $feeds 0 0 0
Condition0%0/3
$task and $feeds
!ll&&!rl&&r
000
MC/DC0%0/2
$task and $feeds
$task $feeds
Truth table0%0/3
A and B
A= $taskB= $feeds
ABresult
0X0
100
111
823 0 ▶ return unless @$feeds; # nothing to do
Branch: 1 branch
BranchTrueFalseTotal
unless @$feeds 0 0 0
824 0 my $job_id = $task . "-" . DateTime->now->strftime('%F-%H-%M-%S');
825 0 my $job_started_epoch = time();
826  
827 0 $self->_exe_query($self->sqla
828 ->insert(amazon_mws_jobs => {
829 amws_job_id => $job_id,
830 shop_id => $self->_unique_shop_id,
831 task => $task,
832 job_started_epoch => $job_started_epoch,
833 }));
834  
835 # to complete the process, we need to fill out these five
836 # feeds. every feed has the same procedure, as per
837 # http://docs.developer.amazonservices.com/en_US/feeds/Feeds_Overview.html
838 # so we put a flag on the feed when it is done. The processing
839 # of the feed itself is tracked in the amazon_mws_feeds
840  
841 # TODO: we could pass to the object some flags to filter out results.
842 0 foreach my $feed (@$feeds) {
843 # write out the feed if we got something to do, and add a row
844 # to the feeds.
845  
846 # when there is no content, no need to create a job for it.
847 0 ▶ if (my $content = $feed->{content}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $content = $feed->{"content"}) 0 0 0
848 0 ▶ my $name = $feed->{name} or die "Missing feed_name";
Branch: 1 branch
BranchTrueFalseTotal
my $name = $feed->{"name"} or die "Missing feed_name" 0 0 0
849 0 my $file = $self->_feed_file_for_method($job_id, $name);
850 0 ▶ open (my $fh, '>', $file) or die "Couldn't open $file $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $file or die "Couldn't open $file $!" 0 0 0
851 0 print $fh $content;
852 0 close $fh;
853 # and prepare a row for it
854  
855 0 my $insertion = {
856 feed_name => $name,
857 feed_file => $file,
858 amws_job_id => $job_id,
859 shop_id => $self->_unique_shop_id,
860 };
861 0 $self->_exe_query($self->sqla
862 ->insert(amazon_mws_feeds => $insertion));
863 }
864 }
865 0 return $job_id;
866 }
867  
868  
869 0 ▶sub get_pending_jobs {
Subroutine get_pending_jobs: not called CC=17 SCAR=57.2
Pod documented
870 0 my ($self, @args) = @_;
871 0 my %additional;
872 my @named_jobs;
873 0 foreach my $arg (@args) {
874 0 ▶ if (!ref($arg)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not ref $arg) { } 0 0 0
elsif (ref $arg eq 'HASH') { } 0 0 0
875 0 push @named_jobs, $arg;
876 }
877 elsif (ref($arg) eq 'HASH') {
878 # add the filters
879 0 foreach my $key (keys %$arg) {
880 0 ▶ if ($additional{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($additional{$key}) { } 0 0 0
881 0 die "Attempt to overwrite $key in the additional parameters!\n";
882 }
883 else {
884 0 $additional{$key} = $arg->{$key};
885 }
886 }
887 }
888 else {
889 0 die "Argument must be either a scalar with a job name and/or "
890 . "an hashref with additional filters!";
891 }
892 }
893 0 ▶ if (@named_jobs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@named_jobs) 0 0 0
894 0 $additional{amws_job_id} = { -in => \@named_jobs };
895 }
896 0 my ($stmt, @bind) = $self->sqla->select(amazon_mws_jobs => '*',
897 {
898 %additional,
899 aborted => 0,
900 success => 0,
901 shop_id => $self->_unique_shop_id,
902 },
903 { -asc => 'job_started_epoch'});
904 0 my $pending = $self->_exe_query($stmt, @bind);
905 0 my %jobs;
906 0 ▶ while (my $row = $pending->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $pending->fetchrow_hashref) 0 0 0
907 0 ▶ $jobs{$row->{task}} ||= [];
Condition0%0/2
$jobs{$row->{"task"}} ||= []
l!l
00
MC/DC0%0/1
$jobs{$row->{"task"}} ||= []
$jobs{$row->{"task"}}
Truth table0%0/2
A
A= $jobs{$row->{"task"}}
Aresult
11
00
908 0 push @{$jobs{$row->{task}}}, $row;
909 }
910 0 my @out;
911 0 foreach my $task (qw/product_deletion upload shipping_confirmation order_ack/) {
912 0 ▶ if (my $list = delete $jobs{$task}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $list = delete $jobs{$task}) 0 0 0
913 0 ▶ if ($task eq 'order_ack') {
Branch: 2 branches
BranchTrueFalseTotal
if ($task eq 'order_ack') { } 0 0 0
elsif ($task eq 'shipping_confirmation') { } 0 0 0
914 0 for (1..2) {
915 0 ▶ push @out, pop @$list if @$list;
Branch: 1 branch
BranchTrueFalseTotal
if @$list 0 0 0
916 }
917 }
918 elsif ($task eq 'shipping_confirmation') {
919 0 ▶ while (@$list) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$list) 0 0 0
920 0 push @out, pop @$list;
921 }
922 }
923 else {
924 0 ▶ push @out, @$list if @$list;
Branch: 1 branch
BranchTrueFalseTotal
if @$list 0 0 0
925 }
926 }
927 }
928 0 return @out;
929 }
930  
931 0 ▶sub resume {
Subroutine resume: not called CC=4 SCAR=30.0
Pod documented
932 0 my ($self, @args) = @_;
933 0 foreach my $row ($self->get_pending_jobs(@args)) {
934 0 print "Working on $row->{amws_job_id}\n";
935 # check if the job dir exists
936 0 ▶ if (-d $self->_feed_job_dir($row->{amws_job_id})) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $self->_feed_job_dir($row->{'amws_job_id'})) { } 0 0 0
937 0 ▶ if (my $seconds_elapsed = $self->job_timed_out($row)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $seconds_elapsed = $self->job_timed_out($row)) 0 0 0
938 0 $self->_print_or_warn_error("Timeout reached for $row->{amws_job_id}, aborting: "
939 . Dumper($row));
940 $self->cancel_job($row->{task}, $row->{amws_job_id},
941 0 "Job timed out after $seconds_elapsed seconds");
942 0 next;
943 }
944 0 $self->process_feeds($row);
945 }
946 else {
947 0 warn "No directory " . $self->_feed_job_dir($row->{amws_job_id}) .
948 " found, removing job id $row->{amws_job_id}\n";
949 $self->cancel_job($row->{task}, $row->{amws_job_id},
950 0 "Job canceled due to missing feed directory");
951 }
952 }
953 }
954  
955 =head2 cancel_job($task, $job_id, $reason)
956  
957 Abort the job setting the aborted flag in C<amazon_mws_jobs> table.
958  
959 =cut
960  
961 0 ▶sub cancel_job {
Subroutine cancel_job: not called CC=4 SCAR=30.0
Pod documented
962 0 my ($self, $task, $job_id, $reason) = @_;
963 0 $self->_exe_query($self->sqla->update('amazon_mws_jobs',
964 {
965 aborted => 1,
966 status => $reason,
967 },
968 {
969 amws_job_id => $job_id,
970 shop_id => $self->_unique_shop_id,
971 }));
972  
973 # and revert the products' status
974 0 my $status;
975 0 ▶ if ($task eq 'product_deletion') {
Branch: 2 branches
BranchTrueFalseTotal
if ($task eq 'product_deletion') { } 0 0 0
elsif ($task eq 'upload') { } 0 0 0
976 # let's pretend we were deleting good products
977 0 $status = 'ok';
978 }
979 elsif ($task eq 'upload') {
980 0 $status = 'redo';
981 }
982 0 ▶ if ($status) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status) 0 0 0
983 0 print "Updating product to $status for products with job id $job_id\n";
984 0 $self->_exe_query($self->sqla->update('amazon_mws_products',
985 { status => $status },
986 {
987 amws_job_id => $job_id,
988 shop_id => $self->_unique_shop_id,
989 }));
990 }
991 }
992  
993  
994  
995 =head2 process_feeds(\%job_row)
996  
997 Given the hashref with the db row of the job, check at which point it
998 is and resume.
999  
1000 =cut
1001  
1002 0 ▶sub process_feeds {
Subroutine process_feeds: not called CC=10 SCAR=47.0
Pod documented
1003 0 my ($self, $row) = @_;
1004 # print Dumper($row);
1005 # upload the feeds one by one and stop if something is blocking
1006 0 my $job_id = $row->{amws_job_id};
1007 0 print "Processing job $job_id\n";
1008  
1009 # query the feeds table for this job
1010 0 my ($stmt, @bind) = $self->sqla->select(amazon_mws_feeds => '*',
1011 {
1012 amws_job_id => $job_id,
1013 aborted => 0,
1014 success => 0,
1015 shop_id => $self->_unique_shop_id,
1016 },
1017 ['amws_feed_pk']);
1018  
1019 0 my $sth = $self->_exe_query($stmt, @bind);
1020 0 my $unfinished;
1021 0 ▶ while (my $feed = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $feed = $sth->fetchrow_hashref) 0 0 0
1022 0 ▶ last unless $self->upload_feed($feed);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->upload_feed($feed) 0 0 0
1023 }
1024 0 $sth->finish;
1025  
1026 0 ($stmt, @bind) = $self->sqla->select(amazon_mws_feeds => '*',
1027 {
1028 shop_id => $self->_unique_shop_id,
1029 amws_job_id => $job_id,
1030 });
1031  
1032 0 $sth = $self->_exe_query($stmt, @bind);
1033  
1034 0 my ($total, $success, $aborted) = (0, 0, 0);
1035  
1036 # query again and check if we have aborted jobs;
1037 0 ▶ while (my $feed = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $feed = $sth->fetchrow_hashref) 0 0 0
1038 0 $total++;
1039 0 ▶ $success++ if $feed->{success};
Branch: 1 branch
BranchTrueFalseTotal
if $feed->{"success"} 0 0 0
1040 0 ▶ $aborted++ if $feed->{aborted};
Branch: 1 branch
BranchTrueFalseTotal
if $feed->{"aborted"} 0 0 0
1041 }
1042  
1043 # a job was aborted
1044 0 my $update;
1045 0 ▶ if ($aborted) {
Branch: 2 branches
BranchTrueFalseTotal
if ($aborted) { } 0 0 0
elsif ($success == $total) { } 0 0 0
1046 0 $update = {
1047 aborted => 1,
1048 status => 'Feed error',
1049 };
1050 0 $self->_print_or_warn_error("Job $job_id aborted!\n");
1051 }
1052 elsif ($success == $total) {
1053 0 $update = { success => 1 };
1054 0 print "Job successful!\n";
1055 # if we're here, all the products are fine, so mark them as
1056 # such if it's an upload job
1057 0 ▶ if ($row->{task} eq 'upload') {
Branch: 1 branch
BranchTrueFalseTotal
if ($row->{"task"} eq "upload") 0 0 0
1058 0 $self->_exe_query($self->sqla->update('amazon_mws_products',
1059 { status => 'ok',
1060 listed_date => DateTime->now,
1061 listed => 1,
1062 },
1063 {
1064 amws_job_id => $job_id,
1065 shop_id => $self->_unique_shop_id,
1066 }));
1067 }
1068 }
1069 else {
1070 0 print "Job still to be processed\n";
1071 }
1072 0 ▶ if ($update) {
Branch: 1 branch
BranchTrueFalseTotal
if ($update) 0 0 0
1073 0 $self->_exe_query($self->sqla->update(amazon_mws_jobs => $update,
1074 {
1075 amws_job_id => $job_id,
1076 shop_id => $self->_unique_shop_id,
1077 }));
1078 }
1079 }
1080  
1081 =head2 upload_feed($type, $feed_id);
1082  
1083 Routine to upload the feed. Return true if it's complete, false
1084 otherwise.
1085  
1086 =cut
1087  
1088 0 ▶sub upload_feed {
Subroutine upload_feed: not called CC=20 SCAR=60.4
Pod documented
1089 0 my ($self, $record) = @_;
1090 0 my $job_id = $record->{amws_job_id};
1091 0 my $type = $record->{feed_name};
1092 0 my $feed_id = $record->{feed_id};
1093 0 print "Checking $type feed for $job_id\n";
1094 # http://docs.developer.amazonservices.com/en_US/feeds/Feeds_FeedType.html
1095  
1096  
1097 0 my %names = (
1098 product => '_POST_PRODUCT_DATA_',
1099 inventory => '_POST_INVENTORY_AVAILABILITY_DATA_',
1100 price => '_POST_PRODUCT_PRICING_DATA_',
1101 image => '_POST_PRODUCT_IMAGE_DATA_',
1102 variants => '_POST_PRODUCT_RELATIONSHIP_DATA_',
1103 order_ack => '_POST_ORDER_ACKNOWLEDGEMENT_DATA_',
1104 shipping_confirmation => '_POST_ORDER_FULFILLMENT_DATA_',
1105 );
1106  
1107 0 ▶ die "Unrecognized type $type" unless $names{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $names{$type} 0 0 0
1108  
1109 # no feed id, it's a new batch
1110 0 ▶ if (!$feed_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($feed_id) 0 0 0
1111 0 print "No feed id found, doing a request for $job_id $type\n";
1112 0 my $feed_content = $self->_slurp_file($record->{feed_file});
1113 0 my $res;
1114 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1115 $res = $self->client
1116 ->SubmitFeed(content_type => 'text/xml; charset=utf-8',
1117 0 FeedType => $names{$type},
1118 FeedContent => $feed_content,
1119 MarketplaceIdList => [$self->marketplace_id],
1120 );
1121 }
1122 0 ▶ catch {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1123 0 warn "Failure to submit $type feed: \n";
1124 0 ▶ if (ref($_)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_) { } 0 0 0
1125 0 ▶ if ($_->can('xml')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->can('xml')) { } 0 0 0
1126 0 warn $_->xml;
1127 }
1128 else {
1129 0 warn Dumper($_);
1130 }
1131 }
1132 else {
1133 0 warn $_;
1134 }
1135 0 };
1136 # do not register the failure on die, because in this case (no
1137 # response) there could be throttling, or network failure
1138 0 ▶ die unless $res;
Branch: 1 branch
BranchTrueFalseTotal
unless $res 0 0 0
1139  
1140 # update the feed_id row storing it and updating.
1141 0 ▶ if ($feed_id = $record->{feed_id} = $res->{FeedSubmissionId}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($feed_id = $record->{'feed_id'} = $res->{'FeedSubmissionId'}) { } 0 0 0
1142 $self->_exe_query($self->sqla
1143 ->update(amazon_mws_feeds => $record,
1144 {
1145 amws_feed_pk => $record->{amws_feed_pk},
1146 0 shop_id => $self->_unique_shop_id,
1147 }));
1148 }
1149 else {
1150 # something is really wrong here, we have to die
1151 0 die "Couldn't get a submission id, response is " . Dumper($res);
1152 }
1153 }
1154 0 print "Feed is $feed_id\n";
1155  
1156 0 ▶ if (!$record->{processing_complete}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($record->{"processing_complete"}) 0 0 0
1157 0 ▶ if ($self->_check_processing_complete($feed_id, $type)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_check_processing_complete($feed_id, $type)) { } 0 0 0
1158 # update the record and set the flag to true
1159 0 $self->_exe_query($self->sqla
1160 ->update('amazon_mws_feeds',
1161 { processing_complete => 1 },
1162 {
1163 feed_id => $feed_id,
1164 shop_id => $self->_unique_shop_id,
1165 }));
1166 }
1167 else {
1168 0 print "Still processing\n";
1169 0 return;
1170 }
1171 }
1172  
1173 # check if we didn't already processed it
1174 0 ▶ if (!$record->{aborted} || !$record->{success}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($record->{"aborted"} and $record->{"success"}) 0 0 0
Condition0%0/3
$record->{"aborted"} and $record->{"success"}
!ll&&!rl&&r
000
MC/DC0%0/2
$record->{"aborted"} and $record->{"success"}
$record->{"aborted"} $record->{"success"}
Truth table0%0/3
A and B
A= $record->{"aborted"}B= $record->{"success"}
ABresult
0X0
100
111
1175 # we need a class to parse the result.
1176 0 my $result = $self->submission_result($feed_id);
1177 0 ▶ if ($result->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->is_success) { } 0 0 0
1178 0 $self->_exe_query($self->sqla
1179 ->update('amazon_mws_feeds',
1180 { success => 1 },
1181 {
1182 feed_id => $feed_id,
1183 shop_id => $self->_unique_shop_id,
1184 }));
1185 # if we have a success, print the warnings on the stderr.
1186 # if we have a failure, the warnings will just confuse us.
1187  
1188 0 ▶ if ($type eq 'order_ack') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'order_ack') { } 0 0 0
elsif ($type eq 'shipping_confirmation') { } 0 0 0
1189 # flip the confirmation bit
1190 0 $self->_exe_query($self->sqla->update(amazon_mws_orders => { confirmed => 1 },
1191 { amws_job_id => $job_id,
1192 shop_id => $self->_unique_shop_id }));
1193 }
1194 elsif ($type eq 'shipping_confirmation') {
1195 0 $self->_exe_query($self->sqla->update(amazon_mws_orders => { shipping_confirmation_ok => 1 },
1196 { shipping_confirmation_job_id => $job_id,
1197 shop_id => $self->_unique_shop_id }));
1198 }
1199 0 ▶ if (my $warn = $result->warnings) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $warn = $result->warnings) 0 0 0
1200 0 ▶ if (my $warns = $result->skus_warnings) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $warns = $result->skus_warnings) { } 0 0 0
1201 0 foreach my $w (@$warns) {
1202 $self->_error_logger(warning => $w->{code},
1203 0 "$w->{sku}: $w->{error}");
1204 # and register it in the db
1205 0 ▶ if ($w->{sku} && $w->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($w->{"sku"} and $w->{"error"}) 0 0 0
Condition0%0/3
$w->{"sku"} and $w->{"error"}
!ll&&!rl&&r
000
MC/DC0%0/2
$w->{"sku"} and $w->{"error"}
$w->{"sku"} $w->{"error"}
Truth table0%0/3
A and B
A= $w->{"sku"}B= $w->{"error"}
ABresult
0X0
100
111
1206 $self->_exe_query($self->sqla->update('amazon_mws_products',
1207 { warnings => "$job_id $w->{code} $w->{error}" },
1208 {
1209 sku => $w->{sku},
1210 0 shop_id => $self->_unique_shop_id,
1211 }));
1212 }
1213 }
1214 }
1215 else {
1216 0 warn "$warn\n";
1217 }
1218 }
1219 0 return 1;
1220 }
1221 else {
1222 0 foreach my $err ($result->report_errors) {
1223 $self->_error_logger($err->{type},
1224 $err->{code},
1225 0 $err->{message});
1226 }
1227 0 $self->_exe_query($self->sqla
1228 ->update('amazon_mws_feeds',
1229 {
1230 aborted => 1,
1231 errors => $result->errors,
1232 },
1233 {
1234 feed_id => $feed_id,
1235 shop_id => $self->_unique_shop_id,
1236 }));
1237 0 $self->register_errors($job_id, $result);
1238
1239 0 ▶ if ($type eq 'order_ack') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'order_ack') { } 0 0 0
elsif ($type eq 'shipping_confirmation') { } 0 0 0
1240 0 $self->register_order_ack_errors($job_id, $result);
1241 }
1242 elsif ($type eq 'shipping_confirmation') {
1243 0 $self->register_ship_order_errors($job_id, $result);
1244 }
1245
1246 # and we stop this job, has errors
1247 0 return 0;
1248 }
1249 }
1250 0 return $record->{success};
1251 }
1252  
1253 0 ▶sub _exe_query {
Subroutine _exe_query: not called CC=2 SCAR=17.9
1254 0 my ($self, $stmt, @bind) = @_;
1255 0 my $sth = $self->dbh->prepare($stmt);
1256 0 print $stmt, Dumper(\@bind) if DEBUG;
1257 0 eval {
1258 0 $sth->execute(@bind);
1259 };
1260 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1261 0 die "Failed to execute $stmt with params" . Dumper(\@bind);
1262 }
1263 0 return $sth;
1264 }
1265  
1266 0 ▶sub _check_processing_complete {
Subroutine _check_processing_complete: not called CC=8 SCAR=42.8
1267 0 my ($self, $feed_id, $type) = @_;
1268 0 my $res;
1269 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1270 0 $res = $self->client->GetFeedSubmissionList;
1271 0 ▶ } catch {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1272 0 my $exception = $_;
1273 0 ▶ if (ref($exception) && $exception->can('xml')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $exception and $exception->can('xml')) { } 0 0 0
Condition0%0/3
ref $exception and $exception->can("xml")
!ll&&!rl&&r
000
MC/DC0%0/2
ref $exception and $exception->can("xml")
ref $exception $exception->can("xml")
Truth table0%0/3
A and B
A= ref $exceptionB= $exception->can("xml")
ABresult
0X0
100
111
1274 0 warn "checking processing complete error for $type $feed_id: " . $exception->xml;
1275 }
1276 else {
1277 0 warn "checking processing complete for $type $feed_id: " . Dumper($exception);
1278 }
1279 0 };
1280 0 ▶ die unless $res;
Branch: 1 branch
BranchTrueFalseTotal
unless $res 0 0 0
1281 0 print "Checking if the processing is complete for $type $feed_id\n"; # . Dumper($res);
1282 0 my $found;
1283 0 ▶ if (my $list = $res->{FeedSubmissionInfo}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $list = $res->{'FeedSubmissionInfo'}) { } 0 0 0
1284 0 foreach my $feed (@$list) {
1285 0 ▶ if ($feed->{FeedSubmissionId} eq $feed_id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($feed->{"FeedSubmissionId"} eq $feed_id) 0 0 0
1286 0 $found = $feed;
1287 0 last;
1288 }
1289 }
1290  
1291 # check the result
1292 0 ▶ if ($found && $found->{FeedProcessingStatus} eq '_DONE_') {
Branch: 2 branches
BranchTrueFalseTotal
if ($found and $found->{'FeedProcessingStatus'} eq '_DONE_') { } 0 0 0
elsif ($found) { } 0 0 0
Condition0%0/3
$found and $found->{"FeedProcessingStatus"} eq "_DONE_"
!ll&&!rl&&r
000
MC/DC0%0/2
$found and $found->{"FeedProcessingStatus"} eq "_DONE_"
$found $found->{"FeedProcessingStatus"} eq "_DONE_"
Truth table0%0/3
A and B
A= $foundB= $found->{"FeedProcessingStatus"} eq "_DONE_"
ABresult
0X0
100
111
1293 0 return 1;
1294 }
1295 elsif ($found) {
1296 0 print "Feed $type $feed_id still $found->{FeedProcessingStatus}\n";
1297 0 return;
1298 }
1299 else {
1300 # there is a remote possibility that in it in another
1301 # page, but it should be very unlikely, as we block the
1302 # process when the first one is not complete
1303 0 print "$feed_id not found in submission list\n";
1304 0 return;
1305 }
1306 }
1307 else {
1308 0 warn "No FeedSubmissionInfo found for $type $feed_id:" . Dumper($res);
1309 0 return;
1310 }
1311 }
1312  
1313 =head2 submission_result($feed_id)
1314  
1315 Return a L<Amazon::MWS::XML::Response::FeedSubmissionResult> object
1316 for the given feed ID.
1317  
1318 =cut
1319  
1320 0 ▶sub submission_result {
Subroutine submission_result: not called CC=2 SCAR=17.9
Pod documented
1321 0 my ($self, $feed_id) = @_;
1322 0 my $xml;
1323 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1324 0 $xml = $self->client
1325 ->GetFeedSubmissionResult(FeedSubmissionId => $feed_id);
1326 0 ▶ } catch {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1327 0 my $exception = $_;
1328 0 ▶ if (ref($exception) && $exception->can('xml')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $exception and $exception->can('xml')) { } 0 0 0
Condition0%0/3
ref $exception and $exception->can("xml")
!ll&&!rl&&r
000
MC/DC0%0/2
ref $exception and $exception->can("xml")
ref $exception $exception->can("xml")
Truth table0%0/3
A and B
A= ref $exceptionB= $exception->can("xml")
ABresult
0X0
100
111
1329 0 warn "submission result error: " . $exception->xml;
1330 }
1331 else {
1332 0 warn "submission result error: " . Dumper($exception);
1333 }
1334 0 };
1335 0 ▶ die unless $xml;
Branch: 1 branch
BranchTrueFalseTotal
unless $xml 0 0 0
1336 0 return Amazon::MWS::XML::Response::FeedSubmissionResult
1337 ->new(
1338 xml => $xml,
1339 xml_reader => $self->xml_reader,
1340 );
1341 }
1342  
1343 =head2 get_orders($from_date)
1344  
1345 This is a self-contained method and doesn't require a product list.
1346 The from_date must be a L<DateTime> object. If not provided, it will
1347 the last week.
1348  
1349 Returns a list of Amazon::MWS::XML::Order objects.
1350  
1351 Beware that it's possible you get some items with 0 quantity, i.e.
1352 single items cancelled. The application code needs to be prepared to
1353 deal with such phantom items. You can check each order looping over
1354 C<$order->items> checking for C<$item->quantity>.
1355  
1356 =cut
1357  
1358 0 ▶sub get_orders {
Subroutine get_orders: not called CC=5 SCAR=34.0
Pod documented
1359 0 my ($self, $from_date) = @_;
1360 0 ▶ unless ($from_date) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($from_date) 0 0 0
1361 0 $from_date = DateTime->now;
1362 0 $from_date->subtract(days => $self->order_days_range);
1363 }
1364 0 my @order_structs;
1365 my $res;
1366 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1367 0 $res = $self->client->ListOrders(
1368 MarketplaceId => [$self->marketplace_id],
1369 CreatedAfter => $from_date,
1370 );
1371 0 push @order_structs, @{ $res->{Orders}->{Order} };
1372 }
1373 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1374 0 die Dumper($_);
1375 0 };
1376 0 ▶ while (my $next_token = $res->{NextToken}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $next_token = $res->{"NextToken"}) 0 0 0
1377 # print "Found next token!\n";
1378 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1379 0 $res = $self->client->ListOrdersByNextToken(NextToken => $next_token);
1380 0 push @order_structs, @{ $res->{Orders}->{Order} };
1381 }
1382 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1383 0 die Dumper($_);
1384 0 };
1385 }
1386 0 my @orders;
1387 0 foreach my $order (@order_structs) {
1388 0 my $amws_id = $order->{AmazonOrderId};
1389 0 ▶ die "Missing amazon AmazonOrderId?!" unless $amws_id;
Branch: 1 branch
BranchTrueFalseTotal
unless $amws_id 0 0 0
1390  
1391 0 ▶ my $get_orderline = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1392 # begin of the closure
1393 0 my $orderline;
1394 my @items;
1395 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1396 0 $orderline = $self->client->ListOrderItems(AmazonOrderId => $amws_id);
1397 0 push @items, @{ $orderline->{OrderItems}->{OrderItem} };
1398 }
1399 0 ▶ catch {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1400 0 my $err = $_;
1401 0 ▶ if (blessed($err) && $err->isa('Amazon::MWS::Exception::Throttled')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($err) and $err->isa('Amazon::MWS::Exception::Throttled')) { } 0 0 0
Condition0%0/3
builtin::blessed($err) and $err->isa("Amazon::MWS::Exception::Throttled")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($err) and $err->isa("Amazon::MWS::Exception::Throttled")
builtin::blessed($err) $err->isa("Amazon::MWS::Exception::Throttled")
Truth table0%0/3
A and B
A= builtin::blessed($err)B= $err->isa("Amazon::MWS::Exception::Throttled")
ABresult
0X0
100
111
1402 0 die "Request is throttled. Consider to adjust order_days_range as documented at https://metacpan.org/pod/Amazon::MWS::Uploader#ACCESSORS";
1403 }
1404 else {
1405 0 die Dumper($err);
1406 }
1407 0 };
1408 0 ▶ while (my $next = $orderline->{NextToken}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $next = $orderline->{"NextToken"}) 0 0 0
1409 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1410 0 $orderline =
1411 $self->client->ListOrderItemsByNextToken(NextToken => $next);
1412 0 push @items, @{ $orderline->{OrderItems}->{OrderItem} };
1413 }
1414 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1415 0 die Dumper($_);
1416 0 };
1417 }
1418 0 return \@items;
1419 # end of the closure
1420 0 };
1421  
1422 0 push @orders, Amazon::MWS::XML::Order->new(order => $order,
1423 retrieve_orderline_sub => $get_orderline);
1424 }
1425 0 return @orders;
1426 }
1427  
1428 =head2 order_already_registered($order)
1429  
1430 Check in the amazon_mws_orders table if we already registered this
1431 order.
1432  
1433 Return the row for this table (as an hashref) if present, nothing
1434 underwise.
1435  
1436 =cut
1437  
1438 0 ▶sub order_already_registered {
Subroutine order_already_registered: not called CC=3 SCAR=24.8
Pod documented
1439 0 my ($self, $order) = @_;
1440 0 ▶ die "Bad usage, missing order" unless $order;
Branch: 1 branch
BranchTrueFalseTotal
unless $order 0 0 0
1441 0 my $sth = $self->_exe_query($self->sqla->select(amazon_mws_orders => '*',
1442 {
1443 amazon_order_id => $order->amazon_order_number,
1444 shop_id => $self->_unique_shop_id,
1445 }));
1446 0 ▶ if (my $exists = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $exists = $sth->fetchrow_hashref) { } 0 0 0
1447 0 $sth->finish;
1448 0 return $exists;
1449 }
1450 else {
1451 0 return;
1452 }
1453 }
1454  
1455 =head2 acknowledge_successful_order(@orders)
1456  
1457 Accept a list of L<Amazon::MWS::XML::Order> objects, prepare a
1458 acknowledge feed with the C<Success> status, and insert the orders in
1459 the database.
1460  
1461 =cut
1462  
1463 0 ▶sub acknowledge_successful_order {
Subroutine acknowledge_successful_order: not called CC=6 SCAR=37.4
Pod documented
1464 0 my ($self, @orders) = @_;
1465 0 my @orders_to_register;
1466 0 foreach my $ord (@orders) {
1467 0 ▶ if (my $existing = $self->order_already_registered($ord)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $existing = $self->order_already_registered($ord)) { } 0 0 0
1468 0 ▶ if ($existing->{confirmed}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($existing->{'confirmed'}) { } 0 0 0
1469 0 print "Skipping already confirmed order $existing->{amazon_order_id} => $existing->{shop_order_id}\n";
1470 }
1471 else {
1472 # it's not complete, so print out diagnostics
1473 0 warn "Order $existing->{amazon_order_id} uncompletely registered with id $existing->{shop_order_id}, please indagate why (skipping)\n" . Dumper($existing);
1474 }
1475 }
1476 else {
1477 0 push @orders_to_register, $ord;
1478 }
1479 }
1480 0 ▶ return unless @orders_to_register;
Branch: 1 branch
BranchTrueFalseTotal
unless @orders_to_register 0 0 0
1481  
1482 0 my $feed_content = $self->acknowledge_feed(Success => @orders_to_register);
1483 # here we have only one feed to upload and check
1484 0 my $job_id = $self->prepare_feeds(order_ack => [{
1485 name => 'order_ack',
1486 content => $feed_content,
1487 }]);
1488 # store the pairing amazon order id / shop order id in our table
1489 0 foreach my $order (@orders_to_register) {
1490 0 my %order_pairs = (
1491 shop_id => $self->_unique_shop_id,
1492 amazon_order_id => $order->amazon_order_number,
1493 # this will die if we try to insert an undef order_number
1494 shop_order_id => $order->order_number,
1495 amws_job_id => $job_id,
1496 );
1497 0 $self->_exe_query($self->sqla->insert(amazon_mws_orders => \%order_pairs));
1498 }
1499 }
1500  
1501  
1502 =head2 acknowledge_feed($status, @orders)
1503  
1504 The first argument is usually C<Success>. The other arguments is a
1505 list of L<Amazon::MWS::XML::Order> objects.
1506  
1507 =cut
1508  
1509  
1510 0 ▶sub acknowledge_feed {
Subroutine acknowledge_feed: not called CC=4 SCAR=30.0
Pod documented
1511 0 my ($self, $status, @orders) = @_;
1512 0 ▶ die "Missing status" unless $status;
Branch: 1 branch
BranchTrueFalseTotal
unless $status 0 0 0
1513 0 ▶ die "Missing orders" unless @orders;
Branch: 1 branch
BranchTrueFalseTotal
unless @orders 0 0 0
1514  
1515 0 my $feeder = $self->generic_feeder;
1516  
1517 0 my $counter = 1;
1518 0 my @messages;
1519 0 foreach my $order (@orders) {
1520 0 my $data = $order->as_ack_order_hashref;
1521 0 $data->{StatusCode} = $status;
1522 0 push @messages, {
1523 MessageID => $counter++,
1524 OrderAcknowledgement => $data,
1525 };
1526 }
1527 0 return $feeder->create_feed(OrderAcknowledgement => \@messages);
1528 }
1529  
1530 =head2 delete_skus(@skus)
1531  
1532 Accept a list of skus. Prepare a C<product_deletion> feed and update
1533 the database.
1534  
1535 =cut
1536  
1537 0 ▶sub delete_skus {
Subroutine delete_skus: not called CC=8 SCAR=42.8
Pod documented
1538 0 my ($self, @skus) = @_;
1539 0 ▶ return unless @skus;
Branch: 1 branch
BranchTrueFalseTotal
unless @skus 0 0 0
1540 0 print "Trying to purge missing items " . join(" ", @skus) . "\n";
1541  
1542 # delete only products which are not in pending status
1543 0 my $check = $self
1544 ->_exe_query($self->sqla
1545 ->select('amazon_mws_products', [qw/sku status/],
1546 {
1547 sku => { -in => \@skus },
1548 shop_id => $self->_unique_shop_id,
1549 }));
1550 0 my %our_skus;
1551 0 ▶ while (my $p = $check->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $p = $check->fetchrow_hashref) 0 0 0
1552 0 $our_skus{$p->{sku}} = $p->{status};
1553 }
1554 0 my @checked;
1555 0 ▶ while (@skus) {
Branch: 1 branch
BranchTrueFalseTotal
if (@skus) 0 0 0
1556 0 my $sku = shift @skus;
1557 0 ▶ if (my $status = $our_skus{$sku}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $status = $our_skus{$sku}) { } 0 0 0
1558 0 ▶ if ($status eq 'pending' or
Branch: 1 branch
BranchTrueFalseTotal
if ($status eq "pending" or $status eq "deleted") 0 0 0
Condition0%0/3
$status eq "pending" or $status eq "deleted"
l!l&&r!l&&!r
000
MC/DC0%0/2
$status eq "pending" or $status eq "deleted"
$status eq "pending" $status eq "deleted"
Truth table0%0/3
A or B
A= $status eq "pending"B= $status eq "deleted"
ABresult
1X1
011
000
1559 $status eq 'deleted') {
1560 0 print "Skipping $sku deletion, in status $status\n";
1561 0 next;
1562 }
1563 }
1564 else {
1565 0 warn "$sku not found in amazon_mws_products, deleting anyway\n";
1566 }
1567 0 push @checked, $sku;
1568 }
1569 0 @skus = @checked;
1570  
1571 0 ▶ unless (@skus) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@skus) 0 0 0
1572 0 print "Not purging anything\n";
1573 0 return;
1574 }
1575 0 print "Actually purging items " . join(" ", @skus) . "\n";
1576  
1577 0 my $feed_content = $self->delete_skus_feed(@skus);
1578 0 my $job_id = $self->prepare_feeds(product_deletion => [{
1579 name => 'product',
1580 content => $feed_content,
1581 }] );
1582 # delete the skus locally
1583 0 $self->_exe_query($self->sqla->update('amazon_mws_products',
1584 {
1585 status => 'deleted',
1586 amws_job_id => $job_id,
1587 },
1588 {
1589 sku => { -in => \@skus },
1590 shop_id => $self->_unique_shop_id,
1591 }));
1592 }
1593  
1594 =head2 delete_skus_feed(@skus)
1595  
1596 Prepare a feed (via C<create_feed>) to delete the given skus.
1597  
1598 =cut
1599  
1600 0 ▶sub delete_skus_feed {
Subroutine delete_skus_feed: not called CC=3 SCAR=24.8
Pod documented
1601 0 my ($self, @skus) = @_;
1602 0 ▶ return unless @skus;
Branch: 1 branch
BranchTrueFalseTotal
unless @skus 0 0 0
1603 0 my $feeder = $self->generic_feeder;
1604 0 my $counter = 1;
1605 0 my @messages;
1606 0 foreach my $sku (@skus) {
1607 0 push @messages, {
1608 MessageID => $counter++,
1609 OperationType => 'Delete',
1610 Product => {
1611 SKU => $sku,
1612 }
1613 };
1614 }
1615 0 return $feeder->create_feed(Product => \@messages);
1616 }
1617  
1618 0 ▶sub register_order_ack_errors {
Subroutine register_order_ack_errors: not called CC=7 SCAR=40.3
Pod documented
1619 0 my ($self, $job_id, $result) = @_;
1620 0 my @errors = $result->report_errors;
1621 # we hope to have just one error, but in case...
1622 0 my %update;
1623 0 ▶ if (@errors > 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (@errors > 1) { } 0 0 0
elsif (@errors) { } 0 0 0
1624 0 my @errors_with_code = grep { $_->{code} } @errors;
1625 0 my $error_code = AMW_ORDER_WILDCARD_ERROR;
1626 0 ▶ if (@errors_with_code) {
Branch: 1 branch
BranchTrueFalseTotal
if (@errors_with_code) 0 0 0
1627 # pick just the first, the field is an integer
1628 0 $error_code = $errors_with_code[0]{code};
1629 }
1630 0 my $error_msgs = join('\n', map { $_->{type} . ' ' . $_->{message} . ' ' . $_->{code} } @errors);
1631 0 %update = (
1632 error_msg => $error_msgs,
1633 error_code => $error_code,
1634 );
1635 }
1636 elsif (@errors) {
1637 0 my $error = shift @errors;
1638 %update = (
1639 error_msg => $error->{type} . ' ' . $error->{message} . ' ' . $error->{code},
1640 error_code => $error->{code},
1641 0 );
1642 }
1643 else {
1644 0 %update = (
1645 error_msg => $result->errors,
1646 error_code => AMW_ORDER_WILDCARD_ERROR,
1647 );
1648 }
1649 0 ▶ if (%update) {
Branch: 1 branch
BranchTrueFalseTotal
if (%update) { } 0 0 0
1650 0 $self->_exe_query($self->sqla->update('amazon_mws_orders',
1651 \%update,
1652 { amws_job_id => $job_id,
1653 shop_id => $self->_unique_shop_id }));
1654 }
1655 else {
1656 0 warn "register_order_ack_errors couldn't parse " . Dumper($result);
1657 }
1658 # then get the amazon order number and recheck
1659 0 my $sth = $self->_exe_query($self->sqla->select('amazon_mws_orders',
1660 [qw/amazon_order_id
1661 shop_order_id
1662 /],
1663 {
1664 amws_job_id => $job_id,
1665 shop_id => $self->_unique_shop_id,
1666 }));
1667 0 my ($amw_order_number, $shop_order_id) = $sth->fetchrow_array;
1668 0 ▶ if ($sth->fetchrow_array) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->fetchrow_array) 0 0 0
1669 0 warn "Multiple jobs found for $job_id in amazon_mws_orders!";
1670 }
1671 0 $sth->finish;
1672 0 ▶ if (my $status = $self->update_amw_order_status($amw_order_number)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $status = $self->update_amw_order_status($amw_order_number)) 0 0 0
1673 0 warn "$amw_order_number ($shop_order_id) has now status $status!\n";
1674 }
1675 }
1676  
1677 0 ▶sub register_ship_order_errors {
Subroutine register_ship_order_errors: not called CC=3 SCAR=24.8
Pod documented
1678 0 my ($self, $job_id, $result) = @_;
1679 # here we get the amazon ids,
1680 0 my @orders = $self->orders_in_shipping_job($job_id);
1681 0 my $errors = $result->orders_errors;
1682 # filter
1683 0 my @errors_with_order = grep { $_->{order_id} } @$errors;
1684 0 my %errs = map { $_->{order_id} => {job_id => $job_id, code => $_->{code}, error => $_->{error}} } @errors_with_order;
1685  
1686 0 foreach my $ord (@orders) {
1687 0 ▶ if (my $fault = $errs{$ord}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fault = $errs{$ord}) { } 0 0 0
1688 0 $self->_exe_query($self->sqla->update('amazon_mws_orders',
1689 {
1690 shipping_confirmation_error => "$fault->{code} $fault->{error}",
1691 },
1692 {
1693 amazon_order_id => $ord,
1694 shipping_confirmation_job_id => $job_id,
1695 shop_id => $self->_unique_shop_id,
1696 }));
1697 }
1698 else {
1699 # this looks good
1700 0 $self->_exe_query($self->sqla->update('amazon_mws_orders',
1701 {
1702 shipping_confirmation_ok => 1,
1703 },
1704 {
1705 amazon_order_id => $ord,
1706 shipping_confirmation_job_id => $job_id,
1707 shop_id => $self->_unique_shop_id
1708 }));
1709 }
1710 }
1711 }
1712  
1713  
1714 =head2 register_errors($job_id, $result)
1715  
1716 The first argument is the job ID. The second is a
1717 L<Amazon::MWS::XML::Response::FeedSubmissionResult> object.
1718  
1719 This method will update the status of the products (either C<failed>
1720 or C<redo>) in C<amazon_mws_products>.
1721  
1722 =head2 register_order_ack_errors($job_id, $result);
1723  
1724 Same arguments as above, but for order acknowledgements.
1725  
1726 =head2 register_ship_order_errors($job_id, $result);
1727  
1728 Same arguments as above, but for shipping notifications.
1729  
1730 =cut
1731  
1732 0 ▶sub register_errors {
Subroutine register_errors: not called CC=3 SCAR=24.8
Pod documented
1733 0 my ($self, $job_id, $result) = @_;
1734 # first, get the list of all the skus which were scheduled for this job
1735 # we don't have a products hashref anymore.
1736 # probably we could parse back the produced xml, but looks like an overkill.
1737 # just mark them as redo and wait for the next cron call.
1738 0 my @products = $self->skus_in_job($job_id);
1739 0 my $errors = $result->skus_errors;
1740 0 my @errors_with_sku = grep { $_->{sku} } @$errors;
1741 # turn it into an hash
1742 0 my %errs = map { $_->{sku} => {job_id => $job_id, code => $_->{code}, error => $_->{error}} } @errors_with_sku;
1743  
1744 0 foreach my $sku (@products) {
1745 0 ▶ if ($errs{$sku}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($errs{$sku}) { } 0 0 0
1746 $self->_exe_query($self->sqla->update('amazon_mws_products',
1747 {
1748 status => 'failed',
1749 error_code => $errs{$sku}->{code},
1750 0 error_msg => "$errs{$sku}->{job_id} $errs{$sku}->{code} $errs{$sku}->{error}",
1751 },
1752 {
1753 sku => $sku,
1754 shop_id => $self->_unique_shop_id,
1755 }));
1756 }
1757 else {
1758 # this is good, mark it to be redone
1759 0 $self->_exe_query($self->sqla->update('amazon_mws_products',
1760 {
1761 status => 'redo',
1762 },
1763 {
1764 sku => $sku,
1765 shop_id => $self->_unique_shop_id,
1766 }));
1767 0 print "Scheduling $sku for redoing\n";
1768 }
1769 }
1770 }
1771  
1772 =head2 skus_in_job($job_id)
1773  
1774 Check the amazon_mws_product for the SKU which were uploaded by the
1775 given job ID.
1776  
1777 =cut
1778  
1779 0 ▶sub skus_in_job {
Subroutine skus_in_job: not called CC=2 SCAR=17.9
Pod documented
1780 0 my ($self, $job_id) = @_;
1781 0 my $sth = $self->_exe_query($self->sqla->select('amazon_mws_products',
1782 [qw/sku/],
1783 {
1784 amws_job_id => $job_id,
1785 shop_id => $self->_unique_shop_id,
1786 }));
1787 0 my @skus;
1788 0 ▶ while (my $row = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 0 0 0
1789 0 push @skus, $row->{sku};
1790 }
1791 0 return @skus;
1792 }
1793  
1794 =head2 get_asin_for_eans(@eans)
1795  
1796 Accept a list of EANs and return an hashref where the keys are the
1797 eans passed as arguments, and the values are the ASIN for the current
1798 marketplace. Max EANs: 5.x
1799  
1800 http://docs.developer.amazonservices.com/en_US/products/Products_GetMatchingProductForId.html
1801  
1802 =head2 get_asin_for_skus(@skus)
1803  
1804 Same as above (with the same limit of 5 items), but for SKUs.
1805  
1806 =head2 get_asin_for_sku($sku)
1807  
1808 Same as above, but for a single sku. Return the ASIN or undef if not
1809 found.
1810  
1811 =head2 get_asin_for_ean($ean)
1812  
1813 Same as above, but for a single ean. Return the ASIN or undef if not
1814 found.
1815  
1816 =cut
1817  
1818 0 ▶sub get_asin_for_skus {
Subroutine get_asin_for_skus: not called CC=1 SCAR=6.9
Pod documented
1819 0 my ($self, @skus) = @_;
1820 0 return $self->_get_asin_for_type(SellerSKU => @skus);
1821 }
1822  
1823 0 ▶sub get_asin_for_eans {
Subroutine get_asin_for_eans: not called CC=1 SCAR=6.9
Pod documented
1824 0 my ($self, @eans) = @_;
1825 0 return $self->_get_asin_for_type(EAN => @eans);
1826 }
1827  
1828 0 ▶sub _get_asin_for_type {
Subroutine _get_asin_for_type: not called CC=5 SCAR=34.0
1829 0 my ($self, $type, @list) = @_;
1830 0 ▶ die "Max 5 products to get the asin for $type!" if @list > 5;
Branch: 1 branch
BranchTrueFalseTotal
if @list > 5 0 0 0
1831 0 my $client = $self->client;
1832 0 my $res;
1833 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1834 0 $res = $client->GetMatchingProductForId(IdType => $type,
1835 IdList => \@list,
1836 MarketplaceId => $self->marketplace_id);
1837 }
1838 0 ▶ catch { die Dumper($_) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
1839 0 my %ids;
1840 0 ▶ if ($res && @$res) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res and @$res) 0 0 0
Condition0%0/3
$res and @$res
!ll&&!rl&&r
000
MC/DC0%0/2
$res and @$res
$res @$res
Truth table0%0/3
A and B
A= $resB= @$res
ABresult
0X0
100
111
1841 0 foreach my $product (@$res) {
1842 0 $ids{$product->{Id}} = $product->{Products}->{Product}->{Identifiers}->{MarketplaceASIN}->{ASIN};
1843 }
1844 }
1845 0 return \%ids;
1846 }
1847  
1848 0 ▶sub get_asin_for_ean {
Subroutine get_asin_for_ean: not called CC=3 SCAR=24.8
Pod documented
1849 0 my ($self, $ean) = @_;
1850 0 my $res = $self->get_asin_for_eans($ean);
1851 0 ▶ if ($res && $res->{$ean}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res and $res->{$ean}) { } 0 0 0
Condition0%0/3
$res and $res->{$ean}
!ll&&!rl&&r
000
MC/DC0%0/2
$res and $res->{$ean}
$res $res->{$ean}
Truth table0%0/3
A and B
A= $resB= $res->{$ean}
ABresult
0X0
100
111
1852 0 return $res->{$ean};
1853 }
1854 else {
1855 0 return;
1856 }
1857 }
1858  
1859 0 ▶sub get_asin_for_sku {
Subroutine get_asin_for_sku: not called CC=3 SCAR=24.8
Pod documented
1860 0 my ($self, $sku) = @_;
1861 0 my $res = $self->get_asin_for_skus($sku);
1862 0 ▶ if ($res && $res->{$sku}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res and $res->{$sku}) { } 0 0 0
Condition0%0/3
$res and $res->{$sku}
!ll&&!rl&&r
000
MC/DC0%0/2
$res and $res->{$sku}
$res $res->{$sku}
Truth table0%0/3
A and B
A= $resB= $res->{$sku}
ABresult
0X0
100
111
1863 0 return $res->{$sku};
1864 }
1865 else {
1866 0 return;
1867 }
1868 }
1869  
1870  
1871 =head2 get_product_category_data($ean)
1872  
1873 Return the deep data structures returned by
1874 C<GetProductCategoriesForASIN>.
1875  
1876 =head2 get_product_categories($ean)
1877  
1878 Return a list of category codes (the ones passed to
1879 RecommendedBrowseNode) which exists on amazon.
1880  
1881 =cut
1882  
1883 0 ▶sub get_product_category_data {
Subroutine get_product_category_data: not called CC=3 SCAR=24.8
Pod documented
1884 0 my ($self, $ean) = @_;
1885 0 ▶ return unless $ean;
Branch: 1 branch
BranchTrueFalseTotal
unless $ean 0 0 0
1886 0 my $asin = $self->get_asin_for_ean($ean);
1887 0 ▶ unless ($asin) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($asin) 0 0 0
1888 0 return;
1889 }
1890 0 my $res = $self->client
1891 ->GetProductCategoriesForASIN(ASIN => $asin,
1892 MarketplaceId => $self->marketplace_id);
1893 0 return $res;
1894 }
1895  
1896 =head2 get_product_category_names($ean)
1897  
1898 Return a list of arrayrefs with the category paths. Beware that we
1899 strip the first two parents, which euristically appear meaningless
1900 (Category/Category).
1901  
1902 If this is not a case, please report this as a bug and we'll find a
1903 solution.
1904  
1905 You can call C<get_product_category_data> to inspect the raw response
1906 yourself.
1907  
1908 =cut
1909  
1910 0 ▶sub get_product_category_names {
Subroutine get_product_category_names: not called CC=4 SCAR=30.0
Pod documented
1911 0 my ($self, $ean) = @_;
1912 0 my $res = $self->get_product_category_data($ean);
1913 0 ▶ if ($res) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res) { } 0 0 0
1914 0 my @category_names;
1915 0 foreach my $cat (@$res) {
1916 0 my @list = $self->_parse_amz_cat($cat);
1917 0 ▶ if (@list) {
Branch: 1 branch
BranchTrueFalseTotal
if (@list) 0 0 0
1918 0 push @category_names, \@list;
1919 }
1920  
1921 }
1922 0 return @category_names;
1923 }
1924 else {
1925 0 warn "ASIN exists but no categories found. Bug?\n";
1926 0 return;
1927 }
1928 }
1929  
1930 0 ▶sub _parse_amz_cat {
Subroutine _parse_amz_cat: not called CC=4 SCAR=30.0
1931 0 my ($self, $cat) = @_;
1932 0 my @path;
1933 0 ▶ while ($cat) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cat) 0 0 0
1934 0 ▶ if ($cat->{ProductCategoryName}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cat->{"ProductCategoryName"}) 0 0 0
1935 0 push @path, $cat->{ProductCategoryName};
1936 }
1937 0 $cat = $cat->{Parent};
1938 }
1939 0 @path = reverse @path;
1940  
1941 # the first two parents are Category/Category.
1942 0 ▶ if (@path >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@path >= 2) 0 0 0
1943 0 splice(@path, 0, 2);
1944 }
1945 0 return @path;
1946 }
1947  
1948  
1949 0 ▶sub get_product_categories {
Subroutine get_product_categories: not called CC=2 SCAR=17.9
Pod documented
1950 0 my ($self, $ean) = @_;
1951 0 my $res = $self->get_product_category_data($ean);
1952 0 ▶ if ($res) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res) { } 0 0 0
1953 0 my @ids = map { $_->{ProductCategoryId} } @$res;
1954 0 return @ids;
1955 }
1956 else {
1957 0 warn "ASIN exists but no categories found. Bug?\n";
1958 0 return;
1959 }
1960 }
1961  
1962  
1963 # http://docs.developer.amazonservices.com/en_US/products/Products_GetLowestOfferListingsForSKU.html
1964  
1965 =head2 get_lowest_price_for_asin($asin, $condition)
1966  
1967 Return the lowest price for asin, excluding ourselves. The second
1968 argument, condition, is optional and defaults to "New".
1969  
1970 If you need the full details, you have to call
1971 $self->client->GetLowestOfferListingsForASIN yourself and make sense
1972 of the output. This method is mostly a wrapper meant to simplify the
1973 routine.
1974  
1975 If we can't get any info, just return undef.
1976  
1977 Return undef if no prices are found.
1978  
1979 =head2 get_lowest_price_for_ean($ean, $condition)
1980  
1981 Same as above, but use the EAN instead
1982  
1983 =cut
1984  
1985 0 ▶sub get_lowest_price_for_ean {
Subroutine get_lowest_price_for_ean: not called CC=3 SCAR=24.8
Pod documented
1986 0 my ($self, $ean, $condition) = @_;
1987 0 ▶ return unless $ean;
Branch: 1 branch
BranchTrueFalseTotal
unless $ean 0 0 0
1988 0 my $asin = $self->get_asin_for_ean($ean);
1989 0 ▶ return unless $asin;
Branch: 1 branch
BranchTrueFalseTotal
unless $asin 0 0 0
1990 0 return $self->get_lowest_price_for_asin($asin, $condition);
1991 }
1992  
1993 0 ▶sub get_lowest_price_for_asin {
Subroutine get_lowest_price_for_asin: not called CC=7 SCAR=40.3
Pod documented
1994 0 my ($self, $asin, $condition) = @_;
1995 0 ▶ die "Wrong usage, missing argument asin" unless $asin;
Branch: 1 branch
BranchTrueFalseTotal
unless $asin 0 0 0
1996 0 my $listing;
1997 0 ▶ try { $listing = $self->client
Subroutine __ANON__: not called CC=2 SCAR=17.9
Condition0%0/2
$condition || 'New'
l!l
00
MC/DC0%0/1
$condition || 'New'
$condition
Truth table0%0/2
A
A= $condition
Aresult
11
00
1998 ->GetLowestOfferListingsForASIN(
1999 ASINList => [ $asin ],
2000 MarketplaceId => $self->marketplace_id,
2001 ExcludeMe => 1,
2002 ItemCondition => $condition || 'New',
2003 );
2004 }
2005 0 ▶ catch { die Dumper($_) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
2006  
2007 0 ▶ return unless $listing && @$listing;
Branch: 1 branch
BranchTrueFalseTotal
unless $listing and @$listing 0 0 0
Condition0%0/3
$listing and @$listing
!ll&&!rl&&r
000
MC/DC0%0/2
$listing and @$listing
$listing @$listing
Truth table0%0/3
A and B
A= $listingB= @$listing
ABresult
0X0
100
111
2008 0 my $lowest;
2009 0 foreach my $item (@$listing) {
2010 0 my $current = $item->{Price}->{LandedPrice}->{Amount};
2011 0 ▶ $lowest ||= $current;
Condition0%0/3
$lowest ||= $current
l!l&&r!l&&!r
000
MC/DC0%0/2
$lowest ||= $current
$lowest $current
Truth table0%0/3
A ||= B
A= $lowestB= $current
ABresult
1X1
011
000
2012 0 ▶ if ($current < $lowest) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current < $lowest) 0 0 0
2013 0 $lowest = $current;
2014 }
2015 }
2016 0 return $lowest;
2017 }
2018  
2019 =head2 shipping_confirmation_feed(@shipped_orders)
2020  
2021 Return a feed string with the shipping confirmation. A list of
2022 L<Amazon::MWS::XML::ShippedOrder> object must be passed.
2023  
2024 =cut
2025  
2026 0 ▶sub shipping_confirmation_feed {
Subroutine shipping_confirmation_feed: not called CC=3 SCAR=24.8
Pod documented
2027 0 my ($self, @shipped_orders) = @_;
2028 0 ▶ die "Missing Amazon::MWS::XML::ShippedOrder argument" unless @shipped_orders;
Branch: 1 branch
BranchTrueFalseTotal
unless @shipped_orders 0 0 0
2029 0 my $feeder = $self->generic_feeder;
2030 0 my $counter = 1;
2031 0 my @messages;
2032 0 foreach my $order (@shipped_orders) {
2033 0 push @messages, {
2034 MessageID => $counter++,
2035 OrderFulfillment => $order->as_shipping_confirmation_hashref,
2036 };
2037 }
2038 0 return $feeder->create_feed(OrderFulfillment => \@messages);
2039  
2040 }
2041  
2042 =head2 send_shipping_confirmation($shipped_orders)
2043  
2044 Schedule the shipped orders (an L<Amazon::MWS::XML::ShippedOrder>
2045 object) for the uploading.
2046  
2047 =head2 order_already_shipped($shipped_order)
2048  
2049 Check if the shipped orders (an L<Amazon::MWS::XML::ShippedOrder> was
2050 already notified as shipped looking into our table, returning the row
2051 with the order.
2052  
2053 To see the status, check shipping_confirmation_ok (already done),
2054 shipping_confirmation_error (faulty), shipping_confirmation_job_id (pending).
2055  
2056 =cut
2057  
2058 0 ▶sub order_already_shipped {
Subroutine order_already_shipped: not called CC=3 SCAR=24.8
Pod documented
2059 0 my ($self, $order) = @_;
2060 0 my $condition = $self->_condition_for_shipped_orders($order);
2061 0 my $sth = $self->_exe_query($self->sqla->select(amazon_mws_orders => '*', $condition));
2062 0 ▶ if (my $row = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) { } 0 0 0
2063 0 ▶ die "Multiple results found in amazon_mws_orders for " . Dumper($condition)
Branch: 1 branch
BranchTrueFalseTotal
if $sth->fetchrow_hashref 0 0 0
2064 if $sth->fetchrow_hashref;
2065 0 return $row;
2066 }
2067 else {
2068 0 return;
2069 }
2070 }
2071  
2072 0 ▶sub send_shipping_confirmation {
Subroutine send_shipping_confirmation: not called CC=9 SCAR=45.0
Pod documented
2073 0 my ($self, @orders) = @_;
2074 0 my @orders_to_notify;
2075 0 foreach my $ord (@orders) {
2076 0 ▶ if (my $report = $self->order_already_shipped($ord)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $report = $self->order_already_shipped($ord)) { } 0 0 0
2077 0 ▶ if ($report->{shipping_confirmation_ok}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($report->{'shipping_confirmation_ok'}) { } 0 0 0
elsif (my $error = $report->{'shipping_confirmation_error'}) { } 0 0 0
elsif ($report->{'shipping_confirmation_job_id'}) { } 0 0 0
2078 0 print "Skipping ship-confirm for order $report->{amazon_order_id} $report->{shop_order_id}: already notified\n";
2079 }
2080 elsif (my $error = $report->{shipping_confirmation_error}) {
2081 0 ▶ if ($self->reset_all_errors) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->reset_all_errors) { } 0 0 0
2082 0 warn "Submitting again previously failed job $report->{amazon_order_id} $report->{shop_order_id}\n";
2083 0 push @orders_to_notify, $ord;
2084 }
2085 else {
2086 0 warn "Skipping ship-confirm for order $report->{amazon_order_id} $report->{shop_order_id} with error $error\n";
2087 }
2088 }
2089 elsif ($report->{shipping_confirmation_job_id}) {
2090 0 print "Skipping ship-confirm for order $report->{amazon_order_id} $report->{shop_order_id}: pending\n";
2091 }
2092 else {
2093 0 push @orders_to_notify, $ord;
2094 }
2095 }
2096 else {
2097 0 die "It looks like you are trying to send a shipping confirmation "
2098 . " without prior order acknowlegdement. "
2099 . "At least in the amazon_mws_orders there is no trace of "
2100 . "$report->{amazon_order_id} $report->{shop_order_id}";
2101 }
2102 }
2103 0 ▶ return unless @orders_to_notify;
Branch: 1 branch
BranchTrueFalseTotal
unless @orders_to_notify 0 0 0
2104 0 my $feed_content = $self->shipping_confirmation_feed(@orders_to_notify);
2105 # here we have only one feed to upload and check
2106 0 my $job_id = $self->prepare_feeds(shipping_confirmation => [{
2107 name => 'shipping_confirmation',
2108 content => $feed_content,
2109 }]);
2110 # and store the job id in the table
2111 0 foreach my $ord (@orders_to_notify) {
2112 0 $self->_exe_query($self->sqla->update(amazon_mws_orders => {
2113 shipping_confirmation_job_id => $job_id,
2114 shipping_confirmation_error => undef,
2115 },
2116 $self->_condition_for_shipped_orders($ord)));
2117 }
2118 }
2119  
2120 0 ▶sub _condition_for_shipped_orders {
Subroutine _condition_for_shipped_orders: not called CC=4 SCAR=30.0
2121 0 my ($self, $order) = @_;
2122 0 ▶ die "Missing order" unless $order;
Branch: 1 branch
BranchTrueFalseTotal
unless $order 0 0 0
2123 0 my %condition = (shop_id => $self->_unique_shop_id);
2124 0 ▶ if (my $amazon_order_id = $order->amazon_order_id) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $amazon_order_id = $order->amazon_order_id) { } 0 0 0
elsif (my $order_id = $order->merchant_order_id) { } 0 0 0
2125 0 $condition{amazon_order_id} = $amazon_order_id;
2126 }
2127 elsif (my $order_id = $order->merchant_order_id) {
2128 0 $condition{shop_order_id} = $order_id;
2129 }
2130 else {
2131 0 die "Missing amazon_order_id or merchant_order_id";
2132 }
2133 0 return \%condition;
2134 }
2135  
2136  
2137 =head2 orders_waiting_for_shipping
2138  
2139 Return a list of hashref with two keys, C<amazon_order_id> and
2140 C<shop_order_id> for each order which is waiting confirmation.
2141  
2142 This is implemented looking into amazon_mws_orders where there is no
2143 shipping confirmation job id.
2144  
2145 The confirmed flag (which means we acknowledged the order) is ignored
2146 to avoid stuck order_ack jobs to prevent the shipping confirmation.
2147  
2148 =cut
2149  
2150 0 ▶sub orders_waiting_for_shipping {
Subroutine orders_waiting_for_shipping: not called CC=2 SCAR=17.9
Pod documented
2151 0 my $self = shift;
2152 0 my $sth = $self->_exe_query($self->sqla->select('amazon_mws_orders',
2153 [qw/amazon_order_id
2154 shop_order_id/],
2155 {
2156 shop_id => $self->_unique_shop_id,
2157 shipping_confirmation_job_id => undef,
2158 # do not stop the unconfirmed to be considered
2159 # confirmed => 1,
2160 }));
2161 0 my @out;
2162 0 ▶ while (my $row = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 0 0 0
2163 0 push @out, $row;
2164 }
2165 0 return @out;
2166 }
2167  
2168 =head2 product_needs_upload($sku, $timestamp)
2169  
2170 Lookup the product $sku with timestamp $timestamp and return the sku
2171 if the product needs to be uploaded or can be safely skipped. This
2172 method is stateless and doesn't alter anything.
2173  
2174 =cut
2175  
2176 0 ▶sub product_needs_upload {
Subroutine product_needs_upload: not called CC=24 SCAR=64.0
Pod documented
2177 0 my ($self, $sku, $timestamp) = @_;
2178 0 my $debug = $self->debug;
2179 0 ▶ return unless $sku;
Branch: 1 branch
BranchTrueFalseTotal
unless $sku 0 0 0
2180  
2181 0 my $forced = $self->_force_hashref;
2182 # if it's forced, we have nothing to check, just pass it.
2183 0 ▶ if ($forced->{$sku}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($forced->{$sku}) 0 0 0
2184 0 ▶ print "Forcing $sku as requested\n" if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
2185 0 return $sku;
2186 }
2187  
2188 0 ▶ $timestamp ||= 0;
Condition0%0/2
$timestamp ||= 0
l!l
00
MC/DC0%0/1
$timestamp ||= 0
$timestamp
Truth table0%0/2
A
A= $timestamp
Aresult
11
00
2189 0 my $existing = $self->existing_products;
2190  
2191 0 ▶ if (exists $existing->{$sku}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $existing->{$sku}) 0 0 0
2192 0 ▶ if (my $exists = $existing->{$sku}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $exists = $existing->{$sku}) 0 0 0
2193  
2194 0 ▶ my $status = $exists->{status} || '';
Condition0%0/2
$exists->{'status'} || ''
l!l
00
MC/DC0%0/1
$exists->{'status'} || ''
$exists->{'status'}
Truth table0%0/2
A
A= $exists->{'status'}
Aresult
11
00
2195  
2196 0 ▶ if ($status eq 'ok') {
Branch: 4 branches
BranchTrueFalseTotal
if ($status eq 'ok') { } 0 0 0
elsif ($status eq 'redo') { } 0 0 0
elsif ($status eq 'failed') { } 0 0 0
elsif ($status eq 'pending') { } 0 0 0
2197 0 ▶ if ($exists->{timestamp_string} eq $timestamp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($exists->{'timestamp_string'} eq $timestamp) { } 0 0 0
2198 0 return;
2199 }
2200 else {
2201 0 return $sku;
2202 }
2203 }
2204 elsif ($status eq 'redo') {
2205 0 return $sku;
2206 }
2207 elsif ($status eq 'failed') {
2208 0 ▶ if ($self->reset_all_errors) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->reset_all_errors) { } 0 0 0
elsif (my $reset = $self->_reset_error_structure) { } 0 0 0
2209 0 return $sku;
2210 }
2211 elsif (my $reset = $self->_reset_error_structure) {
2212 # option for this error was passed.
2213 0 my $error = $exists->{error_code};
2214 0 my $match = $reset->{codes}->{$error};
2215 0 ▶ if (($match && $reset->{negate}) or
Branch: 1 branch
BranchTrueFalseTotal
if ($match and $reset->{'negate'} or not $match || $reset->{'negate'}) { } 0 0 0
Condition0%0/9
$match and $reset->{"negate"} or not $match || $reset->{"negate"}
l!l&&r!l&&!r
000
$match and $reset->{"negate"}
!ll&&!rl&&r
000
$match || $reset->{'negate'}
l!l&&r!l&&!r
000
MC/DC0%0/4
$match and $reset->{"negate"} or not $match || $reset->{"negate"}
$match $reset->{"negate"} $match $reset->{'negate'}
Truth table0%0/7
A and B or not(C || D)
A= $matchB= $reset->{"negate"}C= $matchD= $reset->{'negate'}
ABCDresult
11XX1
0X001
10001
0X1X0
0X010
101X0
10010
2216 (!$match && !$reset->{negate})) {
2217 # was passed !this error or !random , so do not reset
2218 0 ▶ print "Skipping failed item $sku with error code $error\n" if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
2219 0 return;
2220 }
2221 else {
2222 # otherwise reset
2223 0 ▶ print "Resetting error for $sku with error code $error\n" if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
2224 0 return $sku;
2225 }
2226 }
2227 else {
2228 0 ▶ print "Skipping failed item $sku\n" if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
2229 0 return;
2230 }
2231 }
2232 elsif ($status eq 'pending') {
2233 0 ▶ print "Skipping pending item $sku\n" if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
2234 0 return;
2235 }
2236 0 die "I shouldn't have reached this point with status <$status>";
2237 }
2238 }
2239 0 ▶ print "$sku wasn't uploaded so far, scheduling it\n" if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
2240 0 return $sku;
2241 }
2242  
2243 =head2 orders_in_shipping_job($job_id)
2244  
2245 Lookup the C<amazon_mws_orders> table and return a list of
2246 C<amazon_order_id> for the given shipping confirmation job. INTERNAL.
2247  
2248 =cut
2249  
2250 0 ▶sub orders_in_shipping_job {
Subroutine orders_in_shipping_job: not called CC=3 SCAR=24.8
Pod documented
2251 0 my ($self, $job_id) = @_;
2252 0 ▶ die unless $job_id;
Branch: 1 branch
BranchTrueFalseTotal
unless $job_id 0 0 0
2253 0 my $sth = $self->_exe_query($self->sqla->select(amazon_mws_orders => [qw/amazon_order_id/],
2254 {
2255 shipping_confirmation_job_id => $job_id,
2256 shop_id => $self->_unique_shop_id,
2257 }));
2258 0 my @orders;
2259 0 ▶ while (my $row = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 0 0 0
2260 0 push @orders, $row->{amazon_order_id};
2261 }
2262 0 return @orders;
2263 }
2264  
2265 =head2 put_product_on_error(sku => $sku, timestamp_string => $timestamp, error_code => $error_code, error_msg => $error)
2266  
2267 Register a custom error for the product $sku with error $error and
2268 $timestamp as the timestamp string. The error is optional, and will be
2269 "shop error" if not provided. The error code will be 1 if not provided.
2270  
2271 =cut
2272  
2273 0 ▶sub put_product_on_error {
Subroutine put_product_on_error: not called CC=6 SCAR=37.4
Pod documented
2274 0 my ($self, %product) = @_;
2275 0 ▶ die "Missing sku" unless $product{sku};
Branch: 1 branch
BranchTrueFalseTotal
unless $product{"sku"} 0 0 0
2276 0 ▶ die "Missing timestamp" unless defined $product{timestamp_string};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $product{"timestamp_string"} 0 0 0
2277  
2278 my %identifier = (
2279 shop_id => $self->_unique_shop_id,
2280 sku => $product{sku},
2281 0 );
2282 my %errors = (
2283 status => 'failed',
2284 error_msg => $product{error_msg} || 'shop error',
2285 error_code => $product{error_code} || 1,
2286 timestamp_string => $product{timestamp_string},
2287 0 ▶ );
Condition0%0/4
$product{'error_msg'} || 'shop error'
l!l
00
$product{'error_code'} || 1
l!l
00
MC/DC0%0/1
$product{'error_msg'} || 'shop error'
$product{'error_msg'}
MC/DC0%0/1
$product{'error_code'} || 1
$product{'error_code'}
Truth table0%0/2
A
A= $product{'error_msg'}
Aresult
11
00
Truth table0%0/2
A
A= $product{'error_code'}
Aresult
11
00
2288  
2289  
2290 # check if we have it
2291 0 my $sth = $self->_exe_query($self->sqla
2292 ->select('amazon_mws_products',
2293 [qw/sku/], { %identifier }));
2294 0 ▶ if ($sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->fetchrow_hashref) { } 0 0 0
2295 0 $sth->finish;
2296 0 print "Updating $product{sku} with error $product{error_msg}\n";
2297 0 $self->_exe_query($self->sqla->update('amazon_mws_products',
2298 \%errors, \%identifier));
2299 }
2300 else {
2301 0 print "Inserting $identifier{sku} with error $errors{error_msg}\n";
2302 0 $self->_exe_query($self->sqla
2303 ->insert('amazon_mws_products',
2304 {
2305 %identifier,
2306 %errors,
2307 }));
2308 }
2309 }
2310  
2311  
2312 =head2 cancel_feed($feed_id)
2313  
2314 Call the CancelFeedSubmissions API and abort the feed and the
2315 belonging job if found in the list. Return the response, which
2316 probably is not even meaningful. It is a big FeedSubmissionInfo with
2317 the past feed submissions.
2318  
2319 =cut
2320  
2321 0 ▶sub cancel_feed {
Subroutine cancel_feed: not called CC=3 SCAR=24.8
Pod documented
2322 0 my ($self, $feed) = @_;
2323 0 ▶ die "Missing feed id argument" unless $feed;
Branch: 1 branch
BranchTrueFalseTotal
unless $feed 0 0 0
2324 # do the api call
2325 0 my $sth = $self->_exe_query($self->sqla
2326 ->select(amazon_mws_feeds => [qw/amws_job_id/],
2327 {
2328 shop_id => $self->_unique_shop_id,
2329 feed_id => $feed,
2330 aborted => 0,
2331 success => 0,
2332 processing_complete => 0,
2333 }));
2334 0 my $feed_record = $sth->fetchrow_hashref;
2335 0 ▶ if ($feed_record) {
Branch: 1 branch
BranchTrueFalseTotal
if ($feed_record) { } 0 0 0
2336 0 $sth->finish;
2337 0 print "Found $feed in pending state\n";
2338 # abort it on our side
2339 0 $self->_exe_query($self->sqla
2340 ->update('amazon_mws_feeds',
2341 {
2342 aborted => 1,
2343 errors => "Canceled by shop action",
2344 },
2345 {
2346 feed_id => $feed,
2347 shop_id => $self->_unique_shop_id,
2348 }));
2349 # and abort the job as well
2350 $self->_exe_query($self->sqla
2351 ->update('amazon_mws_jobs',
2352 {
2353 aborted => 1,
2354 status => "Job aborted by cancel_feed",
2355 },
2356 {
2357 amws_job_id => $feed_record->{amws_job_id},
2358 0 shop_id => $self->_unique_shop_id,
2359 }));
2360 # and set the belonging products to redo
2361 $self->_exe_query($self->sqla
2362 ->update('amazon_mws_products',
2363 {
2364 status => 'redo',
2365 },
2366 {
2367 amws_job_id => $feed_record->{amws_job_id},
2368 0 shop_id => $self->_unique_shop_id,
2369 }));
2370 }
2371 else {
2372 0 warn "No $feed found in pending list, trying to cancel anyway\n";
2373 }
2374 0 return $self->client->CancelFeedSubmissions(IdList => [ $feed ]);
2375 }
2376  
2377 0 ▶sub _error_logger {
Subroutine _error_logger: not called CC=5 SCAR=34.0
2378 0 my ($self, $error_or_warning, $error_code, $message) = @_;
2379 0 my $mode = 'warn';
2380 0 my $modes = $self->skus_warnings_modes;
2381 0 my $out_message = "$error_or_warning: $message ($error_code)\n";
2382 # hardcode 8008 as print
2383 0 $modes->{8008} = 'print';
2384 0 ▶ if (exists $modes->{$error_code}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $modes->{$error_code}) 0 0 0
2385 0 $mode = $modes->{$error_code};
2386 }
2387 0 ▶ if ($mode eq 'print') {
Branch: 3 branches
BranchTrueFalseTotal
if ($mode eq 'print') { } 0 0 0
elsif ($mode eq 'warn') { } 0 0 0
elsif ($mode eq 'skip') { } 0 0 0
2388 0 print $out_message;
2389 }
2390 elsif ($mode eq 'warn') {
2391 0 warn $out_message;
2392 }
2393 elsif ($mode eq 'skip') {
2394 # do nothing
2395 }
2396 else {
2397 0 warn "Invalid mode $mode for $out_message";
2398 }
2399 }
2400  
2401 =head2 update_amw_order_status($amazon_order_number)
2402  
2403 Check the order status on Amazon and update the row in the
2404 amazon_mws_orders table.
2405  
2406 =cut
2407  
2408 0 ▶sub update_amw_order_status {
Subroutine update_amw_order_status: not called CC=7 SCAR=40.3
Pod documented
2409 0 my ($self, $order) = @_;
2410 # first, check if it exists
2411 0 ▶ return unless $order;
Branch: 1 branch
BranchTrueFalseTotal
unless $order 0 0 0
2412 0 my $sth = $self->_exe_query($self->sqla->select('amazon_mws_orders',
2413 '*',
2414 {
2415 amazon_order_id => $order,
2416 shop_id => $self->_unique_shop_id,
2417 }));
2418 0 my $order_ref = $sth->fetchrow_hashref;
2419 0 ▶ die "Multiple rows found for $order!" if $sth->fetchrow_hashref;
Branch: 1 branch
BranchTrueFalseTotal
if $sth->fetchrow_hashref 0 0 0
2420 0 print Dumper($order_ref);
2421 0 my $res = $self->client->GetOrder(AmazonOrderId => [$order]);
2422 0 my $amazon_order;
2423 0 ▶ if ($res && $res->{Orders}->{Order} && @{$res->{Orders}->{Order}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res and $res->{'Orders'}{'Order'} and @{$res->{'Orders'}{'Order'};}) { } 0 0 0
Condition0%0/6
$res and $res->{"Orders"}{"Order"} and @{$res->{"Orders"}{"Order"};}
!ll&&!rl&&r
000
$res and $res->{"Orders"}{"Order"}
!ll&&!rl&&r
000
MC/DC0%0/3
$res and $res->{"Orders"}{"Order"} and @{$res->{"Orders"}{"Order"};}
$res $res->{"Orders"}{"Order"} @{$res->{"Orders"}{"Order"};}
Truth table0%0/4
A and B and C
A= $resB= $res->{"Orders"}{"Order"}C= @{$res->{"Orders"}{"Order"};}
ABCresult
0XX0
10X0
1100
1111
2424 0 ▶ if (@{$res->{Orders}->{Order}} > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$res->{"Orders"}{"Order"};} > 1) 0 0 0
2425 0 warn "Multiple results for order $order: " . Dumper($res);
2426 }
2427 0 $amazon_order = $res->{Orders}->{Order}->[0];
2428 }
2429 else {
2430 0 warn "Order $order not found on amazon!"
2431 }
2432 0 print Dumper($amazon_order);
2433 0 my $obj = Amazon::MWS::XML::Order->new(order => $amazon_order);
2434 0 my $status = $obj->order_status;
2435 0 $self->_exe_query($self->sqla->update('amazon_mws_orders',
2436 { status => $status },
2437 {
2438 amazon_order_id => $order,
2439 shop_id => $self->_unique_shop_id,
2440 }));
2441 0 return $status;
2442 }
2443  
2444 =head2 get_products_with_error_code(@error_codes)
2445  
2446 Return a list of hashref with the rows from C<amazon_mws_products> for
2447 the current shop and the error code passed as argument. If no error
2448 codes are passed, fetch all the products in error.
2449  
2450 =head2 get_products_with_warnings
2451  
2452 Returns a list of hashref, with C<sku> and C<warnings> as keys, for
2453 each product in the shop which has the warnings set to something.
2454  
2455 =cut
2456  
2457 0 ▶sub get_products_with_error_code {
Subroutine get_products_with_error_code: not called CC=3 SCAR=24.8
Pod documented
2458 0 my ($self, @errcodes) = @_;
2459 0 my $where = { '>' => 0 };
2460 0 ▶ if (@errcodes) {
Branch: 1 branch
BranchTrueFalseTotal
if (@errcodes) 0 0 0
2461 0 $where = { -in => \@errcodes };
2462 }
2463 0 my $sth = $self->_exe_query($self->sqla
2464 ->select('amazon_mws_products', '*',
2465 {
2466 status => { '!=' => 'deleted' },
2467 shop_id => $self->_unique_shop_id,
2468 error_code => $where,
2469 },
2470 [qw/error_code sku/]));
2471 0 my @records;
2472 0 ▶ while (my $row = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 0 0 0
2473 0 push @records, $row;
2474 }
2475 0 return @records;
2476 }
2477  
2478 0 ▶sub get_products_with_warnings {
Subroutine get_products_with_warnings: not called CC=2 SCAR=17.9
Pod documented
2479 0 my $self = shift;
2480 0 my $sth = $self->_exe_query($self->sqla
2481 ->select('amazon_mws_products', '*',
2482 {
2483 status => 'ok',
2484 shop_id => $self->_unique_shop_id,
2485 warnings => { '!=' => '' },
2486 },
2487 [qw/sku warnings/]));
2488 0 my @records;
2489 0 ▶ while (my $row = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 0 0 0
2490 0 push @records, $row;
2491 }
2492 0 return @records;
2493 }
2494  
2495 =head2 mark_failed_products_as_redo(@skus)
2496  
2497 Alter the status of the failed skus passed as argument from 'failed'
2498 to 'redo' to trigger an update.
2499  
2500 =cut
2501  
2502 0 ▶sub mark_failed_products_as_redo {
Subroutine mark_failed_products_as_redo: not called CC=2 SCAR=17.9
Pod documented
2503 0 my ($self, @skus) = @_;
2504 0 ▶ return unless @skus;
Branch: 1 branch
BranchTrueFalseTotal
unless @skus 0 0 0
2505 0 $self->_exe_query($self->sqla->update('amazon_mws_products',
2506 {
2507 status => 'redo',
2508 },
2509 {
2510 shop_id => $self->_unique_shop_id,
2511 status => 'failed',
2512 sku => { -in => \@skus },
2513 }));
2514 }
2515  
2516 =head2 get_products_with_amazon_shop_mismatches(@errors)
2517  
2518 Parse the amazon_mws_products and return an hashref where the keys are
2519 the failed skus, and the values are hashrefs where the keys are the
2520 mismatched fields and the values are hashrefs with these keys:
2521  
2522 Mismatched fields may be: C<part_number>, C<title>, C<manufacturer>,
2523 C<brand>, C<color>, C<size>
2524  
2525 =over 4
2526  
2527 =item shop
2528  
2529 The value on the shop
2530  
2531 =item amazon
2532  
2533 The value of the amazon product
2534  
2535 =item error_code
2536  
2537 The error code
2538  
2539 =back
2540  
2541 E.g.
2542  
2543 my $mismatches = {12344 => {
2544 part_number => {
2545 shop => 'XY',
2546 amazon => 'XYZ',
2547 error_code => '8541',
2548 },
2549 title => {
2550 shop => 'ABC',
2551 amazon => 'DFG',
2552 error_code => '8541',
2553 },
2554 },
2555 .....
2556 };
2557  
2558 Optionally, if the error codes are passed to the argument, only those
2559 errors are fetches.
2560  
2561 =cut
2562  
2563  
2564 0 ▶sub get_products_with_amazon_shop_mismatches {
Subroutine get_products_with_amazon_shop_mismatches: not called CC=5 SCAR=34.0
Pod documented
2565 0 my ($self, @errors) = @_;
2566 # so far only this code is for mismatches
2567 0 my %mismatches;
2568 0 my @faulty = $self->get_products_with_error_code(@errors);
2569 0 foreach my $product (@faulty) {
2570 # only if failed.
2571 0 ▶ next if $product->{status} ne 'failed';
Branch: 1 branch
BranchTrueFalseTotal
if $product->{"status"} ne "failed" 0 0 0
2572 0 my $msg = $product->{error_msg};
2573 0 my $error_code = $product->{error_code};
2574 0 my $sku = $product->{sku};
2575 0 my $errors = $self->_parse_error_message_mismatches($msg);
2576 0 foreach my $key (keys %$errors) {
2577 # in this case, we are interested only in the pairs
2578 0 ▶ if (ref($errors->{$key}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $errors->{$key} eq "HASH") 0 0 0
2579 # we have the pair, so add the error code and report
2580 0 $errors->{$key}->{error_code} = $error_code;
2581 0 $mismatches{$sku}{$key} = $errors->{$key};
2582 }
2583 }
2584 }
2585 0 return \%mismatches;
2586 }
2587  
2588 =head2 get_products_with_mismatches(@errors)
2589  
2590 Similar to C<get_products_with_amazon_shop_mismatches>, but instead
2591 return an arrayref where each element is a hashref with all the info
2592 collapsed.
2593  
2594 The structures reported by C<get_products_with_amazon_shop_mismatches>
2595 are flattened with an C<our_> and C<amazon_> prefix.
2596  
2597 our_part_number => 'XY',
2598 amazon_part_number => 'YZ',
2599 our_title = 'xx',
2600 amazon_title => 'yy',
2601 # etc.
2602  
2603  
2604 =cut
2605  
2606 0 ▶sub get_products_with_mismatches {
Subroutine get_products_with_mismatches: not called CC=2 SCAR=17.9
Pod documented
2607 0 my ($self, @errors) = @_;
2608 0 my @faulty = $self->get_products_with_error_code(@errors);
2609 0 my @out;
2610 0 ▶ while (@faulty) {
Branch: 1 branch
BranchTrueFalseTotal
if (@faulty) 0 0 0
2611 0 my $product = shift @faulty;
2612 0 my $errors = $self->_parse_error_message_mismatches($product->{error_msg});
2613 0 push @out, { %$product, %$errors };
2614 }
2615 0 return \@out;
2616 }
2617  
2618 0 ▶sub _parse_error_message_mismatches {
Subroutine _parse_error_message_mismatches: not called CC=7 SCAR=40.3
2619 0 my ($self, $message) = @_;
2620 0 ▶ return {} unless $message;
Branch: 1 branch
BranchTrueFalseTotal
unless $message 0 0 0
2621 0 my %patterns = %{$self->_mismatch_patterns};
2622 0 my %out;
2623 0 foreach my $key (keys %patterns) {
2624 # if the pattern start we shop_ or amazon_, it's a pair
2625 0 my ($mismatch, $target);
2626 0 ▶ if ($key =~ /\A(shop|amazon)_(.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key =~ /\A(shop|amazon)_(.+)/) 0 0 0
2627 0 $target = $1;
2628 0 $mismatch = $2;
2629 }
2630 0 ▶ if ($message =~ $patterns{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($message =~ /$patterns{$key}/) 0 0 0
2631 0 my $value = $1;
2632 0 ▶ if ($target && $mismatch) {
Branch: 1 branch
BranchTrueFalseTotal
if ($target and $mismatch) 0 0 0
Condition0%0/3
$target and $mismatch
!ll&&!rl&&r
000
MC/DC0%0/2
$target and $mismatch
$target $mismatch
Truth table0%0/3
A and B
A= $targetB= $mismatch
ABresult
0X0
100
111
2633 0 $out{$mismatch}{$target} = $value;
2634 }
2635 # and in any case store a scalar (and let's hope not to conflict)
2636 0 $out{$key} = $value;
2637 }
2638 }
2639 0 return \%out;
2640 }
2641  
2642 =head2 Order Report
2643  
2644 To get this feature working, you need an C<amzn-envelope.xsd> with
2645 OrderReport plugged in. Older versions are broken. Newer schema
2646 versions may have missing Amazon.xsd file. So either you ask amazon to
2647 give you a B<full set of xsd, which inclused OrderReport in
2648 amzn-envelope.xsd> or you apply this patch to amzn-envelope.xsd:
2649  
2650 --- a/amzn-envelope.xsd 2014-10-27 10:26:19.000000000 +0100
2651 +++ b/amzn-envelope.xsd 2015-03-26 10:56:16.000000000 +0100
2652 @@ -23,2 +23,3 @@
2653 <xsd:include schemaLocation="Price.xsd"/>
2654 + <xsd:include schemaLocation="OrderReport.xsd"/>
2655 <xsd:include schemaLocation="ProcessingReport.xsd"/>
2656 @@ -41,2 +42,3 @@
2657 <xsd:enumeration value="OrderFulfillment"/>
2658 + <xsd:enumeration value="OrderReport"/>
2659 <xsd:enumeration value="Override"/>
2660 @@ -83,2 +85,3 @@
2661 <xsd:element ref="OrderFulfillment"/>
2662 + <xsd:element ref="OrderReport"/>
2663 <xsd:element ref="Override"/>
2664  
2665 =head3 get_unprocessed_orders
2666  
2667 Return a list of objects with the orders.
2668  
2669 =head3 get_unprocessed_order_report_ids
2670  
2671 Return a list of unprocessed (i.e., which weren't acknowledged by us)
2672 order report ids.
2673  
2674 =cut
2675  
2676 0 ▶sub get_unprocessed_orders {
Subroutine get_unprocessed_orders: not called CC=1 SCAR=6.9
Pod documented
2677 0 my ($self) = @_;
2678 0 my @ids = $self->get_unprocessed_order_report_ids;
2679 0 my @orders = $self->get_order_reports_by_id(@ids);
2680 0 return @orders;
2681 }
2682  
2683 0 ▶sub get_unprocessed_order_report_ids {
Subroutine get_unprocessed_order_report_ids: not called CC=5 SCAR=34.0
Pod documented
2684 0 my ($self, %options) = @_;
2685 0 my $res;
2686 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2687 0 $res = $self->client
2688 ->GetReportList(Acknowledged => 0,
2689 ReportTypeList => ['_GET_ORDERS_DATA_'],
2690 %options,
2691 );
2692 0 ▶ } catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2693 0 _handle_exception($_);
2694 0 };
2695  
2696 0 my @reportids;
2697  
2698 # for now, do not ask for the next token, we will process them all
2699 # eventually
2700  
2701 0 ▶ if ($res and $res->{ReportInfo}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res and $res->{"ReportInfo"}) 0 0 0
Condition0%0/3
$res and $res->{"ReportInfo"}
!ll&&!rl&&r
000
MC/DC0%0/2
$res and $res->{"ReportInfo"}
$res $res->{"ReportInfo"}
Truth table0%0/3
A and B
A= $resB= $res->{"ReportInfo"}
ABresult
0X0
100
111
2702 0 foreach my $report (@{$res->{ReportInfo}}) {
2703 0 ▶ if (my $id = $report->{ReportId}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = $report->{"ReportId"}) 0 0 0
2704 0 push @reportids, $id;
2705 }
2706 }
2707 }
2708 0 return @reportids;
2709 }
2710  
2711  
2712 =head3 get_order_reports_by_id(@id_list)
2713  
2714 The GetReport operation has a maximum request quota of 15 and a
2715 restore rate of one request every minute.
2716  
2717 =cut
2718  
2719 0 ▶sub get_order_reports_by_id {
Subroutine get_order_reports_by_id: not called CC=4 SCAR=30.0
Pod documented
2720 0 my ($self, @ids) = @_;
2721 0 my @orders;
2722 0 foreach my $id (@ids) {
2723 0 my $xml;
2724 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2725 0 $xml = $self->client->GetReport(ReportId => $id);
2726 0 ▶ } catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2727 0 _handle_exception($_);
2728 0 };
2729 0 ▶ if ($xml) {
Branch: 1 branch
BranchTrueFalseTotal
if ($xml) 0 0 0
2730 0 ▶ if (my @got = $self->_parse_order_reports_xml($xml)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@got) = $self->_parse_order_reports_xml($xml)) 0 0 0
2731 0 push @orders, @got;
2732 }
2733 }
2734 }
2735 0 return @orders;
2736 }
2737  
2738 0 ▶sub _parse_order_reports_xml {
Subroutine _parse_order_reports_xml: not called CC=4 SCAR=30.0
2739 0 my ($self, $xml) = @_;
2740 0 my @orders;
2741 0 my $data = $self->xml_reader->($xml);
2742 0 ▶ if (my $messages = $data->{Message}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $messages = $data->{"Message"}) 0 0 0
2743 0 foreach my $message (@$messages) {
2744 0 ▶ if (my $order = $message->{OrderReport}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $order = $message->{'OrderReport'}) { } 0 0 0
2745 0 my $order_object = Amazon::MWS::XML::Response::OrderReport->new(struct => $order);
2746 0 push @orders, $order_object;
2747 }
2748 else {
2749 0 die "Cannot found expected OrderReport in " . Dumper($message);
2750 }
2751 }
2752 }
2753 0 return @orders;
2754 }
2755  
2756  
2757 =head2 acknowledge_reports(@ids)
2758  
2759 Mark the reports as processed.
2760  
2761 =head2 unacknowledge_reports(@ids)
2762  
2763 Mark the reports as not processed.
2764  
2765 =cut
2766  
2767 0 ▶sub acknowledge_reports {
Subroutine acknowledge_reports: not called CC=1 SCAR=6.9
Pod documented
2768 0 my ($self, @ids) = @_;
2769 0 $self->_toggle_ack_reports(1, @ids);
2770 }
2771  
2772 0 ▶sub unacknowledge_reports {
Subroutine unacknowledge_reports: not called CC=1 SCAR=6.9
Pod documented
2773 0 my ($self, @ids) = @_;
2774 0 $self->_toggle_ack_reports(0, @ids);
2775 }
2776  
2777 0 ▶sub _toggle_ack_reports {
Subroutine _toggle_ack_reports: not called CC=3 SCAR=24.8
2778 0 my ($self, $flag, @ids) = @_;
2779 0 ▶ return unless @ids;
Branch: 1 branch
BranchTrueFalseTotal
unless @ids 0 0 0
2780 0 ▶ while (@ids) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ids) 0 0 0
2781 # max 100 ids per run
2782 0 my @list = splice(@ids, 0, 100);
2783 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2784 0 $self->client->UpdateReportAcknowledgements(ReportIdList => \@list,
2785 Acknowledged => $flag);
2786 0 ▶ } catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2787 0 _handle_exception($_);
2788 0 };
2789 }
2790 0 return;
2791 }
2792  
2793 0 ▶sub _handle_exception {
Subroutine _handle_exception: not called CC=6 SCAR=37.4
2794 0 my ($err) = @_;
2795 0 ▶ if (blessed $err) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($err)) 0 0 0
2796 0 my $msg;
2797 0 ▶ if ( $err->isa('Amazon::MWS::Exception::Throttled') ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($err->isa('Amazon::MWS::Exception::Throttled')) { } 0 0 0
elsif ($err->isa('Amazon::MWS::Exception')) { } 0 0 0
2798 0 $msg = $err->xml;
2799 }
2800 elsif ( $err->isa('Amazon::MWS::Exception')) {
2801 0 ▶ if (my $string = $err->error) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $string = $err->error) { } 0 0 0
2802 0 $msg = $string;
2803 }
2804 else {
2805 0 $msg = Dumper($err);
2806 }
2807 }
2808 else {
2809 0 $msg = Dumper($err);
2810 }
2811 0 ▶ if ( $err->isa('Amazon::MWS::Exception')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err->isa("Amazon::MWS::Exception")) 0 0 0
2812 0 $msg .= "\n" . $err->trace->as_string . "\n";
2813 }
2814 0 die $msg;
2815 }
2816 0 die $err;
2817 }
2818  
2819 =head2 job_timed_out($job_row) [INTERNAL]
2820  
2821 Check if the hashref (which is a hashref of the amazon_mws_jobs row)
2822 has timed out, comparing with the C<order_ack_days_timeout> and
2823 C<job_hours_timeout> (depending on the job).
2824  
2825  
2826 =cut
2827  
2828 0 ▶sub job_timed_out {
Subroutine job_timed_out: not called CC=7 SCAR=40.3
Pod documented
2829 0 my ($self, $job_row) = @_;
2830 0 my $task = $job_row->{task};
2831 0 ▶ die "Missing task in $job_row->{amws_job_id}" unless $task;
Branch: 1 branch
BranchTrueFalseTotal
unless $task 0 0 0
2832 0 my $started = $job_row->{job_started_epoch};
2833 0 ▶ die "Missing job_started_epoch in $job_row->{amws_job_id}" unless $started;
Branch: 1 branch
BranchTrueFalseTotal
unless $started 0 0 0
2834 0 my $now = time();
2835 0 my $timeout;
2836 0 ▶ if ($task eq 'order_ack') {
Branch: 1 branch
BranchTrueFalseTotal
if ($task eq 'order_ack') { } 0 0 0
2837 0 $timeout = $self->order_ack_days_timeout * 60 * 60 * 24;
2838 }
2839 else {
2840 0 $timeout = $self->job_hours_timeout * 60 * 60;
2841 }
2842 0 ▶ die "Something is off, timeout not defined" unless defined $timeout;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $timeout 0 0 0
2843 0 ▶ return unless $timeout;
Branch: 1 branch
BranchTrueFalseTotal
unless $timeout 0 0 0
2844 0 my $elapsed = $now - $started;
2845 0 ▶ if ($elapsed > $timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elapsed > $timeout) { } 0 0 0
2846 0 return $elapsed;
2847 }
2848 else {
2849 0 return;
2850 }
2851 }
2852  
2853 0 ▶sub _print_or_warn_error {
Subroutine _print_or_warn_error: not called CC=3 SCAR=24.8
2854 0 my ($self, @args) = @_;
2855 0 my $action;
2856 0 ▶ if (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 0 0 0
2857 0 ▶ if ($self->quiet) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->quiet) { } 0 0 0
2858 0 $action = 'print';
2859 0 print @args;
2860 }
2861 else {
2862 0 $action = 'warn';
2863 0 warn @args;
2864 }
2865 }
2866 0 return ($action, @args);
2867 }
2868  
2869 =head2 purge_old_jobs($limit)
2870  
2871 Eventually the jobs and feed tables grow and never get purged. You can
2872 call this method to remove from the db all the feeds older than
2873 C<order_ack_days_timeout> (30 by default).
2874  
2875 To avoid too much load on the db, you can set the limit to purge the
2876 jobs. Defaults to 500. Set it to 0 to disable it.
2877  
2878 =cut
2879  
2880 0 ▶sub purge_old_jobs {
Subroutine purge_old_jobs: not called CC=10 SCAR=47.0
Pod documented
2881 0 my ($self, $limit) = @_;
2882 0 ▶ unless (defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $limit) 0 0 0
2883 0 $limit = 500;
2884 }
2885 0 my $range = time() - $self->order_ack_days_timeout * 60 * 60 * 24;
2886 0 my @and = (
2887 task => [qw/product_deletion
2888 upload/],
2889 job_started_epoch => { '<', $range },
2890 [ -or => {
2891 aborted => 1,
2892 success => 1,
2893 },
2894 ],
2895 );
2896 0 ▶ if (my $shop_id = $self->shop_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $shop_id = $self->shop_id) 0 0 0
2897 0 push @and, shop_id => $shop_id;
2898 }
2899  
2900 0 my $sth = $self->_exe_query($self->sqla
2901 ->select(amazon_mws_jobs => [qw/amws_job_id shop_id/],
2902 [ -and => \@and ] ));
2903 0 my @purge_jobs;
2904 0 my $count = 0;
2905 0 ▶ while (my $where = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $where = $sth->fetchrow_hashref) 0 0 0
2906 0 ▶ if ($limit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit) 0 0 0
2907 0 ▶ last if $count++ > $limit;
Branch: 1 branch
BranchTrueFalseTotal
if $count++ > $limit 0 0 0
2908 }
2909 0 push @purge_jobs, $where;
2910 }
2911 0 $sth->finish;
2912 0 ▶ if (@purge_jobs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@purge_jobs) { } 0 0 0
2913 0 $self->_exe_query($self->sqla->delete(amazon_mws_feeds => \@purge_jobs));
2914 0 $self->_exe_query($self->sqla->delete(amazon_mws_jobs => \@purge_jobs));
2915 0 ▶ while (@purge_jobs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@purge_jobs) 0 0 0
2916 0 my $feed = shift @purge_jobs;
2917 0 my $dir = path($self->feed_dir)->child($feed->{shop_id}, $feed->{amws_job_id});
2918 0 ▶ if ($dir->exists) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dir->exists) { } 0 0 0
2919 0 print "Removing " . $dir->canonpath . "\n"; # unless $self->quiet;
2920 0 $dir->remove_tree;
2921 }
2922 else {
2923 0 print "$dir doesn't exist\n";
2924 }
2925 }
2926 }
2927 else {
2928 0 ▶ print "Nothing to purge\n" unless $self->quiet;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->quiet 0 0 0
2929 }
2930 }
2931  
2932 6 1;
↑ Summary MWS/XML/Product.pm »