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