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