Bug 15869: Change framework on overlay
[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 use Try::Tiny;
27
28 # Koha modules used
29 use C4::Context;
30 use C4::Koha;
31 use C4::Auth qw( get_template_and_user );
32 use C4::Output qw( output_html_with_http_headers );
33 use C4::ImportBatch qw( CleanBatch DeleteBatch GetImportBatch GetImportBatchOverlayAction GetImportBatchNoMatchAction GetImportBatchItemAction SetImportBatchOverlayAction SetImportBatchNoMatchAction SetImportBatchItemAction BatchFindDuplicates SetImportBatchMatcher GetItemNumbersFromImportBatch GetImportBatchRangeDesc GetNumberOfNonZ3950ImportBatches BatchCommitRecords BatchRevertRecords );
34 use C4::Matcher;
35 use C4::Labels::Batch;
36 use Koha::BiblioFrameworks;
37 use Koha::BackgroundJob::MARCImportCommitBatch;
38 use Koha::BackgroundJob::MARCImportRevertBatch;
39
40 use Koha::Logger;
41
42
43 my $input = CGI->new;
44 my $op = $input->param('op') || '';
45 my $import_batch_id = $input->param('import_batch_id') || '';
46 my @messages;
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 $frameworks = Koha::BiblioFrameworks->search({ tagfield => { 'not' => undef } }, { join => 'marc_tag_structure', distinct => 'frameworkcode', order_by => ['frameworktext'] });
60 $template->param( frameworks => $frameworks );
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         if ($label_batch_id == -1) {
66             $template->param(   label_batch_msg => "error",
67                                 message_type    => 'alert',
68             );
69         }
70         else {
71             $template->param(   label_batch_msg => $label_batch_id,
72                                 message_type    => 'dialog',
73             );
74         }
75         $op='';
76         $import_batch_id='';
77 }
78
79 if ($op) {
80     $template->param($op => 1);
81 }
82
83 if ($op eq "") {
84     # displaying a list
85     if ($import_batch_id eq '') {
86         import_batches_list($template, $offset, $results_per_page);
87     } else {
88         import_records_list($template, $import_batch_id, $offset, $results_per_page);
89     }
90 } elsif ($op eq "commit-batch") {
91     my $frameworkcode = $input->param('framework');
92     my $overlay_framework = $input->param('overlay_framework');
93     try {
94         my $job_id = Koha::BackgroundJob::MARCImportCommitBatch->new->enqueue(
95             {
96                 import_batch_id => $import_batch_id,
97                 frameworkcode   => $frameworkcode,
98                 overlay_framework => $overlay_framework
99             }
100         );
101         if ($job_id) {
102             $template->param(
103                 job_enqueued => 1,
104                 job_id => $job_id,
105             );
106         }
107     }
108     catch {
109         warn $_;
110         push @messages,
111           {
112             type  => 'error',
113             code  => 'cannot_enqueue_job',
114             error => $_,
115           };
116     };
117 } elsif ($op eq "revert-batch") {
118     try {
119         my $job_id = Koha::BackgroundJob::MARCImportRevertBatch->new->enqueue(
120             { import_batch_id => $import_batch_id } );
121         if ($job_id) {
122             $template->param(
123                 job_enqueued => 1,
124                 job_id => $job_id,
125             );
126         }
127     }
128     catch {
129         warn $_;
130         push @messages,
131           {
132             type  => 'error',
133             code  => 'cannot_enqueue_job',
134             error => $_,
135           };
136     };
137 } elsif ($op eq "clean-batch") {
138     CleanBatch($import_batch_id);
139     import_batches_list($template, $offset, $results_per_page);
140     $template->param( 
141         did_clean       => 1,
142         import_batch_id => $import_batch_id,
143     );
144 } elsif ($op eq "delete-batch") {
145     DeleteBatch($import_batch_id);
146     import_batches_list($template, $offset, $results_per_page);
147     $template->param(
148         did_delete      => 1,
149     );
150 } elsif ($op eq "redo-matching") {
151     my $new_matcher_id = $input->param('new_matcher_id');
152     my $current_matcher_id = $input->param('current_matcher_id');
153     my $overlay_action = $input->param('overlay_action');
154     my $nomatch_action = $input->param('nomatch_action');
155     my $item_action = $input->param('item_action');
156     redo_matching($template, $import_batch_id, $new_matcher_id, $current_matcher_id, 
157                   $overlay_action, $nomatch_action, $item_action);
158     import_records_list($template, $import_batch_id, $offset, $results_per_page);
159
160
161 output_html_with_http_headers $input, $cookie, $template->output;
162
163 exit 0;
164
165 sub redo_matching {
166     my ($template, $import_batch_id, $new_matcher_id, $current_matcher_id, $overlay_action, $nomatch_action, $item_action) = @_;
167     my $rematch_failed = 0;
168     return if not defined $new_matcher_id and not defined $current_matcher_id;
169     my $old_overlay_action = GetImportBatchOverlayAction($import_batch_id);
170     my $old_nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
171     my $old_item_action = GetImportBatchItemAction($import_batch_id);
172     return if $new_matcher_id eq $current_matcher_id and 
173               $old_overlay_action eq $overlay_action and 
174               $old_nomatch_action eq $nomatch_action and 
175               $old_item_action eq $item_action;
176  
177     if ($old_overlay_action ne $overlay_action) {
178         SetImportBatchOverlayAction($import_batch_id, $overlay_action);
179         $template->param('changed_overlay_action' => 1);
180     }
181     if ($old_nomatch_action ne $nomatch_action) {
182         SetImportBatchNoMatchAction($import_batch_id, $nomatch_action);
183         $template->param('changed_nomatch_action' => 1);
184     }
185     if ($old_item_action ne $item_action) {
186         SetImportBatchItemAction($import_batch_id, $item_action);
187         $template->param('changed_item_action' => 1);
188     }
189
190     my $num_with_matches = 0;
191     if (defined $new_matcher_id and $new_matcher_id ne "") {
192         my $matcher = C4::Matcher->fetch($new_matcher_id);
193         if (defined $matcher) {
194             $num_with_matches = BatchFindDuplicates($import_batch_id, $matcher);
195             SetImportBatchMatcher($import_batch_id, $new_matcher_id);
196         } else {
197             $rematch_failed = 1;
198         }
199     } else {
200         $num_with_matches = BatchFindDuplicates($import_batch_id, undef);
201         SetImportBatchMatcher($import_batch_id, undef);
202         SetImportBatchOverlayAction('create_new');
203     }
204     $template->param(rematch_failed => $rematch_failed);
205     $template->param(rematch_attempted => 1);
206     $template->param(num_with_matches => $num_with_matches);
207 }
208
209 sub create_labelbatch_from_importbatch {
210         my ($batch_id) = @_;
211         my $err = undef;
212         my $branch_code = C4::Context->userenv->{'branch'};
213         my $batch = C4::Labels::Batch->new(branch_code => $branch_code);
214         my @items = GetItemNumbersFromImportBatch($batch_id);
215         if (grep{$_ == 0} @items) {
216             warn sprintf('create_labelbatch_from_importbatch() : Call to C4::ImportBatch::GetItemNumbersFromImportBatch returned no item number(s) from import batch #%s.', $batch_id);
217             return -1;
218         }
219         foreach my $item_number (@items) {
220             $err = $batch->add_item($item_number);
221             if ($err == -1) {
222                 warn sprintf('create_labelbatch_from_importbatch() : Error attempting to add item #%s of import batch #%s to label batch.', $item_number, $batch_id);
223                 return -1;
224             }
225         }
226         return $batch->get_attr('batch_id');
227 }
228
229 sub import_batches_list {
230     my ($template, $offset, $results_per_page) = @_;
231     my $batches = GetImportBatchRangeDesc($offset, $results_per_page);
232
233     my @list = ();
234     foreach my $batch (@$batches) {
235         push @list, {
236             import_batch_id => $batch->{'import_batch_id'},
237             num_records => $batch->{'num_records'},
238             num_items => $batch->{'num_items'},
239             upload_timestamp => $batch->{'upload_timestamp'},
240             import_status => $batch->{'import_status'},
241             file_name => $batch->{'file_name'} || "($batch->{'batch_type'})",
242             comments => $batch->{'comments'},
243             can_clean => ($batch->{'import_status'} ne 'cleaned') ? 1 : 0,
244             record_type => $batch->{'record_type'},
245             profile => $batch->{'profile'},
246         };
247     }
248     $template->param(batch_list => \@list); 
249     my $num_batches = GetNumberOfNonZ3950ImportBatches();
250     add_page_numbers($template, $offset, $results_per_page, $num_batches);
251     $template->param(offset => $offset);
252     $template->param(range_top => $offset + $results_per_page - 1);
253     $template->param(num_results => $num_batches);
254     $template->param(results_per_page => $results_per_page);
255
256 }
257
258 sub import_records_list {
259     my ($template, $import_batch_id, $offset, $results_per_page) = @_;
260
261     my $batch = GetImportBatch($import_batch_id);
262     $template->param(import_batch_id => $import_batch_id);
263
264     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
265     $template->param("overlay_action_${overlay_action}" => 1);
266     $template->param(overlay_action => $overlay_action);
267
268     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
269     $template->param("nomatch_action_${nomatch_action}" => 1);
270     $template->param(nomatch_action => $nomatch_action);
271
272     my $item_action = GetImportBatchItemAction($import_batch_id);
273     $template->param("item_action_${item_action}" => 1);
274     $template->param(item_action => $item_action);
275
276     batch_info($template, $batch);
277     
278 }
279
280 sub batch_info {
281     my ($template, $batch) = @_;
282     $template->param(batch_info => 1);
283     $template->param(file_name => $batch->{'file_name'});
284     $template->param(profile => $batch->{'profile'});
285     $template->param(comments => $batch->{'comments'});
286     $template->param(import_status => $batch->{'import_status'});
287     $template->param(upload_timestamp => $batch->{'upload_timestamp'});
288     $template->{VARS}->{'record_type'} = $batch->{'record_type'};
289     $template->param(num_records => $batch->{'num_records'});
290     $template->param(num_items => $batch->{'num_items'});
291     if ($batch->{'import_status'} ne 'cleaned') {
292         $template->param(can_clean => 1);
293     }
294     if ($batch->{'num_records'} > 0) {
295         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
296             $template->param(can_commit => 1);
297         }
298         if ($batch->{'import_status'} eq 'imported') {
299             $template->param(can_revert => 1);
300         }
301     }
302     if (defined $batch->{'matcher_id'}) {
303         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
304         if (defined $matcher) {
305             $template->param('current_matcher_id' => $batch->{'matcher_id'});
306             $template->param('current_matcher_code' => $matcher->code());
307             $template->param('current_matcher_description' => $matcher->description());
308         }
309     }
310     add_matcher_list($template,$batch->{'matcher_id'});
311 }
312
313 sub add_matcher_list {
314     my ($template,$current_matcher_id) = @_;
315     my @matchers = C4::Matcher::GetMatcherList();
316     if (defined $current_matcher_id) {
317         for (my $i = 0; $i <= $#matchers; $i++) {
318             if ($matchers[$i]->{'matcher_id'} eq $current_matcher_id) {
319                 $matchers[$i]->{'selected'} = 1;
320             }
321         }
322     }
323     $template->param(available_matchers => \@matchers);
324 }
325
326 sub add_page_numbers {
327     my ($template, $offset, $results_per_page, $total_results) = @_;
328     my $max_pages = POSIX::ceil($total_results / $results_per_page);
329     return if $max_pages < 2;
330     my $current_page = int($offset / $results_per_page) + 1;
331     my @pages = ();
332     for (my $i = 1; $i <= $max_pages; $i++) {
333         push @pages, {
334             page_number => $i,
335             current_page => ($current_page == $i) ? 1 : 0,
336             offset => ($i - 1) * $results_per_page
337         }
338     }
339     $template->param(pages => \@pages);
340 }
341