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