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