Bug 33974: (QA follow-up) Remove superflous import
[koha.git] / Koha / BackgroundJob / BatchDeleteAuthority.pm
1 package Koha::BackgroundJob::BatchDeleteAuthority;
2
3 use Modern::Perl;
4
5 use C4::AuthoritiesMarc;
6
7 use Koha::SearchEngine;
8 use Koha::SearchEngine::Indexer;
9
10 use base 'Koha::BackgroundJob';
11
12 sub job_type {
13     return 'batch_authority_record_deletion';
14 }
15
16 sub process {
17     my ( $self, $args ) = @_;
18
19     if ( $self->status eq 'cancelled' ) {
20         return;
21     }
22
23     # FIXME If the job has already been started, but started again (worker has been restart for instance)
24     # Then we will start from scratch and so double delete the same records
25
26     $self->start;
27
28     my $mmtid = $args->{mmtid};
29     my @record_ids = @{ $args->{record_ids} };
30
31     my $report = {
32         total_records => scalar @record_ids,
33         total_success => 0,
34     };
35     my @messages;
36     my $schema = Koha::Database->new->schema;
37     RECORD_IDS: for my $record_id ( sort { $a <=> $b } @record_ids ) {
38
39         last if $self->get_from_storage->status eq 'cancelled';
40
41         next unless $record_id;
42
43         $schema->storage->txn_begin;
44
45         my $authid = $record_id;
46         eval {
47             C4::AuthoritiesMarc::DelAuthority(
48                 { authid => $authid, skip_record_index => 1 } );
49         };
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->step;
70     }
71
72     my @deleted_authids =
73       map { $_->{code} eq 'authority_deleted' ? $_->{authid} : () }
74           @messages;
75
76     if ( @deleted_authids ) {
77         my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::AUTHORITIES_INDEX });
78         $indexer->index_records( \@deleted_authids, "recordDelete", "authorityserver" );
79     }
80
81     my $data = $self->decoded_data;
82     $data->{messages} = \@messages;
83     $data->{report} = $report;
84
85     $self->finish( $data );
86 }
87
88 sub enqueue {
89     my ( $self, $args) = @_;
90
91     # TODO Raise exception instead
92     return unless exists $args->{record_ids};
93
94     my @record_ids = @{ $args->{record_ids} };
95
96     $self->SUPER::enqueue({
97         job_size  => scalar @record_ids,
98         job_args  => {record_ids => \@record_ids,},
99         job_queue => 'long_tasks',
100     });
101 }
102
103 1;