Bug 22417: Fix the batch authority tool
[koha.git] / Koha / BackgroundJob / BatchUpdateAuthority.pm
blobed634d251dfc003aa02845dca2b6ad8c4bb4807d
1 package Koha::BackgroundJob::BatchUpdateAuthority;
3 use Modern::Perl;
4 use JSON qw( encode_json decode_json );
6 use C4::MarcModificationTemplates;
7 use C4::AuthoritiesMarc;
8 use Koha::BackgroundJobs;
9 use Koha::DateUtils qw( dt_from_string );
10 use Koha::MetadataRecord::Authority;
12 use base 'Koha::BackgroundJob';
14 sub job_type {
15 return 'batch_authority_record_modification';
18 sub process {
19 my ( $self, $args ) = @_;
21 my $job = Koha::BackgroundJobs->find( $args->{job_id} );
23 if ( !exists $args->{job_id} || !$job || $job->status eq 'cancelled' ) {
24 return;
27 my $job_progress = 0;
28 $job->started_on(dt_from_string)
29 ->progress($job_progress)
30 ->status('started')
31 ->store;
33 my $mmtid = $args->{mmtid};
34 my $record_type = $args->{record_type};
35 my @record_ids = @{ $args->{record_ids} };
37 my $report = {
38 total_records => scalar @record_ids,
39 total_success => 0,
41 my @messages;
42 my $dbh = C4::Context->dbh;
43 $dbh->{RaiseError} = 1;
44 RECORD_IDS: for my $record_id ( sort { $a <=> $b } @record_ids ) {
45 next unless $record_id;
46 # Authorities
47 my $authid = $record_id;
48 my $error = eval {
49 my $authority = Koha::MetadataRecord::Authority->get_from_authid( $authid );
50 my $record = $authority->record;
51 ModifyRecordWithTemplate( $mmtid, $record );
52 ModAuthority( $authid, $record, $authority->authtypecode );
54 if ( $error and $error != $authid or $@ ) {
55 push @messages, {
56 type => 'error',
57 code => 'authority_not_modified',
58 authid => $authid,
59 error => ($@ ? $@ : 0),
61 } else {
62 push @messages, {
63 type => 'success',
64 code => 'authority_modified',
65 authid => $authid,
67 $report->{total_success}++;
69 $job->progress( ++$job_progress )->store;
72 my $job_data = decode_json $job->data;
73 $job_data->{messages} = \@messages;
74 $job_data->{report} = $report;
76 $job->ended_on(dt_from_string)
77 ->data(encode_json $job_data);
78 $job->status('finished') if $job->status ne 'cancelled';
79 $job->store;
83 sub enqueue {
84 my ( $self, $args) = @_;
86 # TODO Raise exception instead
87 return unless exists $args->{mmtid};
88 return unless exists $args->{record_type}; #FIXME RMME
89 return unless exists $args->{record_ids};
91 my $mmtid = $args->{mmtid};
92 my $record_type = $args->{record_type};
93 my @record_ids = @{ $args->{record_ids} };
95 $self->SUPER::enqueue({
96 job_size => scalar @record_ids,
97 job_args => {mmtid => $mmtid, record_type => $record_type, record_ids => \@record_ids,}
98 });