Bug 22417: Fix borrowernumber values
[srvgit] / 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::RabbitFoot;
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 $conn = Net::RabbitFoot->new()->load_xml_spec()->connect(
17         host => 'localhost', # TODO Move this to KOHA_CONF
18         port => 5672,
19         user => 'guest',
20         pass => 'guest',
21         vhost => '/',
22     );
23
24     return $conn;
25 }
26
27 sub enqueue {
28     my ( $self, $params ) = @_;
29
30     my $job_type = $params->{job_type};
31     my $job_size = $params->{job_size};
32     my $job_args = $params->{job_args};
33
34     my $borrowernumber = C4::Context->userenv->{number}; # FIXME Handle non GUI calls
35     my $json_args = encode_json $job_args;
36     $self->set({
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     })->store;
44
45     my $job_id = $self->id;
46     $job_args->{job_id} = $job_id;
47     $json_args = encode_json $job_args,
48
49     my $conn = $self->connect;
50     my $channel = $conn->open_channel();
51
52     $channel->declare_queue(
53         queue => $job_type,
54         durable => 1,
55     );
56
57     $channel->publish(
58         exchange => '',
59         routing_key => $job_type, # TODO Must be different?
60         body => $json_args,
61     );
62     $conn->close;
63     return $job_id;
64 }
65
66 sub process { croak "This method must be subclassed" }
67
68 sub messages {
69     my ( $self ) = @_;
70
71     my @messages;
72     my $data_dump = decode_json $self->data;
73     if ( exists $data_dump->{messages} ) {
74         @messages = @{ $data_dump->{messages} };
75     }
76
77     return @messages;
78 }
79
80 sub report {
81     my ( $self ) = @_;
82
83     my $data_dump = decode_json $self->data;
84     return $data_dump->{report};
85 }
86
87 sub cancel {
88     my ( $self ) = @_;
89     $self->status('cancelled')->store;
90 }
91
92 sub _type {
93     return 'BackgroundJob';
94 }
95
96 1;