]> git.koha-community.org Git - koha.git/blob - acqui/addorderiso2709.pl
Bug 35892: Populate order price using GetMarcPrice if no price specified
[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('replacementprice_' . $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         if($budget_code) {
512             my $biblio_budget = GetBudgetByCode($budget_code);
513             if($biblio_budget) {
514                 $budget_id = $biblio_budget->{budget_id};
515             }
516         }
517
518         # Items
519         my @itemlist = ();
520         my $all_items_quantity = 0;
521         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']);
522         if ($alliteminfos != -1) {
523             foreach my $iteminfos (@$alliteminfos) {
524                 my $item_homebranch = $iteminfos->{homebranch};
525                 my $item_holdingbranch = $iteminfos->{holdingbranch};
526                 my $item_itype = $iteminfos->{itype};
527                 my $item_nonpublic_note = $iteminfos->{nonpublic_note};
528                 my $item_public_note = $iteminfos->{public_note};
529                 my $item_loc = $iteminfos->{loc};
530                 my $item_ccode = $iteminfos->{ccode};
531                 my $item_notforloan = $iteminfos->{notforloan};
532                 my $item_uri = $iteminfos->{uri};
533                 my $item_copyno = $iteminfos->{copyno};
534                 my $item_quantity = $iteminfos->{quantity} || 1;
535                 my $item_budget_code = $iteminfos->{budget_code};
536                 my $item_budget_id;
537                 if ( $iteminfos->{budget_code} ) {
538                     my $item_budget = GetBudgetByCode( $iteminfos->{budget_code} );
539                     if ( $item_budget ) {
540                         $item_budget_id = $item_budget->{budget_id};
541                     }
542                 }
543                 my $item_price = $iteminfos->{price};
544                 my $item_replacement_price = $iteminfos->{replacementprice};
545                 my $item_callnumber = $iteminfos->{itemcallnumber};
546
547                 for (my $i = 0; $i < $item_quantity; $i++) {
548
549                     my %itemrecord = (
550                         'item_id' => $item_id++,
551                         'biblio_count' => $biblio_count,
552                         'homebranch' => $item_homebranch,
553                         'holdingbranch' => $item_holdingbranch,
554                         'itype' => $item_itype,
555                         'nonpublic_note' => $item_nonpublic_note,
556                         'public_note' => $item_public_note,
557                         'loc' => $item_loc,
558                         'ccode' => $item_ccode,
559                         'notforloan' => $item_notforloan,
560                         'uri' => $item_uri,
561                         'copyno' => $item_copyno,
562                         'quantity' => $item_quantity,
563                         'budget_id' => $item_budget_id || $budget_id,
564                         'itemprice' => $item_price || $price,
565                         'replacementprice' => $item_replacement_price || $replacementprice,
566                         'itemcallnumber' => $item_callnumber,
567                     );
568                     $all_items_quantity++;
569                     push @itemlist, \%itemrecord;
570
571                 }
572             }
573
574             $cellrecord{'iteminfos'} = \@itemlist;
575         } else {
576             $cellrecord{'item_error'} = 1;
577         }
578         push @list, \%cellrecord;
579
580         # If MarcItemFieldsToOrder is not set, we use MarcFieldsToOrder to populate the order form.
581         if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
582             $cellrecord{price} = $price || '';
583             $cellrecord{replacementprice} = $replacementprice || '';
584             $cellrecord{quantity} = $quantity || '';
585             $cellrecord{budget_id} = $budget_id || '';
586         } else {
587             # When using MarcItemFields to order we want the order to have the same quantity as total items
588             $cellrecord{quantity} = $all_items_quantity;
589         }
590         # The fields discount, sort1, and sort2 only exist at the order level, so always use MarcItemFieldsToOrder
591         $cellrecord{discount} = $discount || '';
592         $cellrecord{sort1} = $sort1 || '';
593         $cellrecord{sort2} = $sort2 || '';
594
595     }
596     my $num_records = $batch->{'num_records'};
597     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
598     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
599     my $item_action = GetImportBatchItemAction($import_batch_id);
600     $template->param(import_biblio_list => \@list,
601                         num_results => $num_records,
602                         import_batch_id => $import_batch_id,
603                         "overlay_action_${overlay_action}" => 1,
604                         overlay_action => $overlay_action,
605                         "nomatch_action_${nomatch_action}" => 1,
606                         nomatch_action => $nomatch_action,
607                         "item_action_${item_action}" => 1,
608                         item_action => $item_action,
609                         item_error => $item_error,
610                         libraries => Koha::Libraries->search,
611                         locationloop => \@locations,
612                         itemtypes => Koha::ItemTypes->search,
613                         ccodeloop => \@ccodes,
614                         notforloanloop => \@notforloans,
615                     );
616     batch_info($template, $batch);
617 }
618
619 sub batch_info {
620     my ($template, $batch) = @_;
621     $template->param(batch_info => 1,
622                                       file_name => $batch->{'file_name'},
623                                           comments => $batch->{'comments'},
624                                           import_status => $batch->{'import_status'},
625                                           upload_timestamp => $batch->{'upload_timestamp'},
626                                           num_records => $batch->{'num_records'},
627                                           num_items => $batch->{'num_items'});
628     if ($batch->{'num_records'} > 0) {
629         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
630             $template->param(can_commit => 1);
631         }
632         if ($batch->{'import_status'} eq 'imported') {
633             $template->param(can_revert => 1);
634         }
635     }
636     if (defined $batch->{'matcher_id'}) {
637         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
638         if (defined $matcher) {
639             $template->param('current_matcher_id' => $batch->{'matcher_id'},
640                                               'current_matcher_code' => $matcher->code(),
641                                               'current_matcher_description' => $matcher->description());
642         }
643     }
644     add_matcher_list($batch->{'matcher_id'}, $template);
645 }
646
647 sub add_matcher_list {
648     my ($current_matcher_id, $template) = @_;
649     my @matchers = C4::Matcher::GetMatcherList();
650     if (defined $current_matcher_id) {
651         for (my $i = 0; $i <= $#matchers; $i++) {
652             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
653                 $matchers[$i]->{'selected'} = 1;
654             }
655         }
656     }
657     $template->param(available_matchers => \@matchers);
658 }
659
660 sub get_infos_syspref {
661     my ($syspref_name, $record, $field_list) = @_;
662     my $syspref = C4::Context->preference($syspref_name);
663     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
664     my $yaml = eval {
665         YAML::XS::Load(Encode::encode_utf8($syspref));
666     };
667     if ( $@ ) {
668         warn "Unable to parse $syspref syspref : $@";
669         return ();
670     }
671     my $r;
672     for my $field_name ( @$field_list ) {
673         next unless exists $yaml->{$field_name};
674         my @fields = split /\|/, $yaml->{$field_name};
675         for my $field ( @fields ) {
676             my ( $f, $sf ) = split /\$/, $field;
677             next unless $f and $sf;
678             if ( my $v = $record->subfield( $f, $sf ) ) {
679                 $r->{$field_name} = $v;
680             }
681             last if $yaml->{$field};
682         }
683     }
684     return $r;
685 }
686
687 sub equal_number_of_fields {
688     my ($tags_list, $record) = @_;
689     my $tag_fields_count;
690     for my $tag (@$tags_list) {
691         my @fields = $record->field($tag);
692         $tag_fields_count->{$tag} = scalar @fields;
693     }
694
695     my $tags_count;
696     foreach my $key ( keys %$tag_fields_count ) {
697         if ( $tag_fields_count->{$key} > 0 ) { # Having 0 of a field is ok
698             $tags_count //= $tag_fields_count->{$key}; # Start with the count from the first occurrence
699             return -1 if $tag_fields_count->{$key} != $tags_count; # All counts of various fields should be equal if they exist
700         }
701     }
702
703     return $tags_count;
704 }
705
706 sub get_infos_syspref_on_item {
707     my ($syspref_name, $record, $field_list) = @_;
708     my $syspref = C4::Context->preference($syspref_name);
709     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
710     my $yaml = eval {
711         YAML::XS::Load(Encode::encode_utf8($syspref));
712     };
713     if ( $@ ) {
714         warn "Unable to parse $syspref syspref : $@";
715         return ();
716     }
717     my @result;
718     my @tags_list;
719
720     # Check tags in syspref definition
721     for my $field_name ( @$field_list ) {
722         next unless exists $yaml->{$field_name};
723         my @fields = split /\|/, $yaml->{$field_name};
724         for my $field ( @fields ) {
725             my ( $f, $sf ) = split /\$/, $field;
726             next unless $f and $sf;
727             push @tags_list, $f;
728         }
729     }
730     @tags_list = List::MoreUtils::uniq(@tags_list);
731
732     my $tags_count = equal_number_of_fields(\@tags_list, $record);
733     # Return if the number of these fields in the record is not the same.
734     return -1 if $tags_count == -1;
735
736     # Gather the fields
737     my $fields_hash;
738     foreach my $tag (@tags_list) {
739         my @tmp_fields;
740         foreach my $field ($record->field($tag)) {
741             push @tmp_fields, $field;
742         }
743         $fields_hash->{$tag} = \@tmp_fields;
744     }
745
746     for (my $i = 0; $i < $tags_count; $i++) {
747         my $r;
748         for my $field_name ( @$field_list ) {
749             next unless exists $yaml->{$field_name};
750             my @fields = split /\|/, $yaml->{$field_name};
751             for my $field ( @fields ) {
752                 my ( $f, $sf ) = split /\$/, $field;
753                 next unless $f and $sf;
754                 my $v = $fields_hash->{$f}[$i] ? $fields_hash->{$f}[$i]->subfield( $sf ) : undef;
755                 $r->{$field_name} = $v if (defined $v);
756                 last if $yaml->{$field};
757             }
758         }
759         push @result, $r;
760     }
761     return \@result;
762 }