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