Bug 31569: Remove GetImportRecordsRange from import_biblios_list
[koha.git] / acqui / addorderiso2709.pl
1 #!/usr/bin/perl
2
3 #A script that lets the user populate a basket from an iso2709 file
4 #the script first displays a list of import batches, then when a batch is selected displays all the biblios in it.
5 #The user can then pick which biblios they want to order
6
7 # Copyright 2008 - 2011 BibLibre SARL
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it
12 # under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # Koha is distributed in the hope that it will be useful, but
17 # WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23
24 use Modern::Perl;
25 use CGI qw ( -utf8 );
26 use YAML::XS;
27 use List::MoreUtils;
28 use Encode;
29
30 use C4::Context;
31 use C4::Auth qw( get_template_and_user );
32 use C4::Output qw( output_html_with_http_headers );
33 use C4::ImportBatch qw( GetImportRecordsRange GetImportRecordMarc GetImportRecordMatches SetImportRecordStatus SetMatchedBiblionumber SetImportBatchStatus GetImportBatch GetImportBatchRangeDesc GetNumberOfNonZ3950ImportBatches GetImportBatchOverlayAction GetImportBatchNoMatchAction GetImportBatchItemAction );
34 use C4::Matcher;
35 use C4::Search qw( FindDuplicate );
36 use C4::Biblio qw(
37     AddBiblio
38     GetMarcFromKohaField
39     GetMarcPrice
40     GetMarcQuantity
41     TransformHtmlToXml
42 );
43 use C4::Items qw( PrepareItemrecordDisplay AddItemFromMarc );
44 use C4::Budgets qw( GetBudget GetBudgets GetBudgetHierarchy CanUserUseBudget GetBudgetByCode );
45 use C4::Suggestions;    # GetSuggestion
46 use C4::Members;
47
48 use Koha::Number::Price;
49 use Koha::Libraries;
50 use Koha::Acquisition::Baskets;
51 use Koha::Acquisition::Currencies;
52 use Koha::Acquisition::Orders;
53 use Koha::Acquisition::Booksellers;
54 use Koha::Import::Records;
55 use Koha::Patrons;
56
57 my $input = CGI->new;
58 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
59     template_name => "acqui/addorderiso2709.tt",
60     query => $input,
61     type => "intranet",
62     flagsrequired   => { acquisition => 'order_manage' },
63 });
64
65 my $cgiparams = $input->Vars;
66 my $op = $cgiparams->{'op'} || '';
67 my $booksellerid  = $input->param('booksellerid');
68 my $allmatch = $input->param('allmatch');
69 my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
70
71 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
72                 booksellerid => $booksellerid,
73                 booksellername => $bookseller->name,
74                 );
75
76 if ($cgiparams->{'import_batch_id'} && $op eq ""){
77     $op = "batch_details";
78 }
79
80 #Needed parameters:
81 if (! $cgiparams->{'basketno'}){
82     die "Basketnumber required to order from iso2709 file import";
83 }
84 my $basket = Koha::Acquisition::Baskets->find( $cgiparams->{basketno} );
85
86 #
87 # 1st step = choose the file to import into acquisition
88 #
89 if ($op eq ""){
90     $template->param("basketno" => $cgiparams->{'basketno'});
91 #display batches
92     import_batches_list($template);
93 #
94 # 2nd step = display the content of the chosen file
95 #
96 } elsif ($op eq "batch_details"){
97 #display lines inside the selected batch
98
99     $template->param("batch_details" => 1,
100                      "basketno"      => $cgiparams->{'basketno'},
101                      # get currencies (for change rates calcs if needed)
102                      currencies => Koha::Acquisition::Currencies->search,
103                      bookseller => $bookseller,
104                      "allmatch" => $allmatch,
105                      );
106     import_biblios_list($template, $cgiparams->{'import_batch_id'});
107     if ( $basket->effective_create_items eq 'ordering' && !$basket->is_standing ) {
108         # prepare empty item form
109         my $cell = PrepareItemrecordDisplay( '', '', undef, 'ACQ' );
110
111         #     warn "==> ".Data::Dumper::Dumper($cell);
112         unless ($cell) {
113             $cell = PrepareItemrecordDisplay( '', '', undef, '' );
114             $template->param( 'NoACQframework' => 1 );
115         }
116         my @itemloop;
117         push @itemloop, $cell;
118
119         $template->param( items => \@itemloop );
120     }
121 #
122 # 3rd step = import the records
123 #
124 } elsif ( $op eq 'import_records' ) {
125 #import selected lines
126     $template->param('basketno' => $cgiparams->{'basketno'});
127 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
128     my $budgets = GetBudgets();
129     if (scalar @$budgets == 0){
130         die "No budgets defined, can't continue";
131     }
132     my $budget_id = @$budgets[0]->{'budget_id'};
133 #get all records from a batch, and check their import status to see if they are checked.
134 #(default values: quantity 1, uncertainprice yes, first budget)
135
136     # retrieve the file you want to import
137     my $import_batch_id = $cgiparams->{'import_batch_id'};
138     my $biblios = GetImportRecordsRange($import_batch_id);
139     my $duplinbatch;
140     my $imported = 0;
141     my @import_record_id_selected = $input->multi_param("import_record_id");
142     my @quantities = $input->multi_param('quantity');
143     my @prices = $input->multi_param('price');
144     my @orderreplacementprices = $input->multi_param('replacementprice');
145     my @budgets_id = $input->multi_param('budget_id');
146     my @discount = $input->multi_param('discount');
147     my @sort1 = $input->multi_param('sort1');
148     my @sort2 = $input->multi_param('sort2');
149     my $matcher_id = $input->param('matcher_id');
150     my $active_currency = Koha::Acquisition::Currencies->get_active;
151     my $biblio_count = 0;
152     for my $biblio (@$biblios){
153         $biblio_count++;
154         my $duplifound = 0;
155         # Check if this import_record_id was selected
156         next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
157         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
158         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
159         my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
160         my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
161         my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
162         my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
163         my $c_discount = shift ( @discount);
164         my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
165         my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
166         my $c_replacement_price = shift( @orderreplacementprices );
167         my $c_price = shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
168
169         # Insert the biblio, or find it through matcher
170         unless ( $biblionumber ) {
171             if ($matcher_id) {
172                 if ( $matcher_id eq '_TITLE_AUTHOR_' ) {
173                     $duplifound = 1 if FindDuplicate($marcrecord);
174                 }
175                 else {
176                     my $matcher = C4::Matcher->fetch($matcher_id);
177                     my @matches = $matcher->get_matches( $marcrecord, my $max_matches = 1 );
178                     $duplifound = 1 if @matches;
179                 }
180
181                 $duplinbatch = $import_batch_id and next if $duplifound;
182             }
183
184             # add the biblio
185             my $bibitemnum;
186
187             # remove ISBN -
188             my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn' );
189             if ( $marcrecord->field($isbnfield) ) {
190                 foreach my $field ( $marcrecord->field($isbnfield) ) {
191                     foreach my $subfield ( $field->subfield($isbnsubfield) ) {
192                         my $newisbn = $field->subfield($isbnsubfield);
193                         $newisbn =~ s/-//g;
194                         $field->update( $isbnsubfield => $newisbn );
195                     }
196                 }
197             }
198             ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
199             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
200         } else {
201             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
202         }
203
204         SetMatchedBiblionumber( $biblio->{import_record_id}, $biblionumber );
205
206         # Add items from MarcItemFieldsToOrder
207         my @homebranches = $input->multi_param('homebranch_' . $biblio_count);
208         my $count = scalar @homebranches;
209         my @holdingbranches = $input->multi_param('holdingbranch_' . $biblio_count);
210         my @itypes = $input->multi_param('itype_' . $biblio_count);
211         my @nonpublic_notes = $input->multi_param('nonpublic_note_' . $biblio_count);
212         my @public_notes = $input->multi_param('public_note_' . $biblio_count);
213         my @locs = $input->multi_param('loc_' . $biblio_count);
214         my @ccodes = $input->multi_param('ccode_' . $biblio_count);
215         my @notforloans = $input->multi_param('notforloan_' . $biblio_count);
216         my @uris = $input->multi_param('uri_' . $biblio_count);
217         my @copynos = $input->multi_param('copyno_' . $biblio_count);
218         my @budget_codes = $input->multi_param('budget_code_' . $biblio_count);
219         my @itemprices = $input->multi_param('itemprice_' . $biblio_count);
220         my @replacementprices = $input->multi_param('replacementprice_' . $biblio_count);
221         my @itemcallnumbers = $input->multi_param('itemcallnumber_' . $biblio_count);
222         my $itemcreation = 0;
223
224         my @itemnumbers;
225         for (my $i = 0; $i < $count; $i++) {
226             $itemcreation = 1;
227             my $item = Koha::Item->new(
228                 {
229                     biblionumber        => $biblionumber,
230                     homebranch          => $homebranches[$i],
231                     holdingbranch       => $holdingbranches[$i],
232                     itemnotes_nonpublic => $nonpublic_notes[$i],
233                     itemnotes           => $public_notes[$i],
234                     location            => $locs[$i],
235                     ccode               => $ccodes[$i],
236                     itype               => $itypes[$i],
237                     notforloan          => $notforloans[$i],
238                     uri                 => $uris[$i],
239                     copynumber          => $copynos[$i],
240                     price               => $itemprices[$i],
241                     replacementprice    => $replacementprices[$i],
242                     itemcallnumber      => $itemcallnumbers[$i],
243                 }
244             )->store;
245             push( @itemnumbers, $item->itemnumber );
246         }
247         if ($itemcreation == 1) {
248             # Group orderlines from MarcItemFieldsToOrder
249             my $budget_hash;
250             for (my $i = 0; $i < $count; $i++) {
251                 $budget_hash->{$budget_codes[$i]}->{quantity} += 1;
252                 $budget_hash->{$budget_codes[$i]}->{price} = $itemprices[$i];
253                 $budget_hash->{$budget_codes[$i]}->{replacementprice} = $replacementprices[$i];
254                 $budget_hash->{$budget_codes[$i]}->{itemnumbers} //= [];
255                 push @{ $budget_hash->{$budget_codes[$i]}->{itemnumbers} }, $itemnumbers[$i];
256             }
257
258             # Create orderlines from MarcItemFieldsToOrder
259             while(my ($budget_id, $infos) = each %$budget_hash) {
260                 if ($budget_id) {
261                     my %orderinfo = (
262                         biblionumber       => $biblionumber,
263                         basketno           => $cgiparams->{'basketno'},
264                         quantity           => $infos->{quantity},
265                         budget_id          => $budget_id,
266                         currency           => $cgiparams->{'all_currency'},
267                     );
268
269                     my $price = $infos->{price};
270                     if ($price){
271                         # in France, the cents separator is the , but sometimes, ppl use a .
272                         # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
273                         $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
274                         $price = Koha::Number::Price->new($price)->unformat;
275                         $orderinfo{tax_rate_on_ordering} = $bookseller->tax_rate;
276                         $orderinfo{tax_rate_on_receiving} = $bookseller->tax_rate;
277                         my $c = $c_discount ? $c_discount : $bookseller->discount;
278                         $orderinfo{discount} = $c;
279                         if ( $c ) {
280                             $orderinfo{ecost} = $price * ( 1 - $c / 100 );
281                             $orderinfo{rrp}   = $price;
282                         }
283                         $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
284                         $orderinfo{unitprice} = $orderinfo{ecost};
285                     } else {
286                         $orderinfo{listprice} = 0;
287                     }
288                     $orderinfo{replacementprice} = $infos->{replacementprice} || 0;
289
290                     # remove uncertainprice flag if we have found a price in the MARC record
291                     $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
292
293                     my $order = Koha::Acquisition::Order->new( \%orderinfo )->store;
294                     $order->populate_with_prices_for_ordering();
295                     $order->populate_with_prices_for_receiving();
296                     $order->add_item( $_ ) for @{ $budget_hash->{$budget_id}->{itemnumbers} };
297                 }
298             }
299         } else {
300             # 3rd add order
301             my $patron = Koha::Patrons->find( $loggedinuser );
302             # get quantity in the MARC record (1 if none)
303             my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
304             my %orderinfo = (
305                 biblionumber       => $biblionumber,
306                 basketno           => $cgiparams->{'basketno'},
307                 quantity           => $c_quantity,
308                 branchcode         => $patron->branchcode,
309                 budget_id          => $c_budget_id,
310                 uncertainprice     => 1,
311                 sort1              => $c_sort1,
312                 sort2              => $c_sort2,
313                 order_internalnote => $cgiparams->{'all_order_internalnote'},
314                 order_vendornote   => $cgiparams->{'all_order_vendornote'},
315                 currency           => $cgiparams->{'all_currency'},
316                 replacementprice   => $c_replacement_price,
317             );
318             # get the price if there is one.
319             if ($c_price){
320                 # in France, the cents separator is the , but sometimes, ppl use a .
321                 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
322                 $c_price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
323                 $c_price = Koha::Number::Price->new($c_price)->unformat;
324                 $orderinfo{tax_rate_on_ordering} = $bookseller->tax_rate;
325                 $orderinfo{tax_rate_on_receiving} = $bookseller->tax_rate;
326                 my $c = $c_discount ? $c_discount : $bookseller->discount;
327                 $orderinfo{discount} = $c;
328                 if ( $c ) {
329                     $orderinfo{ecost} = $c_price * ( 1 - $c / 100 );
330                     $orderinfo{rrp}   = $c_price;
331                 }
332                 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
333                 $orderinfo{unitprice} = $orderinfo{ecost};
334             } else {
335                 $orderinfo{listprice} = 0;
336             }
337
338         # remove uncertainprice flag if we have found a price in the MARC record
339         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
340
341         my $order = Koha::Acquisition::Order->new( \%orderinfo );
342         $order->populate_with_prices_for_ordering();
343         $order->populate_with_prices_for_receiving();
344         $order->store;
345
346         # 4th, add items if applicable
347         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
348         # this is not optimised, but it's working !
349         if ( $basket->effective_create_items eq 'ordering' && !$basket->is_standing ) {
350             my @tags         = $input->multi_param('tag');
351             my @subfields    = $input->multi_param('subfield');
352             my @field_values = $input->multi_param('field_value');
353             my @serials      = $input->multi_param('serial');
354             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values );
355             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
356             for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
357                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
358                 $order->add_item( $itemnumber );
359                 }
360             } else {
361                 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
362             }
363         }
364         $imported++;
365     }
366
367     # If all bibliographic records from the batch have been imported we modifying the status of the batch accordingly
368     SetImportBatchStatus( $import_batch_id, 'imported' )
369         if    @{ GetImportRecordsRange( $import_batch_id, undef, undef, 'imported' )}
370            == @{ GetImportRecordsRange( $import_batch_id )};
371
372     # go to basket page
373     if ( $imported ) {
374         print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
375     } else {
376         print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&amp;basketno=".$cgiparams->{'basketno'}."&amp;booksellerid=$booksellerid&amp;allmatch=1");
377     }
378     exit;
379 }
380
381 my $budgets = GetBudgets();
382 my $budget_id = @$budgets[0]->{'budget_id'};
383 # build bookfund list
384 my $patron = Koha::Patrons->find( $loggedinuser )->unblessed;
385 my $budget = GetBudget($budget_id);
386
387 # build budget list
388 my $budget_loop = [];
389 my $budgets_hierarchy = GetBudgetHierarchy;
390 foreach my $r ( @{$budgets_hierarchy} ) {
391     next unless (CanUserUseBudget($patron, $r, $userflags));
392     push @{$budget_loop},
393       { b_id  => $r->{budget_id},
394         b_txt => $r->{budget_name},
395         b_code => $r->{budget_code},
396         b_sort1_authcat => $r->{'sort1_authcat'},
397         b_sort2_authcat => $r->{'sort2_authcat'},
398         b_active => $r->{budget_period_active},
399         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
400       };
401 }
402
403 @{$budget_loop} =
404   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
405
406 $template->param( budget_loop    => $budget_loop,);
407
408 output_html_with_http_headers $input, $cookie, $template->output;
409
410
411 sub import_batches_list {
412     my ($template) = @_;
413     my $batches = GetImportBatchRangeDesc();
414
415     my @list = ();
416     foreach my $batch (@$batches) {
417         if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
418             # check if there is at least 1 line still staged
419             my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
420             if (scalar @$stagedList) {
421                 push @list, {
422                         import_batch_id => $batch->{'import_batch_id'},
423                         num_records => $batch->{'num_records'},
424                         num_items => $batch->{'num_items'},
425                         staged_date => $batch->{'upload_timestamp'},
426                         import_status => $batch->{'import_status'},
427                         file_name => $batch->{'file_name'},
428                         comments => $batch->{'comments'},
429                 };
430             } else {
431                 # if there are no more line to includes, set the status to imported
432                 # FIXME This should be removed in the future.
433                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
434             }
435         }
436     }
437     $template->param(batch_list => \@list); 
438     my $num_batches = GetNumberOfNonZ3950ImportBatches();
439     $template->param(num_results => $num_batches);
440 }
441
442 sub import_biblios_list {
443     my ($template, $import_batch_id) = @_;
444     my $batch = GetImportBatch($import_batch_id,'staged');
445     return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
446     my $import_records = Koha::Import::Records->search({
447         import_batch_id => $import_batch_id,
448         status => $batch->{import_status}
449     });
450     my @list = ();
451     my $item_error = 0;
452
453     my $ccodes = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' } ) };
454     my $locations = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
455     my $notforloans = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.notforloan' } ) };
456     # location list
457     my @locations;
458     foreach (sort keys %$locations) {
459         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
460     }
461     my @ccodes;
462     foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
463         push @ccodes, { code => $_, description => $ccodes->{$_} };
464     }
465     my @notforloans;
466     foreach (sort {$notforloans->{$a} cmp $notforloans->{$b}} keys %$notforloans) {
467         push @notforloans, { code => $_, description => $notforloans->{$_} };
468     }
469
470     my $biblio_count = 0;
471     while ( my $import_record = $import_records->next ) {
472         my $item_id = 1;
473         $biblio_count++;
474         my $match = GetImportRecordMatches($import_record->import_record_id, 1);
475         my %cellrecord = (
476             import_record_id => $import_record->import_record_id,
477             import_biblio => $import_record->import_biblio,
478             import  => 1,
479             status => $import_record->status,
480             record_sequence => $import_record->record_sequence,
481             overlay_status => $import_record->overlay_status,
482             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
483             match_citation     => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
484             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
485         );
486         my $marcrecord = $import_record->get_marc_record || die "couldn't translate marc information";
487
488         my $infos = get_infos_syspref('MarcFieldsToOrder', $marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2','replacementprice']);
489         my $price = $infos->{price};
490         my $replacementprice = $infos->{replacementprice};
491         my $quantity = $infos->{quantity};
492         my $budget_code = $infos->{budget_code};
493         my $discount = $infos->{discount};
494         my $sort1 = $infos->{sort1};
495         my $sort2 = $infos->{sort2};
496         my $budget_id;
497         if($budget_code) {
498             my $biblio_budget = GetBudgetByCode($budget_code);
499             if($biblio_budget) {
500                 $budget_id = $biblio_budget->{budget_id};
501             }
502         }
503
504         # Items
505         my @itemlist = ();
506         my $all_items_quantity = 0;
507         my $alliteminfos = get_infos_syspref_on_item('MarcItemFieldsToOrder', $marcrecord, ['homebranch', 'holdingbranch', 'itype', 'nonpublic_note', 'public_note', 'loc', 'ccode', 'notforloan', 'uri', 'copyno', 'price', 'replacementprice', 'itemcallnumber', 'quantity', 'budget_code']);
508         if ($alliteminfos != -1) {
509             foreach my $iteminfos (@$alliteminfos) {
510                 my $item_homebranch = $iteminfos->{homebranch};
511                 my $item_holdingbranch = $iteminfos->{holdingbranch};
512                 my $item_itype = $iteminfos->{itype};
513                 my $item_nonpublic_note = $iteminfos->{nonpublic_note};
514                 my $item_public_note = $iteminfos->{public_note};
515                 my $item_loc = $iteminfos->{loc};
516                 my $item_ccode = $iteminfos->{ccode};
517                 my $item_notforloan = $iteminfos->{notforloan};
518                 my $item_uri = $iteminfos->{uri};
519                 my $item_copyno = $iteminfos->{copyno};
520                 my $item_quantity = $iteminfos->{quantity} || 1;
521                 my $item_budget_code = $iteminfos->{budget_code};
522                 my $item_budget_id;
523                 if ( $iteminfos->{budget_code} ) {
524                     my $item_budget = GetBudgetByCode( $iteminfos->{budget_code} );
525                     if ( $item_budget ) {
526                         $item_budget_id = $item_budget->{budget_id};
527                     }
528                 }
529                 my $item_price = $iteminfos->{price};
530                 my $item_replacement_price = $iteminfos->{replacementprice};
531                 my $item_callnumber = $iteminfos->{itemcallnumber};
532
533                 for (my $i = 0; $i < $item_quantity; $i++) {
534
535                     my %itemrecord = (
536                         'item_id' => $item_id++,
537                         'biblio_count' => $biblio_count,
538                         'homebranch' => $item_homebranch,
539                         'holdingbranch' => $item_holdingbranch,
540                         'itype' => $item_itype,
541                         'nonpublic_note' => $item_nonpublic_note,
542                         'public_note' => $item_public_note,
543                         'loc' => $item_loc,
544                         'ccode' => $item_ccode,
545                         'notforloan' => $item_notforloan,
546                         'uri' => $item_uri,
547                         'copyno' => $item_copyno,
548                         'quantity' => $item_quantity,
549                         'budget_id' => $item_budget_id || $budget_id,
550                         'itemprice' => $item_price || $price,
551                         'replacementprice' => $item_replacement_price || $replacementprice,
552                         'itemcallnumber' => $item_callnumber,
553                     );
554                     $all_items_quantity++;
555                     push @itemlist, \%itemrecord;
556
557                 }
558             }
559
560             $cellrecord{'iteminfos'} = \@itemlist;
561         } else {
562             $cellrecord{'item_error'} = 1;
563         }
564         push @list, \%cellrecord;
565
566         if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
567             $cellrecord{price} = $price || '';
568             $cellrecord{replacementprice} = $replacementprice || '';
569             $cellrecord{quantity} = $quantity || '';
570             $cellrecord{budget_id} = $budget_id || '';
571             $cellrecord{discount} = $discount || '';
572             $cellrecord{sort1} = $sort1 || '';
573             $cellrecord{sort2} = $sort2 || '';
574         } else {
575             $cellrecord{quantity} = $all_items_quantity;
576         }
577
578     }
579     my $num_records = $batch->{'num_records'};
580     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
581     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
582     my $item_action = GetImportBatchItemAction($import_batch_id);
583     $template->param(import_biblio_list => \@list,
584                         num_results => $num_records,
585                         import_batch_id => $import_batch_id,
586                         "overlay_action_${overlay_action}" => 1,
587                         overlay_action => $overlay_action,
588                         "nomatch_action_${nomatch_action}" => 1,
589                         nomatch_action => $nomatch_action,
590                         "item_action_${item_action}" => 1,
591                         item_action => $item_action,
592                         item_error => $item_error,
593                         libraries => Koha::Libraries->search,
594                         locationloop => \@locations,
595                         itemtypes => Koha::ItemTypes->search,
596                         ccodeloop => \@ccodes,
597                         notforloanloop => \@notforloans,
598                     );
599     batch_info($template, $batch);
600 }
601
602 sub batch_info {
603     my ($template, $batch) = @_;
604     $template->param(batch_info => 1,
605                                       file_name => $batch->{'file_name'},
606                                           comments => $batch->{'comments'},
607                                           import_status => $batch->{'import_status'},
608                                           upload_timestamp => $batch->{'upload_timestamp'},
609                                           num_records => $batch->{'num_records'},
610                                           num_items => $batch->{'num_items'});
611     if ($batch->{'num_records'} > 0) {
612         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
613             $template->param(can_commit => 1);
614         }
615         if ($batch->{'import_status'} eq 'imported') {
616             $template->param(can_revert => 1);
617         }
618     }
619     if (defined $batch->{'matcher_id'}) {
620         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
621         if (defined $matcher) {
622             $template->param('current_matcher_id' => $batch->{'matcher_id'},
623                                               'current_matcher_code' => $matcher->code(),
624                                               'current_matcher_description' => $matcher->description());
625         }
626     }
627     add_matcher_list($batch->{'matcher_id'}, $template);
628 }
629
630 sub add_matcher_list {
631     my ($current_matcher_id, $template) = @_;
632     my @matchers = C4::Matcher::GetMatcherList();
633     if (defined $current_matcher_id) {
634         for (my $i = 0; $i <= $#matchers; $i++) {
635             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
636                 $matchers[$i]->{'selected'} = 1;
637             }
638         }
639     }
640     $template->param(available_matchers => \@matchers);
641 }
642
643 sub get_infos_syspref {
644     my ($syspref_name, $record, $field_list) = @_;
645     my $syspref = C4::Context->preference($syspref_name);
646     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
647     my $yaml = eval {
648         YAML::XS::Load(Encode::encode_utf8($syspref));
649     };
650     if ( $@ ) {
651         warn "Unable to parse $syspref syspref : $@";
652         return ();
653     }
654     my $r;
655     for my $field_name ( @$field_list ) {
656         next unless exists $yaml->{$field_name};
657         my @fields = split /\|/, $yaml->{$field_name};
658         for my $field ( @fields ) {
659             my ( $f, $sf ) = split /\$/, $field;
660             next unless $f and $sf;
661             if ( my $v = $record->subfield( $f, $sf ) ) {
662                 $r->{$field_name} = $v;
663             }
664             last if $yaml->{$field};
665         }
666     }
667     return $r;
668 }
669
670 sub equal_number_of_fields {
671     my ($tags_list, $record) = @_;
672     my $tag_fields_count;
673     for my $tag (@$tags_list) {
674         my @fields = $record->field($tag);
675         $tag_fields_count->{$tag} = scalar @fields;
676     }
677
678     my $tags_count;
679     foreach my $key ( keys %$tag_fields_count ) {
680         if ( $tag_fields_count->{$key} > 0 ) { # Having 0 of a field is ok
681             $tags_count //= $tag_fields_count->{$key}; # Start with the count from the first occurrence
682             return -1 if $tag_fields_count->{$key} != $tags_count; # All counts of various fields should be equal if they exist
683         }
684     }
685
686     return $tags_count;
687 }
688
689 sub get_infos_syspref_on_item {
690     my ($syspref_name, $record, $field_list) = @_;
691     my $syspref = C4::Context->preference($syspref_name);
692     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
693     my $yaml = eval {
694         YAML::XS::Load(Encode::encode_utf8($syspref));
695     };
696     if ( $@ ) {
697         warn "Unable to parse $syspref syspref : $@";
698         return ();
699     }
700     my @result;
701     my @tags_list;
702
703     # Check tags in syspref definition
704     for my $field_name ( @$field_list ) {
705         next unless exists $yaml->{$field_name};
706         my @fields = split /\|/, $yaml->{$field_name};
707         for my $field ( @fields ) {
708             my ( $f, $sf ) = split /\$/, $field;
709             next unless $f and $sf;
710             push @tags_list, $f;
711         }
712     }
713     @tags_list = List::MoreUtils::uniq(@tags_list);
714
715     my $tags_count = equal_number_of_fields(\@tags_list, $record);
716     # Return if the number of these fields in the record is not the same.
717     return -1 if $tags_count == -1;
718
719     # Gather the fields
720     my $fields_hash;
721     foreach my $tag (@tags_list) {
722         my @tmp_fields;
723         foreach my $field ($record->field($tag)) {
724             push @tmp_fields, $field;
725         }
726         $fields_hash->{$tag} = \@tmp_fields;
727     }
728
729     for (my $i = 0; $i < $tags_count; $i++) {
730         my $r;
731         for my $field_name ( @$field_list ) {
732             next unless exists $yaml->{$field_name};
733             my @fields = split /\|/, $yaml->{$field_name};
734             for my $field ( @fields ) {
735                 my ( $f, $sf ) = split /\$/, $field;
736                 next unless $f and $sf;
737                 my $v = $fields_hash->{$f}[$i] ? $fields_hash->{$f}[$i]->subfield( $sf ) : undef;
738                 $r->{$field_name} = $v if (defined $v);
739                 last if $yaml->{$field};
740             }
741         }
742         push @result, $r;
743     }
744     return \@result;
745 }