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