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