Bug 22417: Handle errors
[koha.git] / Koha / BackgroundJob.pm
1 package Koha::BackgroundJob;
2
3 use Modern::Perl;
4 use JSON qw( encode_json decode_json );
5 use Carp qw( croak );
6 use Net::Stomp;
7
8 use C4::Context;
9 use Koha::DateUtils qw( dt_from_string );
10 use Koha::BackgroundJobs;
11
12 use base qw( Koha::Object );
13
14 sub connect {
15     my ( $self );
16     my $stomp = Net::Stomp->new( { hostname => 'localhost', port => '61613' } );
17     $stomp->connect( { login => 'guest', passcode => 'guest' } );
18     return $stomp;
19 }
20
21 sub enqueue {
22     my ( $self, $params ) = @_;
23
24     my $job_type = $params->{job_type};
25     my $job_size = $params->{job_size};
26     my $job_args = $params->{job_args};
27
28     my $borrowernumber = C4::Context->userenv->{number}; # FIXME Handle non GUI calls
29     my $json_args = encode_json $job_args;
30     my $job_id;
31     $self->_result->result_source->schema->txn_do(
32         sub {
33             $self->set(
34                 {
35                     status         => 'new',
36                     type           => $job_type,
37                     size           => $job_size,
38                     data           => $json_args,
39                     enqueued_on    => dt_from_string,
40                     borrowernumber => $borrowernumber,
41                 }
42             )->store;
43
44             $job_id = $self->id;
45             $job_args->{job_id} = $job_id;
46             $json_args = encode_json $job_args;
47
48             my $conn = $self->connect;
49             $conn->send_with_receipt( { destination => $job_type, body => $json_args } )
50               or Koha::Exception->throw('Job has not been enqueued');
51         }
52     );
53
54     return $job_id;
55 }
56
57 sub process { croak "This method must be subclassed" }
58
59 sub messages {
60     my ( $self ) = @_;
61
62     my @messages;
63     my $data_dump = decode_json $self->data;
64     if ( exists $data_dump->{messages} ) {
65         @messages = @{ $data_dump->{messages} };
66     }
67
68     return @messages;
69 }
70
71 sub report {
72     my ( $self ) = @_;
73
74     my $data_dump = decode_json $self->data;
75     return $data_dump->{report};
76 }
77
78 sub cancel {
79     my ( $self ) = @_;
80     $self->status('cancelled')->store;
81 }
82
83 sub _type {
84     return 'BackgroundJob';
85 }
86
87 1;