Bug 27783: Rename queues and adjust currently defined jobs
[koha.git] / Koha / BackgroundJob / BatchDeleteAuthority.pm
1 package Koha::BackgroundJob::BatchDeleteAuthority;
2
3 use Modern::Perl;
4 use JSON qw( encode_json decode_json );
5
6 use Koha::DateUtils qw( dt_from_string );
7 use C4::AuthoritiesMarc;
8
9 use base 'Koha::BackgroundJob';
10
11 sub job_type {
12     return 'batch_authority_record_deletion';
13 }
14
15 sub process {
16     my ( $self, $args ) = @_;
17
18     if ( $self->status eq 'cancelled' ) {
19         return;
20     }
21
22     # FIXME If the job has already been started, but started again (worker has been restart for instance)
23     # Then we will start from scratch and so double delete the same records
24
25     my $job_progress = 0;
26     $self->started_on(dt_from_string)
27         ->progress($job_progress)
28         ->status('started')
29         ->store;
30
31     my $mmtid = $args->{mmtid};
32     my @record_ids = @{ $args->{record_ids} };
33
34     my $report = {
35         total_records => scalar @record_ids,
36         total_success => 0,
37     };
38     my @messages;
39     my $schema = Koha::Database->new->schema;
40     RECORD_IDS: for my $record_id ( sort { $a <=> $b } @record_ids ) {
41
42         last if $self->get_from_storage->status eq 'cancelled';
43
44         next unless $record_id;
45
46         $schema->storage->txn_begin;
47
48         my $authid = $record_id;
49         eval { C4::AuthoritiesMarc::DelAuthority({ authid => $authid }) };
50         if ( $@ ) {
51             push @messages, {
52                 type => 'error',
53                 code => 'authority_not_deleted',
54                 authid => $authid,
55                 error => "$@",
56             };
57             $schema->storage->txn_rollback;
58             next;
59         } else {
60             push @messages, {
61                 type => 'success',
62                 code => 'authority_deleted',
63                 authid => $authid,
64             };
65             $report->{total_success}++;
66             $schema->storage->txn_commit;
67         }
68
69         $self->progress( ++$job_progress )->store;
70     }
71
72     my $job_data = decode_json $self->data;
73     $job_data->{messages} = \@messages;
74     $job_data->{report} = $report;
75
76     $self->ended_on(dt_from_string)
77         ->data(encode_json $job_data);
78     $self->status('finished') if $self->status ne 'cancelled';
79     $self->store;
80 }
81
82 sub enqueue {
83     my ( $self, $args) = @_;
84
85     # TODO Raise exception instead
86     return unless exists $args->{record_ids};
87
88     my @record_ids = @{ $args->{record_ids} };
89
90     $self->SUPER::enqueue({
91         job_size => scalar @record_ids,
92         job_args => {record_ids => \@record_ids,},
93         queue    => 'long_tasks',
94     });
95 }
96
97 1;