Bug 32166: Use import record id for retrieving correct inputs
[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( GetImportRecordMatches 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 $import_records = Koha::Import::Records->search({
139         import_batch_id => $import_batch_id,
140     });
141     my $duplinbatch;
142     my $imported = 0;
143     my @import_record_id_selected = $input->multi_param("import_record_id");
144     my @quantities = $input->multi_param('quantity');
145     my @prices = $input->multi_param('price');
146     my @orderreplacementprices = $input->multi_param('replacementprice');
147     my @budgets_id = $input->multi_param('budget_id');
148     my @discount = $input->multi_param('discount');
149     my @sort1 = $input->multi_param('sort1');
150     my @sort2 = $input->multi_param('sort2');
151     my $matcher_id = $input->param('matcher_id');
152     my $active_currency = Koha::Acquisition::Currencies->get_active;
153     my $biblio_count = 0;
154     while( my $import_record = $import_records->next ){
155         $biblio_count++;
156         my $duplifound = 0;
157         # Check if this import_record_id was selected
158         next if not grep { $_ eq $import_record->import_record_id } @import_record_id_selected;
159         my $marcrecord = $import_record->get_marc_record || die "couldn't translate marc information";
160         my $match = GetImportRecordMatches( $import_record->import_record_id, 1 );
161         my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
162         my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
163         my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
164         my $c_discount = shift ( @discount);
165         my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
166         my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
167         my $c_replacement_price = shift( @orderreplacementprices );
168         my $c_price = shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
169
170         # Insert the biblio, or find it through matcher
171         unless ( $biblionumber ) {
172             if ($matcher_id) {
173                 if ( $matcher_id eq '_TITLE_AUTHOR_' ) {
174                     $duplifound = 1 if FindDuplicate($marcrecord);
175                 }
176                 else {
177                     my $matcher = C4::Matcher->fetch($matcher_id);
178                     my @matches = $matcher->get_matches( $marcrecord, my $max_matches = 1 );
179                     $duplifound = 1 if @matches;
180                 }
181
182                 $duplinbatch = $import_batch_id and next if $duplifound;
183             }
184
185             # add the biblio
186             my $bibitemnum;
187
188             # remove ISBN -
189             my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn' );
190             if ( $marcrecord->field($isbnfield) ) {
191                 foreach my $field ( $marcrecord->field($isbnfield) ) {
192                     foreach my $subfield ( $field->subfield($isbnsubfield) ) {
193                         my $newisbn = $field->subfield($isbnsubfield);
194                         $newisbn =~ s/-//g;
195                         $field->update( $isbnsubfield => $newisbn );
196                     }
197                 }
198             }
199             ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
200             $import_record->status('imported')->store;
201         } else {
202             $import_record->status('imported')->store;
203         }
204
205         $import_record->import_biblio->matched_biblionumber($biblionumber)->store;
206
207         # Add items from MarcItemFieldsToOrder
208         my @homebranches = $input->multi_param('homebranch_' . $import_record->import_record_id);
209         my $count = scalar @homebranches;
210         my @holdingbranches = $input->multi_param('holdingbranch_' . $import_record->import_record_id);
211         my @itypes = $input->multi_param('itype_' . $import_record->import_record_id);
212         my @nonpublic_notes = $input->multi_param('nonpublic_note_' . $import_record->import_record_id);
213         my @public_notes = $input->multi_param('public_note_' . $import_record->import_record_id);
214         my @locs = $input->multi_param('loc_' . $import_record->import_record_id);
215         my @ccodes = $input->multi_param('ccode_' . $import_record->import_record_id);
216         my @notforloans = $input->multi_param('notforloan_' . $import_record->import_record_id);
217         my @uris = $input->multi_param('uri_' . $import_record->import_record_id);
218         my @copynos = $input->multi_param('copyno_' . $import_record->import_record_id);
219         my @budget_codes = $input->multi_param('budget_code_' . $import_record->import_record_id);
220         my @itemprices = $input->multi_param('itemprice_' . $import_record->import_record_id);
221         my @replacementprices = $input->multi_param('replacementprice_' . $import_record->import_record_id);
222         my @itemcallnumbers = $input->multi_param('itemcallnumber_' . $import_record->import_record_id);
223         my $itemcreation = 0;
224
225         my @itemnumbers;
226         for (my $i = 0; $i < $count; $i++) {
227             $itemcreation = 1;
228             my $item = Koha::Item->new(
229                 {
230                     biblionumber        => $biblionumber,
231                     homebranch          => $homebranches[$i],
232                     holdingbranch       => $holdingbranches[$i],
233                     itemnotes_nonpublic => $nonpublic_notes[$i],
234                     itemnotes           => $public_notes[$i],
235                     location            => $locs[$i],
236                     ccode               => $ccodes[$i],
237                     itype               => $itypes[$i],
238                     notforloan          => $notforloans[$i],
239                     uri                 => $uris[$i],
240                     copynumber          => $copynos[$i],
241                     price               => $itemprices[$i],
242                     replacementprice    => $replacementprices[$i],
243                     itemcallnumber      => $itemcallnumbers[$i],
244                 }
245             )->store;
246             push( @itemnumbers, $item->itemnumber );
247         }
248         if ($itemcreation == 1) {
249             # Group orderlines from MarcItemFieldsToOrder
250             my $budget_hash;
251             for (my $i = 0; $i < $count; $i++) {
252                 $budget_hash->{$budget_codes[$i]}->{quantity} += 1;
253                 $budget_hash->{$budget_codes[$i]}->{price} = $itemprices[$i];
254                 $budget_hash->{$budget_codes[$i]}->{replacementprice} = $replacementprices[$i];
255                 $budget_hash->{$budget_codes[$i]}->{itemnumbers} //= [];
256                 push @{ $budget_hash->{$budget_codes[$i]}->{itemnumbers} }, $itemnumbers[$i];
257             }
258
259             # Create orderlines from MarcItemFieldsToOrder
260             while(my ($budget_id, $infos) = each %$budget_hash) {
261                 if ($budget_id) {
262                     my %orderinfo = (
263                         biblionumber       => $biblionumber,
264                         basketno           => $cgiparams->{'basketno'},
265                         quantity           => $infos->{quantity},
266                         budget_id          => $budget_id,
267                         currency           => $cgiparams->{'all_currency'},
268                     );
269
270                     my $price = $infos->{price};
271                     if ($price){
272                         # in France, the cents separator is the , but sometimes, ppl use a .
273                         # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
274                         $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
275                         $price = Koha::Number::Price->new($price)->unformat;
276                         $orderinfo{tax_rate_on_ordering} = $bookseller->tax_rate;
277                         $orderinfo{tax_rate_on_receiving} = $bookseller->tax_rate;
278                         my $c = $c_discount ? $c_discount : $bookseller->discount;
279                         $orderinfo{discount} = $c;
280                         if ( $c ) {
281                             $orderinfo{ecost} = $price * ( 1 - $c / 100 );
282                             $orderinfo{rrp}   = $price;
283                         }
284                         $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
285                         $orderinfo{unitprice} = $orderinfo{ecost};
286                     } else {
287                         $orderinfo{listprice} = 0;
288                     }
289                     $orderinfo{replacementprice} = $infos->{replacementprice} || 0;
290
291                     # remove uncertainprice flag if we have found a price in the MARC record
292                     $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
293
294                     my $order = Koha::Acquisition::Order->new( \%orderinfo )->store;
295                     $order->populate_with_prices_for_ordering();
296                     $order->populate_with_prices_for_receiving();
297                     $order->add_item( $_ ) for @{ $budget_hash->{$budget_id}->{itemnumbers} };
298                 }
299             }
300         } else {
301             # 3rd add order
302             my $patron = Koha::Patrons->find( $loggedinuser );
303             # get quantity in the MARC record (1 if none)
304             my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
305             my %orderinfo = (
306                 biblionumber       => $biblionumber,
307                 basketno           => $cgiparams->{'basketno'},
308                 quantity           => $c_quantity,
309                 branchcode         => $patron->branchcode,
310                 budget_id          => $c_budget_id,
311                 uncertainprice     => 1,
312                 sort1              => $c_sort1,
313                 sort2              => $c_sort2,
314                 order_internalnote => $cgiparams->{'all_order_internalnote'},
315                 order_vendornote   => $cgiparams->{'all_order_vendornote'},
316                 currency           => $cgiparams->{'all_currency'},
317                 replacementprice   => $c_replacement_price,
318             );
319             # get the price if there is one.
320             if ($c_price){
321                 # in France, the cents separator is the , but sometimes, ppl use a .
322                 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
323                 $c_price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
324                 $c_price = Koha::Number::Price->new($c_price)->unformat;
325                 $orderinfo{tax_rate_on_ordering} = $bookseller->tax_rate;
326                 $orderinfo{tax_rate_on_receiving} = $bookseller->tax_rate;
327                 my $c = $c_discount ? $c_discount : $bookseller->discount;
328                 $orderinfo{discount} = $c;
329                 if ( $c ) {
330                     $orderinfo{ecost} = $c_price * ( 1 - $c / 100 );
331                     $orderinfo{rrp}   = $c_price;
332                 }
333                 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
334                 $orderinfo{unitprice} = $orderinfo{ecost};
335             } else {
336                 $orderinfo{listprice} = 0;
337             }
338
339         # remove uncertainprice flag if we have found a price in the MARC record
340         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
341
342         my $order = Koha::Acquisition::Order->new( \%orderinfo );
343         $order->populate_with_prices_for_ordering();
344         $order->populate_with_prices_for_receiving();
345         $order->store;
346
347         # 4th, add items if applicable
348         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
349         # this is not optimised, but it's working !
350         if ( $basket->effective_create_items eq 'ordering' && !$basket->is_standing ) {
351             my @tags         = $input->multi_param('tag');
352             my @subfields    = $input->multi_param('subfield');
353             my @field_values = $input->multi_param('field_value');
354             my @serials      = $input->multi_param('serial');
355             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values );
356             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
357             for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
358                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
359                 $order->add_item( $itemnumber );
360                 }
361             } else {
362                 $import_record->status( 'imported' )->store;
363             }
364         }
365         $imported++;
366     }
367
368     # If all bibliographic records from the batch have been imported we modifying the status of the batch accordingly
369     SetImportBatchStatus( $import_batch_id, 'imported' )
370         if Koha::Import::Records->search({import_batch_id => $import_batch_id, status => 'imported' })->count
371            == Koha::Import::Records->search({import_batch_id => $import_batch_id})->count;
372
373     # go to basket page
374     if ( $imported ) {
375         print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
376     } else {
377         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");
378     }
379     exit;
380 }
381
382 my $budgets = GetBudgets();
383 my $budget_id = @$budgets[0]->{'budget_id'};
384 # build bookfund list
385 my $patron = Koha::Patrons->find( $loggedinuser )->unblessed;
386 my $budget = GetBudget($budget_id);
387
388 # build budget list
389 my $budget_loop = [];
390 my $budgets_hierarchy = GetBudgetHierarchy;
391 foreach my $r ( @{$budgets_hierarchy} ) {
392     next unless (CanUserUseBudget($patron, $r, $userflags));
393     push @{$budget_loop},
394       { b_id  => $r->{budget_id},
395         b_txt => $r->{budget_name},
396         b_code => $r->{budget_code},
397         b_sort1_authcat => $r->{'sort1_authcat'},
398         b_sort2_authcat => $r->{'sort2_authcat'},
399         b_active => $r->{budget_period_active},
400         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
401       };
402 }
403
404 @{$budget_loop} =
405   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
406
407 $template->param( budget_loop    => $budget_loop,);
408
409 output_html_with_http_headers $input, $cookie, $template->output;
410
411
412 sub import_batches_list {
413     my ($template) = @_;
414     my $batches = GetImportBatchRangeDesc();
415
416     my @list = ();
417     foreach my $batch (@$batches) {
418         if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
419             # check if there is at least 1 line still staged
420             my $import_records_count = Koha::Import::Records->search({
421                 import_batch_id => $batch->{'import_batch_id'},
422                 status          => $batch->{import_status}
423             })->count;
424             if ( $import_records_count ) {
425                 push @list, {
426                         import_batch_id => $batch->{'import_batch_id'},
427                         num_records => $batch->{'num_records'},
428                         num_items => $batch->{'num_items'},
429                         staged_date => $batch->{'upload_timestamp'},
430                         import_status => $batch->{'import_status'},
431                         file_name => $batch->{'file_name'},
432                         comments => $batch->{'comments'},
433                 };
434             } else {
435                 # if there are no more line to includes, set the status to imported
436                 # FIXME This should be removed in the future.
437                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
438             }
439         }
440     }
441     $template->param(batch_list => \@list); 
442     my $num_batches = GetNumberOfNonZ3950ImportBatches();
443     $template->param(num_results => $num_batches);
444 }
445
446 sub import_biblios_list {
447     my ($template, $import_batch_id) = @_;
448     my $batch = GetImportBatch($import_batch_id,'staged');
449     return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
450     my $import_records = Koha::Import::Records->search({
451         import_batch_id => $import_batch_id,
452         status => $batch->{import_status}
453     });
454     my @list = ();
455     my $item_error = 0;
456
457     my $ccodes = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' } ) };
458     my $locations = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
459     my $notforloans = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.notforloan' } ) };
460     # location list
461     my @locations;
462     foreach (sort keys %$locations) {
463         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
464     }
465     my @ccodes;
466     foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
467         push @ccodes, { code => $_, description => $ccodes->{$_} };
468     }
469     my @notforloans;
470     foreach (sort {$notforloans->{$a} cmp $notforloans->{$b}} keys %$notforloans) {
471         push @notforloans, { code => $_, description => $notforloans->{$_} };
472     }
473
474     my $biblio_count = 0;
475     while ( my $import_record = $import_records->next ) {
476         my $item_id = 1;
477         $biblio_count++;
478         my $match = GetImportRecordMatches($import_record->import_record_id, 1);
479         my %cellrecord = (
480             import_record_id => $import_record->import_record_id,
481             import_biblio => $import_record->import_biblio,
482             import  => 1,
483             status => $import_record->status,
484             record_sequence => $import_record->record_sequence,
485             overlay_status => $import_record->overlay_status,
486             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
487             match_citation     => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
488             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
489         );
490         my $marcrecord = $import_record->get_marc_record || die "couldn't translate marc information";
491
492         my $infos = get_infos_syspref('MarcFieldsToOrder', $marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2','replacementprice']);
493         my $price = $infos->{price};
494         my $replacementprice = $infos->{replacementprice};
495         my $quantity = $infos->{quantity};
496         my $budget_code = $infos->{budget_code};
497         my $discount = $infos->{discount};
498         my $sort1 = $infos->{sort1};
499         my $sort2 = $infos->{sort2};
500         my $budget_id;
501         if($budget_code) {
502             my $biblio_budget = GetBudgetByCode($budget_code);
503             if($biblio_budget) {
504                 $budget_id = $biblio_budget->{budget_id};
505             }
506         }
507
508         # Items
509         my @itemlist = ();
510         my $all_items_quantity = 0;
511         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']);
512         if ($alliteminfos != -1) {
513             foreach my $iteminfos (@$alliteminfos) {
514                 my $item_homebranch = $iteminfos->{homebranch};
515                 my $item_holdingbranch = $iteminfos->{holdingbranch};
516                 my $item_itype = $iteminfos->{itype};
517                 my $item_nonpublic_note = $iteminfos->{nonpublic_note};
518                 my $item_public_note = $iteminfos->{public_note};
519                 my $item_loc = $iteminfos->{loc};
520                 my $item_ccode = $iteminfos->{ccode};
521                 my $item_notforloan = $iteminfos->{notforloan};
522                 my $item_uri = $iteminfos->{uri};
523                 my $item_copyno = $iteminfos->{copyno};
524                 my $item_quantity = $iteminfos->{quantity} || 1;
525                 my $item_budget_code = $iteminfos->{budget_code};
526                 my $item_budget_id;
527                 if ( $iteminfos->{budget_code} ) {
528                     my $item_budget = GetBudgetByCode( $iteminfos->{budget_code} );
529                     if ( $item_budget ) {
530                         $item_budget_id = $item_budget->{budget_id};
531                     }
532                 }
533                 my $item_price = $iteminfos->{price};
534                 my $item_replacement_price = $iteminfos->{replacementprice};
535                 my $item_callnumber = $iteminfos->{itemcallnumber};
536
537                 for (my $i = 0; $i < $item_quantity; $i++) {
538
539                     my %itemrecord = (
540                         'item_id' => $item_id++,
541                         'biblio_count' => $biblio_count,
542                         'homebranch' => $item_homebranch,
543                         'holdingbranch' => $item_holdingbranch,
544                         'itype' => $item_itype,
545                         'nonpublic_note' => $item_nonpublic_note,
546                         'public_note' => $item_public_note,
547                         'loc' => $item_loc,
548                         'ccode' => $item_ccode,
549                         'notforloan' => $item_notforloan,
550                         'uri' => $item_uri,
551                         'copyno' => $item_copyno,
552                         'quantity' => $item_quantity,
553                         'budget_id' => $item_budget_id || $budget_id,
554                         'itemprice' => $item_price || $price,
555                         'replacementprice' => $item_replacement_price || $replacementprice,
556                         'itemcallnumber' => $item_callnumber,
557                     );
558                     $all_items_quantity++;
559                     push @itemlist, \%itemrecord;
560
561                 }
562             }
563
564             $cellrecord{'iteminfos'} = \@itemlist;
565         } else {
566             $cellrecord{'item_error'} = 1;
567         }
568         push @list, \%cellrecord;
569
570         if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
571             $cellrecord{price} = $price || '';
572             $cellrecord{replacementprice} = $replacementprice || '';
573             $cellrecord{quantity} = $quantity || '';
574             $cellrecord{budget_id} = $budget_id || '';
575             $cellrecord{discount} = $discount || '';
576             $cellrecord{sort1} = $sort1 || '';
577             $cellrecord{sort2} = $sort2 || '';
578         } else {
579             $cellrecord{quantity} = $all_items_quantity;
580         }
581
582     }
583     my $num_records = $batch->{'num_records'};
584     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
585     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
586     my $item_action = GetImportBatchItemAction($import_batch_id);
587     $template->param(import_biblio_list => \@list,
588                         num_results => $num_records,
589                         import_batch_id => $import_batch_id,
590                         "overlay_action_${overlay_action}" => 1,
591                         overlay_action => $overlay_action,
592                         "nomatch_action_${nomatch_action}" => 1,
593                         nomatch_action => $nomatch_action,
594                         "item_action_${item_action}" => 1,
595                         item_action => $item_action,
596                         item_error => $item_error,
597                         libraries => Koha::Libraries->search,
598                         locationloop => \@locations,
599                         itemtypes => Koha::ItemTypes->search,
600                         ccodeloop => \@ccodes,
601                         notforloanloop => \@notforloans,
602                     );
603     batch_info($template, $batch);
604 }
605
606 sub batch_info {
607     my ($template, $batch) = @_;
608     $template->param(batch_info => 1,
609                                       file_name => $batch->{'file_name'},
610                                           comments => $batch->{'comments'},
611                                           import_status => $batch->{'import_status'},
612                                           upload_timestamp => $batch->{'upload_timestamp'},
613                                           num_records => $batch->{'num_records'},
614                                           num_items => $batch->{'num_items'});
615     if ($batch->{'num_records'} > 0) {
616         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
617             $template->param(can_commit => 1);
618         }
619         if ($batch->{'import_status'} eq 'imported') {
620             $template->param(can_revert => 1);
621         }
622     }
623     if (defined $batch->{'matcher_id'}) {
624         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
625         if (defined $matcher) {
626             $template->param('current_matcher_id' => $batch->{'matcher_id'},
627                                               'current_matcher_code' => $matcher->code(),
628                                               'current_matcher_description' => $matcher->description());
629         }
630     }
631     add_matcher_list($batch->{'matcher_id'}, $template);
632 }
633
634 sub add_matcher_list {
635     my ($current_matcher_id, $template) = @_;
636     my @matchers = C4::Matcher::GetMatcherList();
637     if (defined $current_matcher_id) {
638         for (my $i = 0; $i <= $#matchers; $i++) {
639             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
640                 $matchers[$i]->{'selected'} = 1;
641             }
642         }
643     }
644     $template->param(available_matchers => \@matchers);
645 }
646
647 sub get_infos_syspref {
648     my ($syspref_name, $record, $field_list) = @_;
649     my $syspref = C4::Context->preference($syspref_name);
650     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
651     my $yaml = eval {
652         YAML::XS::Load(Encode::encode_utf8($syspref));
653     };
654     if ( $@ ) {
655         warn "Unable to parse $syspref syspref : $@";
656         return ();
657     }
658     my $r;
659     for my $field_name ( @$field_list ) {
660         next unless exists $yaml->{$field_name};
661         my @fields = split /\|/, $yaml->{$field_name};
662         for my $field ( @fields ) {
663             my ( $f, $sf ) = split /\$/, $field;
664             next unless $f and $sf;
665             if ( my $v = $record->subfield( $f, $sf ) ) {
666                 $r->{$field_name} = $v;
667             }
668             last if $yaml->{$field};
669         }
670     }
671     return $r;
672 }
673
674 sub equal_number_of_fields {
675     my ($tags_list, $record) = @_;
676     my $tag_fields_count;
677     for my $tag (@$tags_list) {
678         my @fields = $record->field($tag);
679         $tag_fields_count->{$tag} = scalar @fields;
680     }
681
682     my $tags_count;
683     foreach my $key ( keys %$tag_fields_count ) {
684         if ( $tag_fields_count->{$key} > 0 ) { # Having 0 of a field is ok
685             $tags_count //= $tag_fields_count->{$key}; # Start with the count from the first occurrence
686             return -1 if $tag_fields_count->{$key} != $tags_count; # All counts of various fields should be equal if they exist
687         }
688     }
689
690     return $tags_count;
691 }
692
693 sub get_infos_syspref_on_item {
694     my ($syspref_name, $record, $field_list) = @_;
695     my $syspref = C4::Context->preference($syspref_name);
696     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
697     my $yaml = eval {
698         YAML::XS::Load(Encode::encode_utf8($syspref));
699     };
700     if ( $@ ) {
701         warn "Unable to parse $syspref syspref : $@";
702         return ();
703     }
704     my @result;
705     my @tags_list;
706
707     # Check tags in syspref definition
708     for my $field_name ( @$field_list ) {
709         next unless exists $yaml->{$field_name};
710         my @fields = split /\|/, $yaml->{$field_name};
711         for my $field ( @fields ) {
712             my ( $f, $sf ) = split /\$/, $field;
713             next unless $f and $sf;
714             push @tags_list, $f;
715         }
716     }
717     @tags_list = List::MoreUtils::uniq(@tags_list);
718
719     my $tags_count = equal_number_of_fields(\@tags_list, $record);
720     # Return if the number of these fields in the record is not the same.
721     return -1 if $tags_count == -1;
722
723     # Gather the fields
724     my $fields_hash;
725     foreach my $tag (@tags_list) {
726         my @tmp_fields;
727         foreach my $field ($record->field($tag)) {
728             push @tmp_fields, $field;
729         }
730         $fields_hash->{$tag} = \@tmp_fields;
731     }
732
733     for (my $i = 0; $i < $tags_count; $i++) {
734         my $r;
735         for my $field_name ( @$field_list ) {
736             next unless exists $yaml->{$field_name};
737             my @fields = split /\|/, $yaml->{$field_name};
738             for my $field ( @fields ) {
739                 my ( $f, $sf ) = split /\$/, $field;
740                 next unless $f and $sf;
741                 my $v = $fields_hash->{$f}[$i] ? $fields_hash->{$f}[$i]->subfield( $sf ) : undef;
742                 $r->{$field_name} = $v if (defined $v);
743                 last if $yaml->{$field};
744             }
745         }
746         push @result, $r;
747     }
748     return \@result;
749 }