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