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