Bug 17600: Standardize our EXPORT_OK
[srvgit] / 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 sub 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 sub 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     # get currencies (for change rates calcs if needed)
100     my @currencies = Koha::Acquisition::Currencies->search;
101
102     $template->param("batch_details" => 1,
103                      "basketno"      => $cgiparams->{'basketno'},
104                      currencies => \@currencies,
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( '', '', '', 'ACQ' );
112
113         #     warn "==> ".Data::Dumper::Dumper($cell);
114         unless ($cell) {
115             $cell = PrepareItemrecordDisplay( '', '', '', '' );
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 $biblios = GetImportRecordsRange($import_batch_id);
141     my $duplinbatch;
142     my $imported = 0;
143     my @import_record_id_selected = $input->multi_param("import_record_id");
144     my @quantities = $input->multi_param('quantity');
145     my @prices = $input->multi_param('price');
146     my @orderreplacementprices = $input->multi_param('replacementprice');
147     my @budgets_id = $input->multi_param('budget_id');
148     my @discount = $input->multi_param('discount');
149     my @sort1 = $input->multi_param('sort1');
150     my @sort2 = $input->multi_param('sort2');
151     my $matcher_id = $input->param('matcher_id');
152     my $active_currency = Koha::Acquisition::Currencies->get_active;
153     my $biblio_count = 0;
154     for my $biblio (@$biblios){
155         $biblio_count++;
156         my $duplifound = 0;
157         # Check if this import_record_id was selected
158         next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
159         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
160         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
161         my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
162         my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
163         my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
164         my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
165         my $c_discount = shift ( @discount);
166         $c_discount = $c_discount / 100 if $c_discount > 1;
167         my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
168         my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
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 $c = $c_discount ? $c_discount : $bookseller->discount / 100;
278                         $orderinfo{discount} = $c;
279                         if ( $c_discount ) {
280                             $orderinfo{ecost} = $price;
281                             $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
282                         } else {
283                             $orderinfo{ecost} = $price * ( 1 - $c );
284                             $orderinfo{rrp}   = $price;
285                         }
286                         $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
287                         $orderinfo{unitprice} = $orderinfo{ecost};
288                         $orderinfo{total} = $orderinfo{ecost} * $infos->{quantity};
289                     } else {
290                         $orderinfo{listprice} = 0;
291                     }
292                     $orderinfo{replacementprice} = $infos->{replacementprice} || 0;
293
294                     # remove uncertainprice flag if we have found a price in the MARC record
295                     $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
296
297                     %orderinfo = %{
298                         C4::Acquisition::populate_order_with_prices(
299                             {
300                                 order        => \%orderinfo,
301                                 booksellerid => $booksellerid,
302                                 ordering     => 1,
303                                 receiving    => 1,
304                             }
305                         )
306                     };
307
308                     my $order = Koha::Acquisition::Order->new( \%orderinfo )->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   => shift( @orderreplacementprices ),
330             );
331             # get the price if there is one.
332             my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
333             if ($price){
334                 # in France, the cents separator is the , but sometimes, ppl use a .
335                 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
336                 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
337                 $price = Koha::Number::Price->new($price)->unformat;
338                 $orderinfo{tax_rate} = $bookseller->tax_rate;
339                 my $c = $c_discount ? $c_discount : $bookseller->discount / 100;
340                 $orderinfo{discount} = $c;
341                 if ( $c_discount ) {
342                     $orderinfo{ecost} = $price;
343                     $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
344                 } else {
345                     $orderinfo{ecost} = $price * ( 1 - $c );
346                     $orderinfo{rrp}   = $price;
347                 }
348                 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
349                 $orderinfo{unitprice} = $orderinfo{ecost};
350                 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
351             } else {
352                 $orderinfo{listprice} = 0;
353             }
354
355         # remove uncertainprice flag if we have found a price in the MARC record
356         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
357
358         %orderinfo = %{
359             C4::Acquisition::populate_order_with_prices(
360                 {
361                     order        => \%orderinfo,
362                     booksellerid => $booksellerid,
363                     ordering     => 1,
364                     receiving    => 1,
365                 }
366             )
367         };
368
369         my $order = Koha::Acquisition::Order->new( \%orderinfo )->store;
370
371         # 4th, add items if applicable
372         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
373         # this is not optimised, but it's working !
374         if ( $basket->effective_create_items eq 'ordering' && !$basket->is_standing ) {
375             my @tags         = $input->multi_param('tag');
376             my @subfields    = $input->multi_param('subfield');
377             my @field_values = $input->multi_param('field_value');
378             my @serials      = $input->multi_param('serial');
379             my @ind_tag   = $input->multi_param('ind_tag');
380             my @indicator = $input->multi_param('indicator');
381             my $item;
382             push @{ $item->{tags} },         $tags[0];
383             push @{ $item->{subfields} },    $subfields[0];
384             push @{ $item->{field_values} }, $field_values[0];
385             push @{ $item->{ind_tag} },      $ind_tag[0];
386             push @{ $item->{indicator} },    $indicator[0];
387             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@indicator, \@ind_tag );
388             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
389             for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
390                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
391                 $order->add_item( $itemnumber );
392                 }
393             } else {
394                 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
395             }
396         }
397         $imported++;
398     }
399
400     # If all bibliographic records from the batch have been imported we modifying the status of the batch accordingly
401     SetImportBatchStatus( $import_batch_id, 'imported' )
402         if    @{ GetImportRecordsRange( $import_batch_id, undef, undef, 'imported' )}
403            == @{ GetImportRecordsRange( $import_batch_id )};
404
405     # go to basket page
406     if ( $imported ) {
407         print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
408     } else {
409         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");
410     }
411     exit;
412 }
413
414 my $budgets = GetBudgets();
415 my $budget_id = @$budgets[0]->{'budget_id'};
416 # build bookfund list
417 my $patron = Koha::Patrons->find( $loggedinuser )->unblessed;
418 my $budget = GetBudget($budget_id);
419
420 # build budget list
421 my $budget_loop = [];
422 my $budgets_hierarchy = GetBudgetHierarchy;
423 foreach my $r ( @{$budgets_hierarchy} ) {
424     next unless (CanUserUseBudget($patron, $r, $userflags));
425     push @{$budget_loop},
426       { b_id  => $r->{budget_id},
427         b_txt => $r->{budget_name},
428         b_code => $r->{budget_code},
429         b_sort1_authcat => $r->{'sort1_authcat'},
430         b_sort2_authcat => $r->{'sort2_authcat'},
431         b_active => $r->{budget_period_active},
432         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
433       };
434 }
435
436 @{$budget_loop} =
437   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
438
439 $template->param( budget_loop    => $budget_loop,);
440
441 output_html_with_http_headers $input, $cookie, $template->output;
442
443
444 sub import_batches_list {
445     my ($template) = @_;
446     my $batches = GetImportBatchRangeDesc();
447
448     my @list = ();
449     foreach my $batch (@$batches) {
450         if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
451             # check if there is at least 1 line still staged
452             my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
453             if (scalar @$stagedList) {
454                 push @list, {
455                         import_batch_id => $batch->{'import_batch_id'},
456                         num_records => $batch->{'num_records'},
457                         num_items => $batch->{'num_items'},
458                         staged_date => $batch->{'upload_timestamp'},
459                         import_status => $batch->{'import_status'},
460                         file_name => $batch->{'file_name'},
461                         comments => $batch->{'comments'},
462                 };
463             } else {
464                 # if there are no more line to includes, set the status to imported
465                 # FIXME This should be removed in the future.
466                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
467             }
468         }
469     }
470     $template->param(batch_list => \@list); 
471     my $num_batches = GetNumberOfNonZ3950ImportBatches();
472     $template->param(num_results => $num_batches);
473 }
474
475 sub import_biblios_list {
476     my ($template, $import_batch_id) = @_;
477     my $batch = GetImportBatch($import_batch_id,'staged');
478     return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
479     my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
480     my @list = ();
481     my $item_error = 0;
482
483     my $ccodes = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' } ) };
484     my $locations = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
485     my $notforloans = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.notforloan' } ) };
486     # location list
487     my @locations;
488     foreach (sort keys %$locations) {
489         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
490     }
491     my @ccodes;
492     foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
493         push @ccodes, { code => $_, description => $ccodes->{$_} };
494     }
495     my @notforloans;
496     foreach (sort {$notforloans->{$a} cmp $notforloans->{$b}} keys %$notforloans) {
497         push @notforloans, { code => $_, description => $notforloans->{$_} };
498     }
499
500     my $biblio_count = 0;
501     foreach my $biblio (@$biblios) {
502         my $item_id = 1;
503         $biblio_count++;
504         my $citation = $biblio->{'title'};
505         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
506         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
507         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
508         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
509         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
510         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
511         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
512         my %cellrecord = (
513             import_record_id => $biblio->{'import_record_id'},
514             citation => $citation,
515             import  => 1,
516             status => $biblio->{'status'},
517             record_sequence => $biblio->{'record_sequence'},
518             overlay_status => $biblio->{'overlay_status'},
519             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
520             match_citation     => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
521             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
522         );
523         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
524         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
525
526         my $infos = get_infos_syspref('MarcFieldsToOrder', $marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2','replacementprice']);
527         my $price = $infos->{price};
528         my $replacementprice = $infos->{replacementprice};
529         my $quantity = $infos->{quantity};
530         my $budget_code = $infos->{budget_code};
531         my $discount = $infos->{discount};
532         my $sort1 = $infos->{sort1};
533         my $sort2 = $infos->{sort2};
534         my $budget_id;
535         if($budget_code) {
536             my $biblio_budget = GetBudgetByCode($budget_code);
537             if($biblio_budget) {
538                 $budget_id = $biblio_budget->{budget_id};
539             }
540         }
541
542         # Items
543         my @itemlist = ();
544         my $all_items_quantity = 0;
545         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']);
546         if ($alliteminfos != -1) {
547             foreach my $iteminfos (@$alliteminfos) {
548                 my $item_homebranch = $iteminfos->{homebranch};
549                 my $item_holdingbranch = $iteminfos->{holdingbranch};
550                 my $item_itype = $iteminfos->{itype};
551                 my $item_nonpublic_note = $iteminfos->{nonpublic_note};
552                 my $item_public_note = $iteminfos->{public_note};
553                 my $item_loc = $iteminfos->{loc};
554                 my $item_ccode = $iteminfos->{ccode};
555                 my $item_notforloan = $iteminfos->{notforloan};
556                 my $item_uri = $iteminfos->{uri};
557                 my $item_copyno = $iteminfos->{copyno};
558                 my $item_quantity = $iteminfos->{quantity} || 1;
559                 my $item_budget_code = $iteminfos->{budget_code};
560                 my $item_budget_id;
561                 if ( $iteminfos->{budget_code} ) {
562                     my $item_budget = GetBudgetByCode( $iteminfos->{budget_code} );
563                     if ( $item_budget ) {
564                         $item_budget_id = $item_budget->{budget_id};
565                     }
566                 }
567                 my $item_price = $iteminfos->{price};
568                 my $item_replacement_price = $iteminfos->{replacementprice};
569                 my $item_callnumber = $iteminfos->{itemcallnumber};
570
571                 for (my $i = 0; $i < $item_quantity; $i++) {
572
573                     my %itemrecord = (
574                         'item_id' => $item_id++,
575                         'biblio_count' => $biblio_count,
576                         'homebranch' => $item_homebranch,
577                         'holdingbranch' => $item_holdingbranch,
578                         'itype' => $item_itype,
579                         'nonpublic_note' => $item_nonpublic_note,
580                         'public_note' => $item_public_note,
581                         'loc' => $item_loc,
582                         'ccode' => $item_ccode,
583                         'notforloan' => $item_notforloan,
584                         'uri' => $item_uri,
585                         'copyno' => $item_copyno,
586                         'quantity' => $item_quantity,
587                         'budget_id' => $item_budget_id || $budget_id,
588                         'itemprice' => $item_price || $price,
589                         'replacementprice' => $item_replacement_price || $replacementprice,
590                         'itemcallnumber' => $item_callnumber,
591                     );
592                     $all_items_quantity++;
593                     push @itemlist, \%itemrecord;
594
595                 }
596             }
597
598             $cellrecord{'iteminfos'} = \@itemlist;
599         } else {
600             $cellrecord{'item_error'} = 1;
601         }
602         push @list, \%cellrecord;
603
604         if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
605             $cellrecord{price} = $price || '';
606             $cellrecord{replacementprice} = $replacementprice || '';
607             $cellrecord{quantity} = $quantity || '';
608             $cellrecord{budget_id} = $budget_id || '';
609             $cellrecord{discount} = $discount || '';
610             $cellrecord{sort1} = $sort1 || '';
611             $cellrecord{sort2} = $sort2 || '';
612         } else {
613             $cellrecord{quantity} = $all_items_quantity;
614         }
615
616     }
617     my $num_records = $batch->{'num_records'};
618     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
619     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
620     my $item_action = GetImportBatchItemAction($import_batch_id);
621     my @itypes = Koha::ItemTypes->search;
622     $template->param(biblio_list => \@list,
623                         num_results => $num_records,
624                         import_batch_id => $import_batch_id,
625                         "overlay_action_${overlay_action}" => 1,
626                         overlay_action => $overlay_action,
627                         "nomatch_action_${nomatch_action}" => 1,
628                         nomatch_action => $nomatch_action,
629                         "item_action_${item_action}" => 1,
630                         item_action => $item_action,
631                         item_error => $item_error,
632                         libraries => scalar Koha::Libraries->search(),
633                         locationloop => \@locations,
634                         itypeloop => \@itypes,
635                         ccodeloop => \@ccodes,
636                         notforloanloop => \@notforloans,
637                     );
638     batch_info($template, $batch);
639 }
640
641 sub batch_info {
642     my ($template, $batch) = @_;
643     $template->param(batch_info => 1,
644                                       file_name => $batch->{'file_name'},
645                                           comments => $batch->{'comments'},
646                                           import_status => $batch->{'import_status'},
647                                           upload_timestamp => $batch->{'upload_timestamp'},
648                                           num_records => $batch->{'num_records'},
649                                           num_items => $batch->{'num_items'});
650     if ($batch->{'num_records'} > 0) {
651         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
652             $template->param(can_commit => 1);
653         }
654         if ($batch->{'import_status'} eq 'imported') {
655             $template->param(can_revert => 1);
656         }
657     }
658     if (defined $batch->{'matcher_id'}) {
659         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
660         if (defined $matcher) {
661             $template->param('current_matcher_id' => $batch->{'matcher_id'},
662                                               'current_matcher_code' => $matcher->code(),
663                                               'current_matcher_description' => $matcher->description());
664         }
665     }
666     add_matcher_list($batch->{'matcher_id'}, $template);
667 }
668
669 sub add_matcher_list {
670     my ($current_matcher_id, $template) = @_;
671     my @matchers = C4::Matcher::GetMatcherList();
672     if (defined $current_matcher_id) {
673         for (my $i = 0; $i <= $#matchers; $i++) {
674             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
675                 $matchers[$i]->{'selected'} = 1;
676             }
677         }
678     }
679     $template->param(available_matchers => \@matchers);
680 }
681
682 sub get_infos_syspref {
683     my ($syspref_name, $record, $field_list) = @_;
684     my $syspref = C4::Context->preference($syspref_name);
685     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
686     my $yaml = eval {
687         YAML::XS::Load(Encode::encode_utf8($syspref));
688     };
689     if ( $@ ) {
690         warn "Unable to parse $syspref syspref : $@";
691         return ();
692     }
693     my $r;
694     for my $field_name ( @$field_list ) {
695         next unless exists $yaml->{$field_name};
696         my @fields = split /\|/, $yaml->{$field_name};
697         for my $field ( @fields ) {
698             my ( $f, $sf ) = split /\$/, $field;
699             next unless $f and $sf;
700             if ( my $v = $record->subfield( $f, $sf ) ) {
701                 $r->{$field_name} = $v;
702             }
703             last if $yaml->{$field};
704         }
705     }
706     return $r;
707 }
708
709 sub equal_number_of_fields {
710     my ($tags_list, $record) = @_;
711     my $tag_fields_count;
712     for my $tag (@$tags_list) {
713         my @fields = $record->field($tag);
714         $tag_fields_count->{$tag} = scalar @fields;
715     }
716
717     my $tags_count;
718     foreach my $key ( keys %$tag_fields_count ) {
719         if ( $tag_fields_count->{$key} > 0 ) { # Having 0 of a field is ok
720             $tags_count //= $tag_fields_count->{$key}; # Start with the count from the first occurrence
721             return -1 if $tag_fields_count->{$key} != $tags_count; # All counts of various fields should be equal if they exist
722         }
723     }
724
725     return $tags_count;
726 }
727
728 sub get_infos_syspref_on_item {
729     my ($syspref_name, $record, $field_list) = @_;
730     my $syspref = C4::Context->preference($syspref_name);
731     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
732     my $yaml = eval {
733         YAML::XS::Load(Encode::encode_utf8($syspref));
734     };
735     if ( $@ ) {
736         warn "Unable to parse $syspref syspref : $@";
737         return ();
738     }
739     my @result;
740     my @tags_list;
741
742     # Check tags in syspref definition
743     for my $field_name ( @$field_list ) {
744         next unless exists $yaml->{$field_name};
745         my @fields = split /\|/, $yaml->{$field_name};
746         for my $field ( @fields ) {
747             my ( $f, $sf ) = split /\$/, $field;
748             next unless $f and $sf;
749             push @tags_list, $f;
750         }
751     }
752     @tags_list = List::MoreUtils::uniq(@tags_list);
753
754     my $tags_count = equal_number_of_fields(\@tags_list, $record);
755     # Return if the number of these fields in the record is not the same.
756     return -1 if $tags_count == -1;
757
758     # Gather the fields
759     my $fields_hash;
760     foreach my $tag (@tags_list) {
761         my @tmp_fields;
762         foreach my $field ($record->field($tag)) {
763             push @tmp_fields, $field;
764         }
765         $fields_hash->{$tag} = \@tmp_fields;
766     }
767
768     for (my $i = 0; $i < $tags_count; $i++) {
769         my $r;
770         for my $field_name ( @$field_list ) {
771             next unless exists $yaml->{$field_name};
772             my @fields = split /\|/, $yaml->{$field_name};
773             for my $field ( @fields ) {
774                 my ( $f, $sf ) = split /\$/, $field;
775                 next unless $f and $sf;
776                 my $v = $fields_hash->{$f}[$i] ? $fields_hash->{$f}[$i]->subfield( $sf ) : undef;
777                 $r->{$field_name} = $v if (defined $v);
778                 last if $yaml->{$field};
779             }
780         }
781         push @result, $r;
782     }
783     return \@result;
784 }