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