Bug 24995: (QA follow-up) Terminology: Use checkin and checkout
[koha.git] / tools / manage-marc-import.pl
blob6f9405d281e92680bf21747eb2f12d06430b7050
1 #!/usr/bin/perl
3 # Copyright (C) 2007 LibLime
5 # This file is part of Koha.
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.
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.
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>.
20 use Modern::Perl;
22 # standard or CPAN modules used
23 use CGI qw ( -utf8 );
24 use CGI::Cookie;
25 use MARC::File::USMARC;
27 # Koha modules used
28 use C4::Context;
29 use C4::Koha;
30 use C4::Auth;
31 use C4::AuthoritiesMarc;
32 use C4::Output;
33 use C4::Biblio;
34 use C4::ImportBatch;
35 use C4::Matcher;
36 use C4::BackgroundJob;
37 use C4::Labels::Batch;
38 use Koha::BiblioFrameworks;
40 my $script_name = "/cgi-bin/koha/tools/manage-marc-import.pl";
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') || '';
48 # record list displays
49 my $offset = $input->param('offset') || 0;
50 my $results_per_page = $input->param('results_per_page') || 25;
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 });
61 my %cookies = parse CGI::Cookie($cookie);
62 our $sessionID = $cookies{'CGISESSID'}->value;
63 our $dbh = C4::Context->dbh;
65 my $frameworks = Koha::BiblioFrameworks->search({ tagfield => { 'not' => undef } }, { join => 'marc_tag_structure', distinct => 'frameworkcode', order_by => ['frameworktext'] });
66 $template->param( frameworks => $frameworks );
68 if ($op eq "create_labels") {
69 #create a batch of labels, then lose $op & $import_batch_id so we get back to import batch list.
70 my $label_batch_id = create_labelbatch_from_importbatch($import_batch_id);
71 if ($label_batch_id == -1) {
72 $template->param( label_batch_msg => "error",
73 message_type => 'alert',
76 else {
77 $template->param( label_batch_msg => $label_batch_id,
78 message_type => 'dialog',
81 $op='';
82 $import_batch_id='';
84 if ($op) {
85 $template->param(script_name => $script_name, $op => 1);
86 } else {
87 $template->param(script_name => $script_name);
90 if ($op eq "") {
91 # displaying a list
92 if ($import_batch_id eq '') {
93 import_batches_list($template, $offset, $results_per_page);
94 } else {
95 import_records_list($template, $import_batch_id, $offset, $results_per_page);
97 } elsif ($op eq "commit-batch") {
98 if ($completedJobID) {
99 add_saved_job_results_to_template($template, $completedJobID);
100 } else {
101 my $framework = $input->param('framework');
102 commit_batch($template, $import_batch_id, $framework);
104 import_records_list($template, $import_batch_id, $offset, $results_per_page);
105 } elsif ($op eq "revert-batch") {
106 if ($completedJobID) {
107 add_saved_job_results_to_template($template, $completedJobID);
108 } else {
109 revert_batch($template, $import_batch_id);
111 import_records_list($template, $import_batch_id, $offset, $results_per_page);
112 } elsif ($op eq "clean-batch") {
113 CleanBatch($import_batch_id);
114 import_batches_list($template, $offset, $results_per_page);
115 $template->param(
116 did_clean => 1,
117 import_batch_id => $import_batch_id,
119 } elsif ($op eq "delete-batch") {
120 DeleteBatch($import_batch_id);
121 import_batches_list($template, $offset, $results_per_page);
122 $template->param(
123 did_delete => 1,
125 } elsif ($op eq "redo-matching") {
126 my $new_matcher_id = $input->param('new_matcher_id');
127 my $current_matcher_id = $input->param('current_matcher_id');
128 my $overlay_action = $input->param('overlay_action');
129 my $nomatch_action = $input->param('nomatch_action');
130 my $item_action = $input->param('item_action');
131 redo_matching($template, $import_batch_id, $new_matcher_id, $current_matcher_id,
132 $overlay_action, $nomatch_action, $item_action);
133 import_records_list($template, $import_batch_id, $offset, $results_per_page);
136 output_html_with_http_headers $input, $cookie, $template->output;
138 exit 0;
140 sub redo_matching {
141 my ($template, $import_batch_id, $new_matcher_id, $current_matcher_id, $overlay_action, $nomatch_action, $item_action) = @_;
142 my $rematch_failed = 0;
143 return if not defined $new_matcher_id and not defined $current_matcher_id;
144 my $old_overlay_action = GetImportBatchOverlayAction($import_batch_id);
145 my $old_nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
146 my $old_item_action = GetImportBatchItemAction($import_batch_id);
147 return if $new_matcher_id eq $current_matcher_id and
148 $old_overlay_action eq $overlay_action and
149 $old_nomatch_action eq $nomatch_action and
150 $old_item_action eq $item_action;
152 if ($old_overlay_action ne $overlay_action) {
153 SetImportBatchOverlayAction($import_batch_id, $overlay_action);
154 $template->param('changed_overlay_action' => 1);
156 if ($old_nomatch_action ne $nomatch_action) {
157 SetImportBatchNoMatchAction($import_batch_id, $nomatch_action);
158 $template->param('changed_nomatch_action' => 1);
160 if ($old_item_action ne $item_action) {
161 SetImportBatchItemAction($import_batch_id, $item_action);
162 $template->param('changed_item_action' => 1);
165 my $num_with_matches = 0;
166 if (defined $new_matcher_id and $new_matcher_id ne "") {
167 my $matcher = C4::Matcher->fetch($new_matcher_id);
168 if (defined $matcher) {
169 $num_with_matches = BatchFindDuplicates($import_batch_id, $matcher);
170 SetImportBatchMatcher($import_batch_id, $new_matcher_id);
171 } else {
172 $rematch_failed = 1;
174 } else {
175 $num_with_matches = BatchFindDuplicates($import_batch_id, undef);
176 SetImportBatchMatcher($import_batch_id, undef);
177 SetImportBatchOverlayAction('create_new');
179 $template->param(rematch_failed => $rematch_failed);
180 $template->param(rematch_attempted => 1);
181 $template->param(num_with_matches => $num_with_matches);
184 sub create_labelbatch_from_importbatch {
185 my ($batch_id) = @_;
186 my $err = undef;
187 my $branch_code = C4::Context->userenv->{'branch'};
188 my $batch = C4::Labels::Batch->new(branch_code => $branch_code);
189 my @items = GetItemNumbersFromImportBatch($batch_id);
190 if (grep{$_ == 0} @items) {
191 warn sprintf('create_labelbatch_from_importbatch() : Call to C4::ImportBatch::GetItemNumbersFromImportBatch returned no item number(s) from import batch #%s.', $batch_id);
192 return -1;
194 foreach my $item_number (@items) {
195 $err = $batch->add_item($item_number);
196 if ($err == -1) {
197 warn sprintf('create_labelbatch_from_importbatch() : Error attempting to add item #%s of import batch #%s to label batch.', $item_number, $batch_id);
198 return -1;
201 return $batch->get_attr('batch_id');
204 sub import_batches_list {
205 my ($template, $offset, $results_per_page) = @_;
206 my $batches = GetImportBatchRangeDesc($offset, $results_per_page);
208 my @list = ();
209 foreach my $batch (@$batches) {
210 push @list, {
211 import_batch_id => $batch->{'import_batch_id'},
212 num_records => $batch->{'num_records'},
213 num_items => $batch->{'num_items'},
214 upload_timestamp => $batch->{'upload_timestamp'},
215 import_status => $batch->{'import_status'},
216 file_name => $batch->{'file_name'} || "($batch->{'batch_type'})",
217 comments => $batch->{'comments'},
218 can_clean => ($batch->{'import_status'} ne 'cleaned') ? 1 : 0,
219 record_type => $batch->{'record_type'},
222 $template->param(batch_list => \@list);
223 my $num_batches = GetNumberOfNonZ3950ImportBatches();
224 add_page_numbers($template, $offset, $results_per_page, $num_batches);
225 $template->param(offset => $offset);
226 $template->param(range_top => $offset + $results_per_page - 1);
227 $template->param(num_results => $num_batches);
228 $template->param(results_per_page => $results_per_page);
232 sub commit_batch {
233 my ($template, $import_batch_id, $framework) = @_;
235 my $job = undef;
236 my ( $num_added, $num_updated, $num_items_added,
237 $num_items_replaced, $num_items_errored, $num_ignored );
238 my $schema = Koha::Database->new->schema;
239 $schema->storage->txn_do(
240 sub {
241 my $callback = sub { };
242 if ($runinbackground) {
243 $job = put_in_background($import_batch_id);
244 $callback = progress_callback( $job, $dbh );
247 $num_added, $num_updated, $num_items_added,
248 $num_items_replaced, $num_items_errored, $num_ignored
250 = BatchCommitRecords( $import_batch_id, $framework, 50,
251 $callback );
255 my $results = {
256 did_commit => 1,
257 num_added => $num_added,
258 num_updated => $num_updated,
259 num_items_added => $num_items_added,
260 num_items_replaced => $num_items_replaced,
261 num_items_errored => $num_items_errored,
262 num_ignored => $num_ignored
264 if ($runinbackground) {
265 $job->finish($results);
266 } else {
267 add_results_to_template($template, $results);
271 sub revert_batch {
272 my ($template, $import_batch_id) = @_;
274 my $job = undef;
275 my (
276 $num_deleted, $num_errors, $num_reverted,
277 $num_items_deleted, $num_ignored
279 my $schema = Koha::Database->new->schema;
280 $schema->txn_do(
281 sub {
282 my $callback = sub { };
283 if ($runinbackground) {
284 $job = put_in_background($import_batch_id);
285 $callback = progress_callback( $job, $dbh );
288 $num_deleted, $num_errors, $num_reverted,
289 $num_items_deleted, $num_ignored
290 ) = BatchRevertRecords( $import_batch_id, 50, $callback );
294 my $results = {
295 did_revert => 1,
296 num_deleted => $num_deleted,
297 num_items_deleted => $num_items_deleted,
298 num_errors => $num_errors,
299 num_reverted => $num_reverted,
300 num_ignored => $num_ignored,
302 if ($runinbackground) {
303 $job->finish($results);
304 } else {
305 add_results_to_template($template, $results);
309 sub put_in_background {
310 my $import_batch_id = shift;
312 my $batch = GetImportBatch($import_batch_id);
313 my $job = C4::BackgroundJob->new($sessionID, $batch->{'file_name'}, '/cgi-bin/koha/tools/manage-marc-import.pl', $batch->{'num_records'});
314 my $jobID = $job->id();
316 # fork off
317 if (my $pid = fork) {
318 # parent
319 # return job ID as JSON
321 # prevent parent exiting from
322 # destroying the kid's database handle
323 # FIXME: according to DBI doc, this may not work for Oracle
324 $dbh->{InactiveDestroy} = 1;
326 my $reply = CGI->new("");
327 print $reply->header(-type => 'text/html');
328 print '{"jobID":"' . $jobID . '"}';
329 exit 0;
330 } elsif (defined $pid) {
331 # child
332 # close STDOUT to signal to Apache that
333 # we're now running in the background
334 close STDOUT;
335 close STDERR;
336 } else {
337 # fork failed, so exit immediately
338 warn "fork failed while attempting to run tools/manage-marc-import.pl as a background job";
339 exit 0;
341 return $job;
344 sub progress_callback {
345 my $job = shift;
346 my $dbh = shift;
347 return sub {
348 my $progress = shift;
349 $job->progress($progress);
350 $dbh->commit();
354 sub add_results_to_template {
355 my $template = shift;
356 my $results = shift;
357 $template->param(map { $_ => $results->{$_} } keys %{ $results });
360 sub add_saved_job_results_to_template {
361 my $template = shift;
362 my $completedJobID = shift;
363 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
364 my $results = $job->results();
365 add_results_to_template($template, $results);
368 sub import_records_list {
369 my ($template, $import_batch_id, $offset, $results_per_page) = @_;
371 my $batch = GetImportBatch($import_batch_id);
372 $template->param(import_batch_id => $import_batch_id);
374 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
375 $template->param("overlay_action_${overlay_action}" => 1);
376 $template->param(overlay_action => $overlay_action);
378 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
379 $template->param("nomatch_action_${nomatch_action}" => 1);
380 $template->param(nomatch_action => $nomatch_action);
382 my $item_action = GetImportBatchItemAction($import_batch_id);
383 $template->param("item_action_${item_action}" => 1);
384 $template->param(item_action => $item_action);
386 batch_info($template, $batch);
390 sub batch_info {
391 my ($template, $batch) = @_;
392 $template->param(batch_info => 1);
393 $template->param(file_name => $batch->{'file_name'});
394 $template->param(comments => $batch->{'comments'});
395 $template->param(import_status => $batch->{'import_status'});
396 $template->param(upload_timestamp => $batch->{'upload_timestamp'});
397 $template->{VARS}->{'record_type'} = $batch->{'record_type'};
398 $template->param(num_records => $batch->{'num_records'});
399 $template->param(num_items => $batch->{'num_items'});
400 if ($batch->{'import_status'} ne 'cleaned') {
401 $template->param(can_clean => 1);
403 if ($batch->{'num_records'} > 0) {
404 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
405 $template->param(can_commit => 1);
407 if ($batch->{'import_status'} eq 'imported') {
408 $template->param(can_revert => 1);
411 if (defined $batch->{'matcher_id'}) {
412 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
413 if (defined $matcher) {
414 $template->param('current_matcher_id' => $batch->{'matcher_id'});
415 $template->param('current_matcher_code' => $matcher->code());
416 $template->param('current_matcher_description' => $matcher->description());
419 add_matcher_list($template,$batch->{'matcher_id'});
422 sub add_matcher_list {
423 my ($template,$current_matcher_id) = @_;
424 my @matchers = C4::Matcher::GetMatcherList();
425 if (defined $current_matcher_id) {
426 for (my $i = 0; $i <= $#matchers; $i++) {
427 if ($matchers[$i]->{'matcher_id'} eq $current_matcher_id) {
428 $matchers[$i]->{'selected'} = 1;
432 $template->param(available_matchers => \@matchers);
435 sub add_page_numbers {
436 my ($template, $offset, $results_per_page, $total_results) = @_;
437 my $max_pages = POSIX::ceil($total_results / $results_per_page);
438 return if $max_pages < 2;
439 my $current_page = int($offset / $results_per_page) + 1;
440 my @pages = ();
441 for (my $i = 1; $i <= $max_pages; $i++) {
442 push @pages, {
443 page_number => $i,
444 current_page => ($current_page == $i) ? 1 : 0,
445 offset => ($i - 1) * $results_per_page
448 $template->param(pages => \@pages);