Bug 19041: (bug 17855 follow-up) Fix regression on bug 16058
[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 qw/Load/;
28 use List::MoreUtils qw/uniq/;
29
30 use C4::Context;
31 use C4::Auth;
32 use C4::Output;
33 use C4::ImportBatch;
34 use C4::Matcher;
35 use C4::Search qw/FindDuplicate/;
36 use C4::Acquisition;
37 use C4::Biblio;
38 use C4::Items;
39 use C4::Koha;
40 use C4::Budgets;
41 use C4::Acquisition;
42 use C4::Suggestions;    # GetSuggestion
43 use C4::Members;
44
45 use Koha::Number::Price;
46 use Koha::Libraries;
47 use Koha::Acquisition::Currencies;
48 use Koha::Acquisition::Order;
49 use Koha::Acquisition::Booksellers;
50 use Koha::Patrons;
51
52 my $input = new CGI;
53 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
54     template_name => "acqui/addorderiso2709.tt",
55     query => $input,
56     type => "intranet",
57     authnotrequired => 0,
58     flagsrequired   => { acquisition => 'order_manage' },
59     debug => 1,
60 });
61
62 my $cgiparams = $input->Vars;
63 my $op = $cgiparams->{'op'} || '';
64 my $booksellerid  = $input->param('booksellerid');
65 my $allmatch = $input->param('allmatch');
66 my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
67
68 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
69                 booksellerid => $booksellerid,
70                 booksellername => $bookseller->name,
71                 );
72
73 if ($cgiparams->{'import_batch_id'} && $op eq ""){
74     $op = "batch_details";
75 }
76
77 #Needed parameters:
78 if (! $cgiparams->{'basketno'}){
79     die "Basketnumber required to order from iso2709 file import";
80 }
81
82 #
83 # 1st step = choose the file to import into acquisition
84 #
85 if ($op eq ""){
86     $template->param("basketno" => $cgiparams->{'basketno'});
87 #display batches
88     import_batches_list($template);
89 #
90 # 2nd step = display the content of the chosen file
91 #
92 } elsif ($op eq "batch_details"){
93 #display lines inside the selected batch
94     # get currencies (for change rates calcs if needed)
95     my @currencies = Koha::Acquisition::Currencies->search;
96
97     $template->param("batch_details" => 1,
98                      "basketno"      => $cgiparams->{'basketno'},
99                      currencies => \@currencies,
100                      bookseller => $bookseller,
101                      "allmatch" => $allmatch,
102                      );
103     import_biblios_list($template, $cgiparams->{'import_batch_id'});
104     my $basket = GetBasket($cgiparams->{basketno});
105     if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$basket->{is_standing} ) {
106         # prepare empty item form
107         my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
108
109         #     warn "==> ".Data::Dumper::Dumper($cell);
110         unless ($cell) {
111             $cell = PrepareItemrecordDisplay( '', '', '', '' );
112             $template->param( 'NoACQframework' => 1 );
113         }
114         my @itemloop;
115         push @itemloop, $cell;
116
117         $template->param( items => \@itemloop );
118     }
119 #
120 # 3rd step = import the records
121 #
122 } elsif ( $op eq 'import_records' ) {
123 #import selected lines
124     $template->param('basketno' => $cgiparams->{'basketno'});
125 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
126     my $budgets = GetBudgets();
127     if (scalar @$budgets == 0){
128         die "No budgets defined, can't continue";
129     }
130     my $budget_id = @$budgets[0]->{'budget_id'};
131 #get all records from a batch, and check their import status to see if they are checked.
132 #(default values: quantity 1, uncertainprice yes, first budget)
133
134     # retrieve the file you want to import
135     my $import_batch_id = $cgiparams->{'import_batch_id'};
136     my $biblios = GetImportRecordsRange($import_batch_id);
137     my $duplinbatch;
138     my $imported = 0;
139     my @import_record_id_selected = $input->multi_param("import_record_id");
140     my @quantities = $input->multi_param('quantity');
141     my @prices = $input->multi_param('price');
142     my @budgets_id = $input->multi_param('budget_id');
143     my @discount = $input->multi_param('discount');
144     my @sort1 = $input->multi_param('sort1');
145     my @sort2 = $input->multi_param('sort2');
146     my $matcher_id = $input->param('matcher_id');
147     my $active_currency = Koha::Acquisition::Currencies->get_active;
148     my $biblio_count = 0;
149     for my $biblio (@$biblios){
150         $biblio_count++;
151         my $duplifound = 0;
152         # Check if this import_record_id was selected
153         next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
154         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
155         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
156         my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
157         my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
158         my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
159         my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
160         my $c_discount = shift ( @discount);
161         $c_discount = $c_discount / 100 if $c_discount > 1;
162         my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
163         my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
164
165         # 1st insert the biblio, or find it through matcher
166         unless ( $biblionumber ) {
167             if ($matcher_id) {
168                 if ( $matcher_id eq '_TITLE_AUTHOR_' ) {
169                     $duplifound = 1 if FindDuplicate($marcrecord);
170                 }
171                 else {
172                     my $matcher = C4::Matcher->fetch($matcher_id);
173                     my @matches = $matcher->get_matches( $marcrecord, my $max_matches = 1 );
174                     $duplifound = 1 if @matches;
175                 }
176
177                 $duplinbatch = $import_batch_id and next if $duplifound;
178             }
179
180             # add the biblio
181             my $bibitemnum;
182
183             # remove ISBN -
184             my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
185             if ( $marcrecord->field($isbnfield) ) {
186                 foreach my $field ( $marcrecord->field($isbnfield) ) {
187                     foreach my $subfield ( $field->subfield($isbnsubfield) ) {
188                         my $newisbn = $field->subfield($isbnsubfield);
189                         $newisbn =~ s/-//g;
190                         $field->update( $isbnsubfield => $newisbn );
191                     }
192                 }
193             }
194             ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
195             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
196             # 2nd add authorities if applicable
197             if (C4::Context->preference("BiblioAddsAuthorities")){
198                 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
199             }
200         } else {
201             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
202         }
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_bibnum, $item_bibitemnum, $itemnumber) = AddItem({
226                 homebranch => $homebranches[$i],
227                 holdingbranch => $holdingbranches[$i],
228                 itemnotes_nonpublic => $nonpublic_notes[$i],
229                 itemnotes => $public_notes[$i],
230                 location => $locs[$i],
231                 ccode => $ccodes[$i],
232                 itype => $itypes[$i],
233                 notforloan => $notforloans[$i],
234                 uri => $uris[$i],
235                 copynumber => $copynos[$i],
236                 price => $itemprices[$i],
237                 replacementprice => $replacementprices[$i],
238                 itemcallnumber => $itemcallnumbers[$i],
239             }, $biblionumber);
240             push( @itemnumbers, $itemnumber );
241         }
242         if ($itemcreation == 1) {
243             # Group orderlines from MarcItemFieldsToOrder
244             my $budget_hash;
245             for (my $i = 0; $i < $count; $i++) {
246                 $budget_hash->{$budget_codes[$i]}->{quantity} += 1;
247                 $budget_hash->{$budget_codes[$i]}->{price} = $itemprices[$i];
248             }
249
250             # Create orderlines from MarcItemFieldsToOrder
251             while(my ($budget_id, $infos) = each %$budget_hash) {
252                 if ($budget_id) {
253                     my %orderinfo = (
254                         biblionumber       => $biblionumber,
255                         basketno           => $cgiparams->{'basketno'},
256                         quantity           => $infos->{quantity},
257                         budget_id          => $budget_id,
258                         currency           => $cgiparams->{'all_currency'},
259                     );
260
261                     my $price = $infos->{price};
262                     if ($price){
263                         # in France, the cents separator is the , but sometimes, ppl use a .
264                         # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
265                         $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
266                         $price = Koha::Number::Price->new($price)->unformat;
267                         $orderinfo{tax_rate} = $bookseller->tax_rate;
268                         my $c = $c_discount ? $c_discount : $bookseller->discount / 100;
269                         $orderinfo{discount} = $c;
270                         if ( $bookseller->listincgst ) {
271                             if ( $c_discount ) {
272                                 $orderinfo{ecost} = $price;
273                                 $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
274                             } else {
275                                 $orderinfo{ecost} = $price * ( 1 - $c );
276                                 $orderinfo{rrp}   = $price;
277                             }
278                         } else {
279                             if ( $c_discount ) {
280                                 $orderinfo{ecost} = $price / ( 1 + $orderinfo{tax_rate} );
281                                 $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
282                             } else {
283                                 $orderinfo{rrp}   = $price / ( 1 + $orderinfo{tax_rate} );
284                                 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
285                             }
286                         }
287                         $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
288                         $orderinfo{unitprice} = $orderinfo{ecost};
289                         $orderinfo{total} = $orderinfo{ecost} * $infos->{quantity};
290                     } else {
291                         $orderinfo{listprice} = 0;
292                     }
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 )->insert;
309                     $order->add_item( $_ ) for @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             );
330             # get the price if there is one.
331             my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
332             if ($price){
333                 # in France, the cents separator is the , but sometimes, ppl use a .
334                 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
335                 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
336                 $price = Koha::Number::Price->new($price)->unformat;
337                 $orderinfo{tax_rate} = $bookseller->tax_rate;
338                 my $c = $c_discount ? $c_discount : $bookseller->discount / 100;
339                 $orderinfo{discount} = $c;
340                 if ( $bookseller->listincgst ) {
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                 } else {
349                     if ( $c_discount ) {
350                         $orderinfo{ecost} = $price / ( 1 + $orderinfo{tax_rate} );
351                         $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
352                     } else {
353                         $orderinfo{rrp}   = $price / ( 1 + $orderinfo{tax_rate} );
354                         $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
355                     }
356                 }
357                 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
358                 $orderinfo{unitprice} = $orderinfo{ecost};
359                 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
360             } else {
361                 $orderinfo{listprice} = 0;
362             }
363
364         # remove uncertainprice flag if we have found a price in the MARC record
365         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
366
367         %orderinfo = %{
368             C4::Acquisition::populate_order_with_prices(
369                 {
370                     order        => \%orderinfo,
371                     booksellerid => $booksellerid,
372                     ordering     => 1,
373                     receiving    => 1,
374                 }
375             )
376         };
377
378         my $order = Koha::Acquisition::Order->new( \%orderinfo )->insert;
379
380         # 4th, add items if applicable
381         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
382         # this is not optimised, but it's working !
383         my $basket = GetBasket($cgiparams->{basketno});
384         if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$basket->{is_standing} ) {
385             my @tags         = $input->multi_param('tag');
386             my @subfields    = $input->multi_param('subfield');
387             my @field_values = $input->multi_param('field_value');
388             my @serials      = $input->multi_param('serial');
389             my @ind_tag   = $input->multi_param('ind_tag');
390             my @indicator = $input->multi_param('indicator');
391             my $item;
392             push @{ $item->{tags} },         $tags[0];
393             push @{ $item->{subfields} },    $subfields[0];
394             push @{ $item->{field_values} }, $field_values[0];
395             push @{ $item->{ind_tag} },      $ind_tag[0];
396             push @{ $item->{indicator} },    $indicator[0];
397             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@indicator, \@ind_tag );
398             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
399             for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
400                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
401                 $order->add_item( $itemnumber );
402                 }
403             } else {
404                 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
405             }
406         }
407         $imported++;
408     }
409     # go to basket page
410     if ( $imported ) {
411         print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
412     } else {
413         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");
414     }
415     exit;
416 }
417
418 my $budgets = GetBudgets();
419 my $budget_id = @$budgets[0]->{'budget_id'};
420 # build bookfund list
421 my $patron = Koha::Patrons->find( $loggedinuser )->unblessed;
422 my $budget = GetBudget($budget_id);
423
424 # build budget list
425 my $budget_loop = [];
426 my $budgets_hierarchy = GetBudgetHierarchy;
427 foreach my $r ( @{$budgets_hierarchy} ) {
428     next unless (CanUserUseBudget($patron, $r, $userflags));
429     if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
430         next;
431     }
432     push @{$budget_loop},
433       { b_id  => $r->{budget_id},
434         b_txt => $r->{budget_name},
435         b_code => $r->{budget_code},
436         b_sort1_authcat => $r->{'sort1_authcat'},
437         b_sort2_authcat => $r->{'sort2_authcat'},
438         b_active => $r->{budget_period_active},
439         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
440       };
441 }
442
443 @{$budget_loop} =
444   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
445
446 $template->param( budget_loop    => $budget_loop,);
447
448 output_html_with_http_headers $input, $cookie, $template->output;
449
450
451 sub import_batches_list {
452     my ($template) = @_;
453     my $batches = GetImportBatchRangeDesc();
454
455     my @list = ();
456     foreach my $batch (@$batches) {
457         if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
458             # check if there is at least 1 line still staged
459             my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
460             if (scalar @$stagedList) {
461                 push @list, {
462                         import_batch_id => $batch->{'import_batch_id'},
463                         num_records => $batch->{'num_records'},
464                         num_items => $batch->{'num_items'},
465                         staged_date => $batch->{'upload_timestamp'},
466                         import_status => $batch->{'import_status'},
467                         file_name => $batch->{'file_name'},
468                         comments => $batch->{'comments'},
469                 };
470             } else {
471                 # if there are no more line to includes, set the status to imported
472                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
473             }
474         }
475     }
476     $template->param(batch_list => \@list); 
477     my $num_batches = GetNumberOfNonZ3950ImportBatches();
478     $template->param(num_results => $num_batches);
479 }
480
481 sub import_biblios_list {
482     my ($template, $import_batch_id) = @_;
483     my $batch = GetImportBatch($import_batch_id,'staged');
484     return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
485     my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
486     my @list = ();
487     my $item_error = 0;
488
489     my $ccodes = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' } ) };
490     my $locations = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
491     my $notforloans = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.notforloan' } ) };
492     # location list
493     my @locations;
494     foreach (sort keys %$locations) {
495         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
496     }
497     my @ccodes;
498     foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
499         push @ccodes, { code => $_, description => $ccodes->{$_} };
500     }
501     my @notforloans;
502     foreach (sort {$notforloans->{$a} cmp $notforloans->{$b}} keys %$notforloans) {
503         push @notforloans, { code => $_, description => $notforloans->{$_} };
504     }
505
506     my $biblio_count = 0;
507     foreach my $biblio (@$biblios) {
508         my $item_id = 1;
509         $biblio_count++;
510         my $citation = $biblio->{'title'};
511         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
512         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
513         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
514         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
515         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
516         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
517         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
518         my %cellrecord = (
519             import_record_id => $biblio->{'import_record_id'},
520             citation => $citation,
521             import  => 1,
522             status => $biblio->{'status'},
523             record_sequence => $biblio->{'record_sequence'},
524             overlay_status => $biblio->{'overlay_status'},
525             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
526             match_citation     => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
527             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
528         );
529         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
530         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
531
532         my $infos = get_infos_syspref('MarcFieldsToOrder', $marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2']);
533         my $price = $infos->{price};
534         my $quantity = $infos->{quantity};
535         my $budget_code = $infos->{budget_code};
536         my $discount = $infos->{discount};
537         my $sort1 = $infos->{sort1};
538         my $sort2 = $infos->{sort2};
539         my $budget_id;
540         if($budget_code) {
541             my $biblio_budget = GetBudgetByCode($budget_code);
542             if($biblio_budget) {
543                 $budget_id = $biblio_budget->{budget_id};
544             }
545         }
546
547         # Items
548         my @itemlist = ();
549         my $all_items_quantity = 0;
550         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']);
551         if ($alliteminfos != -1) {
552             foreach my $iteminfos (@$alliteminfos) {
553                 my $item_homebranch = $iteminfos->{homebranch};
554                 my $item_holdingbranch = $iteminfos->{holdingbranch};
555                 my $item_itype = $iteminfos->{itype};
556                 my $item_nonpublic_note = $iteminfos->{nonpublic_note};
557                 my $item_public_note = $iteminfos->{public_note};
558                 my $item_loc = $iteminfos->{loc};
559                 my $item_ccode = $iteminfos->{ccode};
560                 my $item_notforloan = $iteminfos->{notforloan};
561                 my $item_uri = $iteminfos->{uri};
562                 my $item_copyno = $iteminfos->{copyno};
563                 my $item_quantity = $iteminfos->{quantity} || 1;
564                 my $item_budget_code = $iteminfos->{budget_code};
565                 my $item_price = $iteminfos->{price};
566                 my $item_replacement_price = $iteminfos->{replacementprice};
567                 my $item_callnumber = $iteminfos->{itemcallnumber};
568
569                 for (my $i = 0; $i < $item_quantity; $i++) {
570
571                     my %itemrecord = (
572                         'item_id' => $item_id++,
573                         'biblio_count' => $biblio_count,
574                         'homebranch' => $item_homebranch,
575                         'holdingbranch' => $item_holdingbranch,
576                         'itype' => $item_itype,
577                         'nonpublic_note' => $item_nonpublic_note,
578                         'public_note' => $item_public_note,
579                         'loc' => $item_loc,
580                         'ccode' => $item_ccode,
581                         'notforloan' => $item_notforloan,
582                         'uri' => $item_uri,
583                         'copyno' => $item_copyno,
584                         'quantity' => $item_quantity,
585                         'budget_code' => $item_budget_code || $budget_code,
586                         'itemprice' => $item_price || $price,
587                         'replacementprice' => $item_replacement_price,
588                         'itemcallnumber' => $item_callnumber,
589                     );
590                     $all_items_quantity++;
591                     push @itemlist, \%itemrecord;
592
593                 }
594             }
595
596             $cellrecord{'iteminfos'} = \@itemlist;
597         } else {
598             $cellrecord{'item_error'} = 1;
599         }
600         push @list, \%cellrecord;
601
602         if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
603             $cellrecord{price} = $price || '';
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::Load($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 $refcount = 0;
709     my $count = 0;
710     for my $tag (@$tags_list) {
711         return -1 if $count != $refcount;
712         $count = 0;
713         for my $field ($record->field($tag)) {
714             $count++;
715         }
716         $refcount = $count if ($refcount == 0);
717     }
718     return -1 if $count != $refcount;
719     return $count;
720 }
721
722 sub get_infos_syspref_on_item {
723     my ($syspref_name, $record, $field_list) = @_;
724     my $syspref = C4::Context->preference($syspref_name);
725     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
726     my $yaml = eval {
727         YAML::Load($syspref);
728     };
729     if ( $@ ) {
730         warn "Unable to parse $syspref syspref : $@";
731         return ();
732     }
733     my @result;
734     my @tags_list;
735
736     # Check tags in syspref definition
737     for my $field_name ( @$field_list ) {
738         next unless exists $yaml->{$field_name};
739         my @fields = split /\|/, $yaml->{$field_name};
740         for my $field ( @fields ) {
741             my ( $f, $sf ) = split /\$/, $field;
742             next unless $f and $sf;
743             push @tags_list, $f;
744         }
745     }
746     @tags_list = List::MoreUtils::uniq(@tags_list);
747
748     my $tags_count = equal_number_of_fields(\@tags_list, $record);
749     # Return if the number of theses fields in the record is not the same.
750     return -1 if $tags_count == -1;
751
752     # Gather the fields
753     my $fields_hash;
754     foreach my $tag (@tags_list) {
755         my @tmp_fields;
756         foreach my $field ($record->field($tag)) {
757             push @tmp_fields, $field;
758         }
759         $fields_hash->{$tag} = \@tmp_fields;
760     }
761
762     for (my $i = 0; $i < $tags_count; $i++) {
763         my $r;
764         for my $field_name ( @$field_list ) {
765             next unless exists $yaml->{$field_name};
766             my @fields = split /\|/, $yaml->{$field_name};
767             for my $field ( @fields ) {
768                 my ( $f, $sf ) = split /\$/, $field;
769                 next unless $f and $sf;
770                 my $v = $fields_hash->{$f}[$i]->subfield( $sf );
771                 $r->{$field_name} = $v if (defined $v);
772                 last if $yaml->{$field};
773             }
774         }
775         push @result, $r;
776     }
777     return \@result;
778 }