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