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