ddaf57f4c3e1752ce2cf39d73d4bbd5c79895471
[kivitendo-erp.git] / SL / BackgroundJob / ShopPartMassUpload.pm
1 package SL::BackgroundJob::ShopPartMassUpload;
2
3 use strict;
4 use warnings;
5
6 use parent qw(SL::BackgroundJob::Base);
7
8 use SL::DBUtils;
9 use SL::DB::ShopPart;
10 use SL::Shop;
11
12 use constant WAITING_FOR_EXECUTION        => 0;
13 use constant UPLOAD_TO_WEBSHOP            => 1;
14 use constant DONE                         => 2;
15
16 # Data format:
17 # my $data                  = {
18 #     shop_part_record_ids         => [ 603, 604, 605 ],
19 #     todo                         => $::form->{upload_todo},
20 #     status                       => SL::BackgroundJob::ShopPartMassUpload->WAITING_FOR_EXECUTION(),
21 #     num_uploaded                 => 0,
22 #     conversation                 => [ { id => 603 , number => 2, message => "Ok" or $@ }, ],
23 # };
24
25 sub update_webarticles {
26   my ( $self ) = @_;
27
28   my $job_obj = $self->{job_obj};
29   my $db      = $job_obj->db;
30
31   $job_obj->set_data(UPLOAD_TO_WEBSHOP())->save;
32   my $num_uploaded = 0;
33   foreach my $shop_part_id (@{ $job_obj->data_as_hash->{shop_part_record_ids} }) {
34     my $data  = $job_obj->data_as_hash;
35     eval {
36       my $shop_part = SL::DB::Manager::ShopPart->find_by(id => $shop_part_id);
37       unless($shop_part){
38         push @{ $data->{conversion} }, { id => $shop_part_id, number => '', message => 'Shoppart not found' };
39       }
40
41       my $shop = SL::Shop->new( config => $shop_part->shop );
42
43       my $return    = $shop->connector->update_part($shop_part, $data->{todo});
44       if ( $return == 1 ) {
45         my $now = DateTime->now;
46         my $attributes->{last_update} = $now;
47         $shop_part->assign_attributes(%{ $attributes });
48         $shop_part->save;
49         $data->{num_uploaded} = $num_uploaded++;
50         push @{ $data->{conversion} }, { id => $shop_part_id, number => $shop_part->part->partnumber, message => 'uploaded' };
51       }else{
52       push @{ $data->{conversion} }, { id => $shop_part_id, number => $shop_part->part->partnumber, message => $return };
53       }
54       1;
55     } or do {
56       push @{ $data->{conversion} }, { id => $shop_part_id, number => '', message => $@ };
57     };
58
59     $job_obj->update_attributes(data_as_hash => $data);
60   }
61 }
62
63 sub run {
64   my ($self, $job_obj) = @_;
65
66   $self->{job_obj}         = $job_obj;
67   $self->update_webarticles;
68
69   $job_obj->set_data(status => DONE())->save;
70
71   return 1;
72 }
73 1;