Bug 32171: Store after populating order
[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 );
295                     $order->populate_with_prices_for_ordering();
296                     $order->populate_with_prices_for_receiving();
297                     $order->store;
298                     $order->add_item( $_ ) for @{ $budget_hash->{$budget_id}->{itemnumbers} };
299                 }
300             }
301         } else {
302             # 3rd add order
303             my $patron = Koha::Patrons->find( $loggedinuser );
304             # get quantity in the MARC record (1 if none)
305             my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
306             my %orderinfo = (
307                 biblionumber       => $biblionumber,
308                 basketno           => $cgiparams->{'basketno'},
309                 quantity           => $c_quantity,
310                 branchcode         => $patron->branchcode,
311                 budget_id          => $c_budget_id,
312                 uncertainprice     => 1,
313                 sort1              => $c_sort1,
314                 sort2              => $c_sort2,
315                 order_internalnote => $cgiparams->{'all_order_internalnote'},
316                 order_vendornote   => $cgiparams->{'all_order_vendornote'},
317                 currency           => $cgiparams->{'all_currency'},
318                 replacementprice   => $c_replacement_price,
319             );
320             # get the price if there is one.
321             if ($c_price){
322                 # in France, the cents separator is the , but sometimes, ppl use a .
323                 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
324                 $c_price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
325                 $c_price = Koha::Number::Price->new($c_price)->unformat;
326                 $orderinfo{tax_rate_on_ordering} = $bookseller->tax_rate;
327                 $orderinfo{tax_rate_on_receiving} = $bookseller->tax_rate;
328                 my $c = $c_discount ? $c_discount : $bookseller->discount;
329                 $orderinfo{discount} = $c;
330                 if ( $c ) {
331                     $orderinfo{ecost} = $c_price * ( 1 - $c / 100 );
332                     $orderinfo{rrp}   = $c_price;
333                 }
334                 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
335                 $orderinfo{unitprice} = $orderinfo{ecost};
336             } else {
337                 $orderinfo{listprice} = 0;
338             }
339
340         # remove uncertainprice flag if we have found a price in the MARC record
341         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
342
343         my $order = Koha::Acquisition::Order->new( \%orderinfo );
344         $order->populate_with_prices_for_ordering();
345         $order->populate_with_prices_for_receiving();
346         $order->store;
347
348         # 4th, add items if applicable
349         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
350         # this is not optimised, but it's working !
351         if ( $basket->effective_create_items eq 'ordering' && !$basket->is_standing ) {
352             my @tags         = $input->multi_param('tag');
353             my @subfields    = $input->multi_param('subfield');
354             my @field_values = $input->multi_param('field_value');
355             my @serials      = $input->multi_param('serial');
356             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values );
357             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
358             for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
359                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
360                 $order->add_item( $itemnumber );
361                 }
362             } else {
363                 $import_record->status( 'imported' )->store;
364             }
365         }
366         $imported++;
367     }
368
369     # If all bibliographic records from the batch have been imported we modifying the status of the batch accordingly
370     SetImportBatchStatus( $import_batch_id, 'imported' )
371         if Koha::Import::Records->search({import_batch_id => $import_batch_id, status => 'imported' })->count
372            == Koha::Import::Records->search({import_batch_id => $import_batch_id})->count;
373
374     # go to basket page
375     if ( $imported ) {
376         print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
377     } else {
378         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");
379     }
380     exit;
381 }
382
383 my $budgets = GetBudgets();
384 my $budget_id = @$budgets[0]->{'budget_id'};
385 # build bookfund list
386 my $patron = Koha::Patrons->find( $loggedinuser )->unblessed;
387 my $budget = GetBudget($budget_id);
388
389 # build budget list
390 my $budget_loop = [];
391 my $budgets_hierarchy = GetBudgetHierarchy;
392 foreach my $r ( @{$budgets_hierarchy} ) {
393     next unless (CanUserUseBudget($patron, $r, $userflags));
394     push @{$budget_loop},
395       { b_id  => $r->{budget_id},
396         b_txt => $r->{budget_name},
397         b_code => $r->{budget_code},
398         b_sort1_authcat => $r->{'sort1_authcat'},
399         b_sort2_authcat => $r->{'sort2_authcat'},
400         b_active => $r->{budget_period_active},
401         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
402       };
403 }
404
405 @{$budget_loop} =
406   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
407
408 $template->param( budget_loop    => $budget_loop,);
409
410 output_html_with_http_headers $input, $cookie, $template->output;
411
412
413 sub import_batches_list {
414     my ($template) = @_;
415     my $batches = GetImportBatchRangeDesc();
416
417     my @list = ();
418     foreach my $batch (@$batches) {
419         if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
420             # check if there is at least 1 line still staged
421             my $import_records_count = Koha::Import::Records->search({
422                 import_batch_id => $batch->{'import_batch_id'},
423                 status          => $batch->{import_status}
424             })->count;
425             if ( $import_records_count ) {
426                 push @list, {
427                         import_batch_id => $batch->{'import_batch_id'},
428                         num_records => $batch->{'num_records'},
429                         num_items => $batch->{'num_items'},
430                         staged_date => $batch->{'upload_timestamp'},
431                         import_status => $batch->{'import_status'},
432                         file_name => $batch->{'file_name'},
433                         comments => $batch->{'comments'},
434                 };
435             } else {
436                 # if there are no more line to includes, set the status to imported
437                 # FIXME This should be removed in the future.
438                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
439             }
440         }
441     }
442     $template->param(batch_list => \@list); 
443     my $num_batches = GetNumberOfNonZ3950ImportBatches();
444     $template->param(num_results => $num_batches);
445 }
446
447 sub import_biblios_list {
448     my ($template, $import_batch_id) = @_;
449     my $batch = GetImportBatch($import_batch_id,'staged');
450     return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
451     my $import_records = Koha::Import::Records->search({
452         import_batch_id => $import_batch_id,
453         status => $batch->{import_status}
454     });
455     my @list = ();
456     my $item_error = 0;
457
458     my $ccodes = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' } ) };
459     my $locations = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
460     my $notforloans = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.notforloan' } ) };
461     # location list
462     my @locations;
463     foreach (sort keys %$locations) {
464         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
465     }
466     my @ccodes;
467     foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
468         push @ccodes, { code => $_, description => $ccodes->{$_} };
469     }
470     my @notforloans;
471     foreach (sort {$notforloans->{$a} cmp $notforloans->{$b}} keys %$notforloans) {
472         push @notforloans, { code => $_, description => $notforloans->{$_} };
473     }
474
475     my $biblio_count = 0;
476     while ( my $import_record = $import_records->next ) {
477         my $item_id = 1;
478         $biblio_count++;
479         my $match = GetImportRecordMatches($import_record->import_record_id, 1);
480         my %cellrecord = (
481             import_record_id => $import_record->import_record_id,
482             import_biblio => $import_record->import_biblio,
483             import  => 1,
484             status => $import_record->status,
485             record_sequence => $import_record->record_sequence,
486             overlay_status => $import_record->overlay_status,
487             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
488             match_citation     => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
489             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
490         );
491         my $marcrecord = $import_record->get_marc_record || die "couldn't translate marc information";
492
493         my $infos = get_infos_syspref('MarcFieldsToOrder', $marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2','replacementprice']);
494         my $price = $infos->{price};
495         my $replacementprice = $infos->{replacementprice};
496         my $quantity = $infos->{quantity};
497         my $budget_code = $infos->{budget_code};
498         my $discount = $infos->{discount};
499         my $sort1 = $infos->{sort1};
500         my $sort2 = $infos->{sort2};
501         my $budget_id;
502         if($budget_code) {
503             my $biblio_budget = GetBudgetByCode($budget_code);
504             if($biblio_budget) {
505                 $budget_id = $biblio_budget->{budget_id};
506             }
507         }
508
509         # Items
510         my @itemlist = ();
511         my $all_items_quantity = 0;
512         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']);
513         if ($alliteminfos != -1) {
514             foreach my $iteminfos (@$alliteminfos) {
515                 my $item_homebranch = $iteminfos->{homebranch};
516                 my $item_holdingbranch = $iteminfos->{holdingbranch};
517                 my $item_itype = $iteminfos->{itype};
518                 my $item_nonpublic_note = $iteminfos->{nonpublic_note};
519                 my $item_public_note = $iteminfos->{public_note};
520                 my $item_loc = $iteminfos->{loc};
521                 my $item_ccode = $iteminfos->{ccode};
522                 my $item_notforloan = $iteminfos->{notforloan};
523                 my $item_uri = $iteminfos->{uri};
524                 my $item_copyno = $iteminfos->{copyno};
525                 my $item_quantity = $iteminfos->{quantity} || 1;
526                 my $item_budget_code = $iteminfos->{budget_code};
527                 my $item_budget_id;
528                 if ( $iteminfos->{budget_code} ) {
529                     my $item_budget = GetBudgetByCode( $iteminfos->{budget_code} );
530                     if ( $item_budget ) {
531                         $item_budget_id = $item_budget->{budget_id};
532                     }
533                 }
534                 my $item_price = $iteminfos->{price};
535                 my $item_replacement_price = $iteminfos->{replacementprice};
536                 my $item_callnumber = $iteminfos->{itemcallnumber};
537
538                 for (my $i = 0; $i < $item_quantity; $i++) {
539
540                     my %itemrecord = (
541                         'item_id' => $item_id++,
542                         'biblio_count' => $biblio_count,
543                         'homebranch' => $item_homebranch,
544                         'holdingbranch' => $item_holdingbranch,
545                         'itype' => $item_itype,
546                         'nonpublic_note' => $item_nonpublic_note,
547                         'public_note' => $item_public_note,
548                         'loc' => $item_loc,
549                         'ccode' => $item_ccode,
550                         'notforloan' => $item_notforloan,
551                         'uri' => $item_uri,
552                         'copyno' => $item_copyno,
553                         'quantity' => $item_quantity,
554                         'budget_id' => $item_budget_id || $budget_id,
555                         'itemprice' => $item_price || $price,
556                         'replacementprice' => $item_replacement_price || $replacementprice,
557                         'itemcallnumber' => $item_callnumber,
558                     );
559                     $all_items_quantity++;
560                     push @itemlist, \%itemrecord;
561
562                 }
563             }
564
565             $cellrecord{'iteminfos'} = \@itemlist;
566         } else {
567             $cellrecord{'item_error'} = 1;
568         }
569         push @list, \%cellrecord;
570
571         if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
572             $cellrecord{price} = $price || '';
573             $cellrecord{replacementprice} = $replacementprice || '';
574             $cellrecord{quantity} = $quantity || '';
575             $cellrecord{budget_id} = $budget_id || '';
576             $cellrecord{discount} = $discount || '';
577             $cellrecord{sort1} = $sort1 || '';
578             $cellrecord{sort2} = $sort2 || '';
579         } else {
580             $cellrecord{quantity} = $all_items_quantity;
581         }
582
583     }
584     my $num_records = $batch->{'num_records'};
585     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
586     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
587     my $item_action = GetImportBatchItemAction($import_batch_id);
588     $template->param(import_biblio_list => \@list,
589                         num_results => $num_records,
590                         import_batch_id => $import_batch_id,
591                         "overlay_action_${overlay_action}" => 1,
592                         overlay_action => $overlay_action,
593                         "nomatch_action_${nomatch_action}" => 1,
594                         nomatch_action => $nomatch_action,
595                         "item_action_${item_action}" => 1,
596                         item_action => $item_action,
597                         item_error => $item_error,
598                         libraries => Koha::Libraries->search,
599                         locationloop => \@locations,
600                         itemtypes => Koha::ItemTypes->search,
601                         ccodeloop => \@ccodes,
602                         notforloanloop => \@notforloans,
603                     );
604     batch_info($template, $batch);
605 }
606
607 sub batch_info {
608     my ($template, $batch) = @_;
609     $template->param(batch_info => 1,
610                                       file_name => $batch->{'file_name'},
611                                           comments => $batch->{'comments'},
612                                           import_status => $batch->{'import_status'},
613                                           upload_timestamp => $batch->{'upload_timestamp'},
614                                           num_records => $batch->{'num_records'},
615                                           num_items => $batch->{'num_items'});
616     if ($batch->{'num_records'} > 0) {
617         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
618             $template->param(can_commit => 1);
619         }
620         if ($batch->{'import_status'} eq 'imported') {
621             $template->param(can_revert => 1);
622         }
623     }
624     if (defined $batch->{'matcher_id'}) {
625         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
626         if (defined $matcher) {
627             $template->param('current_matcher_id' => $batch->{'matcher_id'},
628                                               'current_matcher_code' => $matcher->code(),
629                                               'current_matcher_description' => $matcher->description());
630         }
631     }
632     add_matcher_list($batch->{'matcher_id'}, $template);
633 }
634
635 sub add_matcher_list {
636     my ($current_matcher_id, $template) = @_;
637     my @matchers = C4::Matcher::GetMatcherList();
638     if (defined $current_matcher_id) {
639         for (my $i = 0; $i <= $#matchers; $i++) {
640             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
641                 $matchers[$i]->{'selected'} = 1;
642             }
643         }
644     }
645     $template->param(available_matchers => \@matchers);
646 }
647
648 sub get_infos_syspref {
649     my ($syspref_name, $record, $field_list) = @_;
650     my $syspref = C4::Context->preference($syspref_name);
651     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
652     my $yaml = eval {
653         YAML::XS::Load(Encode::encode_utf8($syspref));
654     };
655     if ( $@ ) {
656         warn "Unable to parse $syspref syspref : $@";
657         return ();
658     }
659     my $r;
660     for my $field_name ( @$field_list ) {
661         next unless exists $yaml->{$field_name};
662         my @fields = split /\|/, $yaml->{$field_name};
663         for my $field ( @fields ) {
664             my ( $f, $sf ) = split /\$/, $field;
665             next unless $f and $sf;
666             if ( my $v = $record->subfield( $f, $sf ) ) {
667                 $r->{$field_name} = $v;
668             }
669             last if $yaml->{$field};
670         }
671     }
672     return $r;
673 }
674
675 sub equal_number_of_fields {
676     my ($tags_list, $record) = @_;
677     my $tag_fields_count;
678     for my $tag (@$tags_list) {
679         my @fields = $record->field($tag);
680         $tag_fields_count->{$tag} = scalar @fields;
681     }
682
683     my $tags_count;
684     foreach my $key ( keys %$tag_fields_count ) {
685         if ( $tag_fields_count->{$key} > 0 ) { # Having 0 of a field is ok
686             $tags_count //= $tag_fields_count->{$key}; # Start with the count from the first occurrence
687             return -1 if $tag_fields_count->{$key} != $tags_count; # All counts of various fields should be equal if they exist
688         }
689     }
690
691     return $tags_count;
692 }
693
694 sub get_infos_syspref_on_item {
695     my ($syspref_name, $record, $field_list) = @_;
696     my $syspref = C4::Context->preference($syspref_name);
697     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
698     my $yaml = eval {
699         YAML::XS::Load(Encode::encode_utf8($syspref));
700     };
701     if ( $@ ) {
702         warn "Unable to parse $syspref syspref : $@";
703         return ();
704     }
705     my @result;
706     my @tags_list;
707
708     # Check tags in syspref definition
709     for my $field_name ( @$field_list ) {
710         next unless exists $yaml->{$field_name};
711         my @fields = split /\|/, $yaml->{$field_name};
712         for my $field ( @fields ) {
713             my ( $f, $sf ) = split /\$/, $field;
714             next unless $f and $sf;
715             push @tags_list, $f;
716         }
717     }
718     @tags_list = List::MoreUtils::uniq(@tags_list);
719
720     my $tags_count = equal_number_of_fields(\@tags_list, $record);
721     # Return if the number of these fields in the record is not the same.
722     return -1 if $tags_count == -1;
723
724     # Gather the fields
725     my $fields_hash;
726     foreach my $tag (@tags_list) {
727         my @tmp_fields;
728         foreach my $field ($record->field($tag)) {
729             push @tmp_fields, $field;
730         }
731         $fields_hash->{$tag} = \@tmp_fields;
732     }
733
734     for (my $i = 0; $i < $tags_count; $i++) {
735         my $r;
736         for my $field_name ( @$field_list ) {
737             next unless exists $yaml->{$field_name};
738             my @fields = split /\|/, $yaml->{$field_name};
739             for my $field ( @fields ) {
740                 my ( $f, $sf ) = split /\$/, $field;
741                 next unless $f and $sf;
742                 my $v = $fields_hash->{$f}[$i] ? $fields_hash->{$f}[$i]->subfield( $sf ) : undef;
743                 $r->{$field_name} = $v if (defined $v);
744                 last if $yaml->{$field};
745             }
746         }
747         push @result, $r;
748     }
749     return \@result;
750 }