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