bug 2157: add ability to 'clean' staged record batches
[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
28 # Koha modules used
29 use C4::Context;
30 use C4::Auth;
31 use C4::Output;
32 use C4::Biblio;
33 use C4::ImportBatch;
34 use C4::Matcher;
35 use C4::BackgroundJob;
36 use C4::Labels qw(add_batch);  
37
38 my $script_name = "/cgi-bin/koha/tools/manage-marc-import.pl";
39
40 my $input = new CGI;
41 my $op = $input->param('op') || '';
42 my $completedJobID = $input->param('completedJobID');
43 my $runinbackground = $input->param('runinbackground');
44 my $import_batch_id = $input->param('import_batch_id') || '';
45
46 # record list displays
47 my $offset = $input->param('offset') || 0;
48 my $results_per_page = $input->param('results_per_page') || 25; 
49
50 my ($template, $loggedinuser, $cookie)
51     = get_template_and_user({template_name => "tools/manage-marc-import.tmpl",
52                  query => $input,
53                  type => "intranet",
54                  authnotrequired => 0,
55                  flagsrequired => {tools => 'manage_staged_marc'},
56                  debug => 1,
57                  });
58
59 my %cookies = parse CGI::Cookie($cookie);
60 my $sessionID = $cookies{'CGISESSID'}->value;
61 my $dbh = C4::Context->dbh;
62
63 if ($op eq "create_labels") {
64         #create a batch of labels, then lose $op & $import_batch_id so we get back to import batch list.
65         my $label_batch_id = create_labelbatch_from_importbatch($import_batch_id);
66         $template->param( label_batch => $label_batch_id );
67         $op='';
68         $import_batch_id='';
69 }
70 if ($op) {
71     $template->param(script_name => $script_name, $op => 1);
72 } else {
73     $template->param(script_name => $script_name);
74 }
75
76 if ($op eq "") {
77     # displaying a list
78     if ($import_batch_id eq '') {
79         import_batches_list($template, $offset, $results_per_page);
80     } else {
81         import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
82     }
83 } elsif ($op eq "commit-batch") {
84     if ($completedJobID) {
85         add_saved_job_results_to_template($template, $completedJobID);
86     } else {
87         commit_batch($template, $import_batch_id);
88     }
89     import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
90 } elsif ($op eq "revert-batch") {
91     if ($completedJobID) {
92         add_saved_job_results_to_template($template, $completedJobID);
93     } else {
94         revert_batch($template, $import_batch_id);
95     }
96     import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
97 } elsif ($op eq "clean-batch") {
98     CleanBatch($import_batch_id);
99     import_batches_list($template, $offset, $results_per_page);
100     $template->param( 
101         did_clean       => 1,
102         import_batch_id => $import_batch_id,
103     );
104 } elsif ($op eq "redo-matching") {
105     my $new_matcher_id = $input->param('new_matcher_id');
106     my $current_matcher_id = $input->param('current_matcher_id');
107     my $overlay_action = $input->param('overlay_action');
108     my $nomatch_action = $input->param('nomatch_action');
109     my $item_action = $input->param('item_action');
110     redo_matching($template, $import_batch_id, $new_matcher_id, $current_matcher_id, 
111                   $overlay_action, $nomatch_action, $item_action);
112     import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
113
114
115 output_html_with_http_headers $input, $cookie, $template->output;
116
117 exit 0;
118
119 sub redo_matching {
120     my ($template, $import_batch_id, $new_matcher_id, $current_matcher_id, $overlay_action, $nomatch_action, $item_action) = @_;
121     my $rematch_failed = 0;
122     return if not defined $new_matcher_id and not defined $current_matcher_id;
123     my $old_overlay_action = GetImportBatchOverlayAction($import_batch_id);
124     my $old_nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
125     my $old_item_action = GetImportBatchItemAction($import_batch_id);
126     return if $new_matcher_id eq $current_matcher_id and 
127               $old_overlay_action eq $overlay_action and 
128               $old_nomatch_action eq $nomatch_action and 
129               $old_item_action eq $item_action;
130  
131     if ($old_overlay_action ne $overlay_action) {
132         SetImportBatchOverlayAction($import_batch_id, $overlay_action);
133         $template->param('changed_overlay_action' => 1);
134     }
135     if ($old_nomatch_action ne $nomatch_action) {
136         SetImportBatchNoMatchAction($import_batch_id, $nomatch_action);
137         $template->param('changed_nomatch_action' => 1);
138     }
139     if ($old_item_action ne $item_action) {
140         SetImportBatchItemAction($import_batch_id, $item_action);
141         $template->param('changed_item_action' => 1);
142     }
143
144     if ($new_matcher_id eq $current_matcher_id) {
145         return;
146     } 
147
148     my $num_with_matches = 0;
149     if (defined $new_matcher_id and $new_matcher_id ne "") {
150         my $matcher = C4::Matcher->fetch($new_matcher_id);
151         if (defined $matcher) {
152             $num_with_matches = BatchFindBibDuplicates($import_batch_id, $matcher);
153             SetImportBatchMatcher($import_batch_id, $new_matcher_id);
154         } else {
155             $rematch_failed = 1;
156         }
157     } else {
158         $num_with_matches = BatchFindBibDuplicates($import_batch_id, undef);
159         SetImportBatchMatcher($import_batch_id, undef);
160         SetImportBatchOverlayAction('create_new');
161     }
162     $template->param(rematch_failed => $rematch_failed);
163     $template->param(rematch_attempted => 1);
164     $template->param(num_with_matches => $num_with_matches);
165 }
166
167 sub create_labelbatch_from_importbatch {
168         my ($batch_id) = @_;
169         my @items = GetItemNumbersFromImportBatch($batch_id);
170         my $labelbatch = add_batch('labels',\@items);
171         return $labelbatch; 
172 }
173
174 sub import_batches_list {
175     my ($template, $offset, $results_per_page) = @_;
176     my $batches = GetImportBatchRangeDesc($offset, $results_per_page);
177
178     my @list = ();
179     foreach my $batch (@$batches) {
180         push @list, {
181             import_batch_id => $batch->{'import_batch_id'},
182             num_biblios => $batch->{'num_biblios'},
183             num_items => $batch->{'num_items'},
184             upload_timestamp => $batch->{'upload_timestamp'},
185             import_status => $batch->{'import_status'},
186             file_name => $batch->{'file_name'},
187             comments => $batch->{'comments'},
188             can_clean => ($batch->{'import_status'} ne 'cleaned') ? 1 : 0,
189         };
190     }
191     $template->param(batch_list => \@list); 
192     my $num_batches = GetNumberOfNonZ3950ImportBatches();
193     add_page_numbers($template, $offset, $results_per_page, $num_batches);
194     $template->param(offset => $offset);
195     $template->param(range_top => $offset + $results_per_page - 1);
196     $template->param(num_results => $num_batches);
197     $template->param(results_per_page => $results_per_page);
198
199 }
200
201 sub commit_batch {
202     my ($template, $import_batch_id) = @_;
203
204     my $job = undef;
205     $dbh->{AutoCommit} = 0;
206     my $callback = sub {};
207     if ($runinbackground) {
208         $job = put_in_background($import_batch_id);
209         $callback = progress_callback($job, $dbh);
210     }
211     my ($num_added, $num_updated, $num_items_added, $num_items_errored, $num_ignored) = 
212         BatchCommitBibRecords($import_batch_id, 50, $callback);
213     $dbh->commit();
214
215     my $results = {
216         did_commit => 1,
217         num_added => $num_added,
218         num_updated => $num_updated,
219         num_items_added => $num_items_added,
220         num_items_errored => $num_items_errored,
221         num_ignored => $num_ignored
222     };
223     if ($runinbackground) {
224         $job->finish($results);
225     } else {
226         add_results_to_template($template, $results);
227     }
228 }
229
230 sub revert_batch {
231     my ($template, $import_batch_id) = @_;
232
233     $dbh->{AutoCommit} = 0;
234     my $job = undef;
235     my $callback = sub {};
236     if ($runinbackground) {
237         $job = put_in_background($import_batch_id);
238         $callback = progress_callback($job, $dbh);
239     }
240     my ($num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored) = 
241         BatchRevertBibRecords($import_batch_id, 50, $callback);
242     $dbh->commit();
243
244     my $results = {
245         did_revert => 1,
246         num_deleted => $num_deleted,
247         num_items_deleted => $num_items_deleted,
248         num_errors => $num_errors,
249         num_reverted => $num_reverted,
250         num_ignored => $num_ignored,
251     };
252     if ($runinbackground) {
253         $job->finish($results);
254     } else {
255         add_results_to_template($template, $results);
256     }
257 }
258
259 sub put_in_background {
260     my $import_batch_id = shift;
261
262     my $batch = GetImportBatch($import_batch_id);
263     my $job = C4::BackgroundJob->new($sessionID, $batch->{'file_name'}, $ENV{'SCRIPT_NAME'}, $batch->{'num_biblios'});
264     my $jobID = $job->id();
265
266     # fork off
267     if (my $pid = fork) {
268         # parent
269         # return job ID as JSON
270
271         # prevent parent exiting from
272         # destroying the kid's database handle
273         # FIXME: according to DBI doc, this may not work for Oracle
274         $dbh->{InactiveDestroy}  = 1;
275
276         my $reply = CGI->new("");
277         print $reply->header(-type => 'text/html');
278         print "{ jobID: '$jobID' }";
279         exit 0;
280     } elsif (defined $pid) {
281         # child
282         # close STDOUT to signal to Apache that
283         # we're now running in the background
284         close STDOUT;
285         close STDERR;
286     } else {
287         # fork failed, so exit immediately
288         warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
289         exit 0;
290     }
291     return $job;
292 }
293
294 sub progress_callback {
295     my $job = shift;
296     my $dbh = shift;
297     return sub {
298         my $progress = shift;
299         $job->progress($progress);
300         $dbh->commit();
301     }
302 }
303
304 sub add_results_to_template {
305     my $template = shift;
306     my $results = shift;
307     $template->param(map { $_ => $results->{$_} } keys %{ $results });
308 }
309
310 sub add_saved_job_results_to_template {
311     my $template = shift;
312     my $completedJobID = shift;
313     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
314     my $results = $job->results();
315     add_results_to_template($template, $results);
316 }
317
318 sub import_biblios_list {
319     my ($template, $import_batch_id, $offset, $results_per_page) = @_;
320
321     my $batch = GetImportBatch($import_batch_id);
322     my $biblios = GetImportBibliosRange($import_batch_id, $offset, $results_per_page);
323     my @list = ();
324     foreach my $biblio (@$biblios) {
325         my $citation = $biblio->{'title'};
326         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
327         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
328         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
329         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
330         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
331         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
332
333         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
334         my $match_citation = '';
335         if ($#$match > -1) {
336             $match_citation .= $match->[0]->{'title'} if defined($match->[0]->{'title'});
337             $match_citation .= ' ' . $match->[0]->{'author'} if defined($match->[0]->{'author'});
338         }
339
340         push @list,
341           { import_record_id         => $biblio->{'import_record_id'},
342             final_match_biblionumber => $biblio->{'matched_biblionumber'},
343             citation                 => $citation,
344             status                   => $biblio->{'status'},
345             record_sequence          => $biblio->{'record_sequence'},
346             overlay_status           => $biblio->{'overlay_status'},
347             match_biblionumber       => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
348             match_citation           => $match_citation,
349             match_score              => $#$match > -1 ? $match->[0]->{'score'} : 0,
350           };
351     }
352     my $num_biblios = $batch->{'num_biblios'};
353     $template->param(biblio_list => \@list); 
354     add_page_numbers($template, $offset, $results_per_page, $num_biblios);
355     $template->param(offset => $offset);
356     $template->param(range_top => $offset + $results_per_page - 1);
357     $template->param(num_results => $num_biblios);
358     $template->param(results_per_page => $results_per_page);
359     $template->param(import_batch_id => $import_batch_id);
360     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
361     $template->param("overlay_action_${overlay_action}" => 1);
362     $template->param(overlay_action => $overlay_action);
363     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
364     $template->param("nomatch_action_${nomatch_action}" => 1);
365     $template->param(nomatch_action => $nomatch_action);
366     my $item_action = GetImportBatchItemAction($import_batch_id);
367     $template->param("item_action_${item_action}" => 1);
368     $template->param(item_action => $item_action);
369     batch_info($template, $batch);
370     
371 }
372
373 sub batch_info {
374     my ($template, $batch) = @_;
375     $template->param(batch_info => 1);
376     $template->param(file_name => $batch->{'file_name'});
377     $template->param(comments => $batch->{'comments'});
378     $template->param(import_status => $batch->{'import_status'});
379     $template->param(upload_timestamp => $batch->{'upload_timestamp'});
380     $template->param(num_biblios => $batch->{'num_biblios'});
381     $template->param(num_items => $batch->{'num_biblios'});
382     if ($batch->{'import_status'} ne 'cleaned') {
383         $template->param(can_clean => 1);
384     }
385     if ($batch->{'num_biblios'} > 0) {
386         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
387             $template->param(can_commit => 1);
388         }
389         if ($batch->{'import_status'} eq 'imported') {
390             $template->param(can_revert => 1);
391         }
392     }
393     if (defined $batch->{'matcher_id'}) {
394         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
395         if (defined $matcher) {
396             $template->param('current_matcher_id' => $batch->{'matcher_id'});
397             $template->param('current_matcher_code' => $matcher->code());
398             $template->param('current_matcher_description' => $matcher->description());
399         }
400     }
401     add_matcher_list($batch->{'matcher_id'});
402 }
403
404 sub add_matcher_list {
405     my $current_matcher_id = shift;
406     my @matchers = C4::Matcher::GetMatcherList();
407     if (defined $current_matcher_id) {
408         for (my $i = 0; $i <= $#matchers; $i++) {
409             if ($matchers[$i]->{'matcher_id'} eq $current_matcher_id) {
410                 $matchers[$i]->{'selected'} = 1;
411             }
412         }
413     }
414     $template->param(available_matchers => \@matchers);
415 }
416
417 sub add_page_numbers {
418     my ($template, $offset, $results_per_page, $total_results) = @_;
419     my $max_pages = POSIX::ceil($total_results / $results_per_page);
420     return if $max_pages < 2;
421     my $current_page = int($offset / $results_per_page) + 1;
422     my @pages = ();
423     for (my $i = 1; $i <= $max_pages; $i++) {
424         push @pages, {
425             page_number => $i,
426             current_page => ($current_page == $i) ? 1 : 0,
427             offset => ($i - 1) * $results_per_page
428         }
429     }
430     $template->param(pages => \@pages);
431 }
432