Update release notes for 19.05.17 release
[koha.git] / tools / manage-marc-import.pl
1 #!/usr/bin/perl
2
3 # Copyright (C) 2007 LibLime
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 # standard or CPAN modules used
23 use CGI qw ( -utf8 );
24 use CGI::Cookie;
25 use MARC::File::USMARC;
26
27 # Koha modules used
28 use C4::Context;
29 use C4::Koha;
30 use C4::Auth;
31 use C4::AuthoritiesMarc;
32 use C4::Output;
33 use C4::Biblio;
34 use C4::ImportBatch;
35 use C4::Matcher;
36 use C4::BackgroundJob;
37 use C4::Labels::Batch;
38 use Koha::BiblioFrameworks;
39
40 my $script_name = "/cgi-bin/koha/tools/manage-marc-import.pl";
41
42 my $input = new CGI;
43 my $op = $input->param('op') || '';
44 my $completedJobID = $input->param('completedJobID');
45 our $runinbackground = $input->param('runinbackground');
46 my $import_batch_id = $input->param('import_batch_id') || '';
47
48 # record list displays
49 my $offset = $input->param('offset') || 0;
50 my $results_per_page = $input->param('results_per_page') || 25; 
51
52 my ($template, $loggedinuser, $cookie)
53     = get_template_and_user({template_name => "tools/manage-marc-import.tt",
54                  query => $input,
55                  type => "intranet",
56                  flagsrequired => {tools => 'manage_staged_marc'},
57                  debug => 1,
58                  });
59
60 my %cookies = parse CGI::Cookie($cookie);
61 our $sessionID = $cookies{'CGISESSID'}->value;
62 our $dbh = C4::Context->dbh;
63
64 my $frameworks = Koha::BiblioFrameworks->search({ tagfield => { 'not' => undef } }, { join => 'marc_tag_structure', distinct => 'frameworkcode', order_by => ['frameworktext'] });
65 $template->param( frameworks => $frameworks );
66
67 if ($op eq "create_labels") {
68         #create a batch of labels, then lose $op & $import_batch_id so we get back to import batch list.
69         my $label_batch_id = create_labelbatch_from_importbatch($import_batch_id);
70         if ($label_batch_id == -1) {
71             $template->param(   label_batch_msg => "Error attempting to create label batch. Please ask your system administrator to check the log for more details.",
72                                 message_type    => 'alert',
73             );
74         }
75         else {
76             $template->param(   label_batch_msg => "Label batch #$label_batch_id created.",
77                                 message_type    => 'dialog',
78             );
79         }
80         $op='';
81         $import_batch_id='';
82 }
83 if ($op) {
84     $template->param(script_name => $script_name, $op => 1);
85 } else {
86     $template->param(script_name => $script_name);
87 }
88
89 if ($op eq "") {
90     # displaying a list
91     if ($import_batch_id eq '') {
92         import_batches_list($template, $offset, $results_per_page);
93     } else {
94         import_records_list($template, $import_batch_id, $offset, $results_per_page);
95     }
96 } elsif ($op eq "commit-batch") {
97     if ($completedJobID) {
98         add_saved_job_results_to_template($template, $completedJobID);
99     } else {
100         my $framework = $input->param('framework');
101         commit_batch($template, $import_batch_id, $framework);
102     }
103     import_records_list($template, $import_batch_id, $offset, $results_per_page);
104 } elsif ($op eq "revert-batch") {
105     if ($completedJobID) {
106         add_saved_job_results_to_template($template, $completedJobID);
107     } else {
108         revert_batch($template, $import_batch_id);
109     }
110     import_records_list($template, $import_batch_id, $offset, $results_per_page);
111 } elsif ($op eq "clean-batch") {
112     CleanBatch($import_batch_id);
113     import_batches_list($template, $offset, $results_per_page);
114     $template->param( 
115         did_clean       => 1,
116         import_batch_id => $import_batch_id,
117     );
118 } elsif ($op eq "delete-batch") {
119     DeleteBatch($import_batch_id);
120     import_batches_list($template, $offset, $results_per_page);
121     $template->param(
122         did_delete      => 1,
123     );
124 } elsif ($op eq "redo-matching") {
125     my $new_matcher_id = $input->param('new_matcher_id');
126     my $current_matcher_id = $input->param('current_matcher_id');
127     my $overlay_action = $input->param('overlay_action');
128     my $nomatch_action = $input->param('nomatch_action');
129     my $item_action = $input->param('item_action');
130     redo_matching($template, $import_batch_id, $new_matcher_id, $current_matcher_id, 
131                   $overlay_action, $nomatch_action, $item_action);
132     import_records_list($template, $import_batch_id, $offset, $results_per_page);
133
134
135 output_html_with_http_headers $input, $cookie, $template->output;
136
137 exit 0;
138
139 sub redo_matching {
140     my ($template, $import_batch_id, $new_matcher_id, $current_matcher_id, $overlay_action, $nomatch_action, $item_action) = @_;
141     my $rematch_failed = 0;
142     return if not defined $new_matcher_id and not defined $current_matcher_id;
143     my $old_overlay_action = GetImportBatchOverlayAction($import_batch_id);
144     my $old_nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
145     my $old_item_action = GetImportBatchItemAction($import_batch_id);
146     return if $new_matcher_id eq $current_matcher_id and 
147               $old_overlay_action eq $overlay_action and 
148               $old_nomatch_action eq $nomatch_action and 
149               $old_item_action eq $item_action;
150  
151     if ($old_overlay_action ne $overlay_action) {
152         SetImportBatchOverlayAction($import_batch_id, $overlay_action);
153         $template->param('changed_overlay_action' => 1);
154     }
155     if ($old_nomatch_action ne $nomatch_action) {
156         SetImportBatchNoMatchAction($import_batch_id, $nomatch_action);
157         $template->param('changed_nomatch_action' => 1);
158     }
159     if ($old_item_action ne $item_action) {
160         SetImportBatchItemAction($import_batch_id, $item_action);
161         $template->param('changed_item_action' => 1);
162     }
163
164     my $num_with_matches = 0;
165     if (defined $new_matcher_id and $new_matcher_id ne "") {
166         my $matcher = C4::Matcher->fetch($new_matcher_id);
167         if (defined $matcher) {
168             $num_with_matches = BatchFindDuplicates($import_batch_id, $matcher);
169             SetImportBatchMatcher($import_batch_id, $new_matcher_id);
170         } else {
171             $rematch_failed = 1;
172         }
173     } else {
174         $num_with_matches = BatchFindDuplicates($import_batch_id, undef);
175         SetImportBatchMatcher($import_batch_id, undef);
176         SetImportBatchOverlayAction('create_new');
177     }
178     $template->param(rematch_failed => $rematch_failed);
179     $template->param(rematch_attempted => 1);
180     $template->param(num_with_matches => $num_with_matches);
181 }
182
183 sub create_labelbatch_from_importbatch {
184         my ($batch_id) = @_;
185         my $err = undef;
186         my $branch_code = C4::Context->userenv->{'branch'};
187         my $batch = C4::Labels::Batch->new(branch_code => $branch_code);
188         my @items = GetItemNumbersFromImportBatch($batch_id);
189         if (grep{$_ == 0} @items) {
190             warn sprintf('create_labelbatch_from_importbatch() : Call to C4::ImportBatch::GetItemNumbersFromImportBatch returned no item number(s) from import batch #%s.', $batch_id);
191             return -1;
192         }
193         foreach my $item_number (@items) {
194             $err = $batch->add_item($item_number);
195             if ($err == -1) {
196                 warn sprintf('create_labelbatch_from_importbatch() : Error attempting to add item #%s of import batch #%s to label batch.', $item_number, $batch_id);
197                 return -1;
198             }
199         }
200         return $batch->get_attr('batch_id');
201 }
202
203 sub import_batches_list {
204     my ($template, $offset, $results_per_page) = @_;
205     my $batches = GetImportBatchRangeDesc($offset, $results_per_page);
206
207     my @list = ();
208     foreach my $batch (@$batches) {
209         push @list, {
210             import_batch_id => $batch->{'import_batch_id'},
211             num_records => $batch->{'num_records'},
212             num_items => $batch->{'num_items'},
213             upload_timestamp => $batch->{'upload_timestamp'},
214             import_status => $batch->{'import_status'},
215             file_name => $batch->{'file_name'} || "($batch->{'batch_type'})",
216             comments => $batch->{'comments'},
217             can_clean => ($batch->{'import_status'} ne 'cleaned') ? 1 : 0,
218             record_type => $batch->{'record_type'},
219         };
220     }
221     $template->param(batch_list => \@list); 
222     my $num_batches = GetNumberOfNonZ3950ImportBatches();
223     add_page_numbers($template, $offset, $results_per_page, $num_batches);
224     $template->param(offset => $offset);
225     $template->param(range_top => $offset + $results_per_page - 1);
226     $template->param(num_results => $num_batches);
227     $template->param(results_per_page => $results_per_page);
228
229 }
230
231 sub commit_batch {
232     my ($template, $import_batch_id, $framework) = @_;
233
234     my $job = undef;
235     my ( $num_added, $num_updated, $num_items_added,
236         $num_items_replaced, $num_items_errored, $num_ignored );
237     my $schema = Koha::Database->new->schema;
238     $schema->storage->txn_do(
239         sub {
240             my $callback = sub { };
241             if ($runinbackground) {
242                 $job = put_in_background($import_batch_id);
243                 $callback = progress_callback( $job, $dbh );
244             }
245             (
246                 $num_added, $num_updated, $num_items_added,
247                 $num_items_replaced, $num_items_errored, $num_ignored
248               )
249               = BatchCommitRecords( $import_batch_id, $framework, 50,
250                 $callback );
251         }
252     );
253
254     my $results = {
255         did_commit => 1,
256         num_added => $num_added,
257         num_updated => $num_updated,
258         num_items_added => $num_items_added,
259         num_items_replaced => $num_items_replaced,
260         num_items_errored => $num_items_errored,
261         num_ignored => $num_ignored
262     };
263     if ($runinbackground) {
264         $job->finish($results);
265     } else {
266         add_results_to_template($template, $results);
267     }
268 }
269
270 sub revert_batch {
271     my ($template, $import_batch_id) = @_;
272
273     my $job = undef;
274             my (
275                 $num_deleted,       $num_errors, $num_reverted,
276                 $num_items_deleted, $num_ignored
277             );
278     my $schema = Koha::Database->new->schema;
279     $schema->txn_do(
280         sub {
281             my $callback = sub { };
282             if ($runinbackground) {
283                 $job = put_in_background($import_batch_id);
284                 $callback = progress_callback( $job, $dbh );
285             }
286             (
287                 $num_deleted,       $num_errors, $num_reverted,
288                 $num_items_deleted, $num_ignored
289             ) = BatchRevertRecords( $import_batch_id, 50, $callback );
290         }
291     );
292
293     my $results = {
294         did_revert => 1,
295         num_deleted => $num_deleted,
296         num_items_deleted => $num_items_deleted,
297         num_errors => $num_errors,
298         num_reverted => $num_reverted,
299         num_ignored => $num_ignored,
300     };
301     if ($runinbackground) {
302         $job->finish($results);
303     } else {
304         add_results_to_template($template, $results);
305     }
306 }
307
308 sub put_in_background {
309     my $import_batch_id = shift;
310
311     my $batch = GetImportBatch($import_batch_id);
312     my $job = C4::BackgroundJob->new($sessionID, $batch->{'file_name'}, '/cgi-bin/koha/tools/manage-marc-import.pl', $batch->{'num_records'});
313     my $jobID = $job->id();
314
315     # fork off
316     if (my $pid = fork) {
317         # parent
318         # return job ID as JSON
319
320         # prevent parent exiting from
321         # destroying the kid's database handle
322         # FIXME: according to DBI doc, this may not work for Oracle
323         $dbh->{InactiveDestroy}  = 1;
324
325         my $reply = CGI->new("");
326         print $reply->header(-type => 'text/html');
327         print '{"jobID":"' . $jobID . '"}';
328         exit 0;
329     } elsif (defined $pid) {
330         # child
331         # close STDOUT to signal to Apache that
332         # we're now running in the background
333         close STDOUT;
334         close STDERR;
335     } else {
336         # fork failed, so exit immediately
337         warn "fork failed while attempting to run tools/manage-marc-import.pl as a background job";
338         exit 0;
339     }
340     return $job;
341 }
342
343 sub progress_callback {
344     my $job = shift;
345     my $dbh = shift;
346     return sub {
347         my $progress = shift;
348         $job->progress($progress);
349         $dbh->commit();
350     }
351 }
352
353 sub add_results_to_template {
354     my $template = shift;
355     my $results = shift;
356     $template->param(map { $_ => $results->{$_} } keys %{ $results });
357 }
358
359 sub add_saved_job_results_to_template {
360     my $template = shift;
361     my $completedJobID = shift;
362     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
363     my $results = $job->results();
364     add_results_to_template($template, $results);
365 }
366
367 sub import_records_list {
368     my ($template, $import_batch_id, $offset, $results_per_page) = @_;
369
370     my $batch = GetImportBatch($import_batch_id);
371     $template->param(import_batch_id => $import_batch_id);
372
373     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
374     $template->param("overlay_action_${overlay_action}" => 1);
375     $template->param(overlay_action => $overlay_action);
376
377     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
378     $template->param("nomatch_action_${nomatch_action}" => 1);
379     $template->param(nomatch_action => $nomatch_action);
380
381     my $item_action = GetImportBatchItemAction($import_batch_id);
382     $template->param("item_action_${item_action}" => 1);
383     $template->param(item_action => $item_action);
384
385     batch_info($template, $batch);
386     
387 }
388
389 sub batch_info {
390     my ($template, $batch) = @_;
391     $template->param(batch_info => 1);
392     $template->param(file_name => $batch->{'file_name'});
393     $template->param(comments => $batch->{'comments'});
394     $template->param(import_status => $batch->{'import_status'});
395     $template->param(upload_timestamp => $batch->{'upload_timestamp'});
396     $template->{VARS}->{'record_type'} = $batch->{'record_type'};
397     $template->param(num_records => $batch->{'num_records'});
398     $template->param(num_items => $batch->{'num_items'});
399     if ($batch->{'import_status'} ne 'cleaned') {
400         $template->param(can_clean => 1);
401     }
402     if ($batch->{'num_records'} > 0) {
403         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
404             $template->param(can_commit => 1);
405         }
406         if ($batch->{'import_status'} eq 'imported') {
407             $template->param(can_revert => 1);
408         }
409     }
410     if (defined $batch->{'matcher_id'}) {
411         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
412         if (defined $matcher) {
413             $template->param('current_matcher_id' => $batch->{'matcher_id'});
414             $template->param('current_matcher_code' => $matcher->code());
415             $template->param('current_matcher_description' => $matcher->description());
416         }
417     }
418     add_matcher_list($template,$batch->{'matcher_id'});
419 }
420
421 sub add_matcher_list {
422     my ($template,$current_matcher_id) = @_;
423     my @matchers = C4::Matcher::GetMatcherList();
424     if (defined $current_matcher_id) {
425         for (my $i = 0; $i <= $#matchers; $i++) {
426             if ($matchers[$i]->{'matcher_id'} eq $current_matcher_id) {
427                 $matchers[$i]->{'selected'} = 1;
428             }
429         }
430     }
431     $template->param(available_matchers => \@matchers);
432 }
433
434 sub add_page_numbers {
435     my ($template, $offset, $results_per_page, $total_results) = @_;
436     my $max_pages = POSIX::ceil($total_results / $results_per_page);
437     return if $max_pages < 2;
438     my $current_page = int($offset / $results_per_page) + 1;
439     my @pages = ();
440     for (my $i = 1; $i <= $max_pages; $i++) {
441         push @pages, {
442             page_number => $i,
443             current_page => ($current_page == $i) ? 1 : 0,
444             offset => ($i - 1) * $results_per_page
445         }
446     }
447     $template->param(pages => \@pages);
448 }
449