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