Bug 22417: Fix the batch authority tool
[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::Exceptions;
11 use Koha::BackgroundJob::BatchUpdateBiblio;
12 use Koha::BackgroundJob::BatchUpdateAuthority;
13
14 use base qw( Koha::Object );
15
16 sub connect {
17     my ( $self );
18     my $stomp = Net::Stomp->new( { hostname => 'localhost', port => '61613' } );
19     $stomp->connect( { login => 'guest', passcode => 'guest' } );
20     return $stomp;
21 }
22
23 sub enqueue {
24     my ( $self, $params ) = @_;
25
26     my $job_type = $self->job_type;
27     my $job_size = $params->{job_size};
28     my $job_args = $params->{job_args};
29
30     my $borrowernumber = C4::Context->userenv->{number}; # FIXME Handle non GUI calls
31     my $json_args = encode_json $job_args;
32     my $job_id;
33     $self->_result->result_source->schema->txn_do(
34         sub {
35             $self->set(
36                 {
37                     status         => 'new',
38                     type           => $job_type,
39                     size           => $job_size,
40                     data           => $json_args,
41                     enqueued_on    => dt_from_string,
42                     borrowernumber => $borrowernumber,
43                 }
44             )->store;
45
46             $job_id = $self->id;
47             $job_args->{job_id} = $job_id;
48             $json_args = encode_json $job_args;
49
50             my $conn = $self->connect;
51             $conn->send_with_receipt( { destination => $job_type, body => $json_args } )
52               or Koha::Exceptions::Exception->throw('Job has not been enqueued');
53         }
54     );
55
56     return $job_id;
57 }
58
59 sub process {
60     my ( $self, $args ) = @_;
61
62     my $job_type = $self->type;
63     return $job_type eq 'batch_biblio_record_modification'
64       ? Koha::BackgroundJob::BatchUpdateBiblio->process($args)
65       : $job_type eq 'batch_authority_record_modification'
66       ? Koha::BackgroundJob::BatchUpdateAuthority->process($args)
67       : Koha::Exceptions::Exception->throw('->process called without valid job_type');
68 }
69
70 sub job_type { croak "This method must be subclassed" }
71
72 sub messages {
73     my ( $self ) = @_;
74
75     my @messages;
76     my $data_dump = decode_json $self->data;
77     if ( exists $data_dump->{messages} ) {
78         @messages = @{ $data_dump->{messages} };
79     }
80
81     return @messages;
82 }
83
84 sub report {
85     my ( $self ) = @_;
86
87     my $data_dump = decode_json $self->data;
88     return $data_dump->{report};
89 }
90
91 sub cancel {
92     my ( $self ) = @_;
93     $self->status('cancelled')->store;
94 }
95
96 sub _type {
97     return 'BackgroundJob';
98 }
99
100 1;