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