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