Bug 15503 [QA Followup] - Remove the use of GetBranchesLoop
[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('ccodes_' . $biblio_count);
211         my @notforloans = $input->multi_param('notforloans_' . $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 $itemcreation = 0;
217         for (my $i = 0; $i < $count; $i++) {
218             $itemcreation = 1;
219             my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({
220                 homebranch => $homebranches[$i],
221                 holdingbranch => $holdingbranches[$i],
222                 itemnotes_nonpublic => $nonpublic_notes[$i],
223                 itemnotes => $public_notes[$i],
224                 location => $locs[$i],
225                 ccode => $ccodes[$i],
226                 notforloan => $notforloans[$i],
227                 uri => $uris[$i],
228                 copynumber => $copynos[$i],
229                 price => $itemprices[$i],
230             }, $biblionumber);
231         }
232         if ($itemcreation == 1) {
233             # Group orderlines from MarcItemFieldsToOrder
234             my $budget_hash;
235             for (my $i = 0; $i < $count; $i++) {
236                 $budget_hash->{$budget_codes[$i]}->{quantity} += 1;
237                 $budget_hash->{$budget_codes[$i]}->{price} = $itemprices[$i];
238             }
239
240             # Create orderlines from MarcItemFieldsToOrder
241             while(my ($budget_id, $infos) = each $budget_hash) {
242                 if ($budget_id) {
243                     my %orderinfo = (
244                         biblionumber       => $biblionumber,
245                         basketno           => $cgiparams->{'basketno'},
246                         quantity           => $infos->{quantity},
247                         budget_id          => $budget_id,
248                         currency           => $cgiparams->{'all_currency'},
249                     );
250
251                     my $price = $infos->{price};
252                     if ($price){
253                         # in France, the cents separator is the , but sometimes, ppl use a .
254                         # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
255                         $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
256                         $price = Koha::Number::Price->new($price)->unformat;
257                         $orderinfo{gstrate} = $bookseller->{gstrate};
258                         my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
259                         if ( $bookseller->{listincgst} ) {
260                             if ( $c_discount ) {
261                                 $orderinfo{ecost} = $price;
262                                 $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
263                             } else {
264                                 $orderinfo{ecost} = $price * ( 1 - $c );
265                                 $orderinfo{rrp}   = $price;
266                             }
267                         } else {
268                             if ( $c_discount ) {
269                                 $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
270                                 $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
271                             } else {
272                                 $orderinfo{rrp}   = $price / ( 1 + $orderinfo{gstrate} );
273                                 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
274                             }
275                         }
276                         $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
277                         $orderinfo{unitprice} = $orderinfo{ecost};
278                         $orderinfo{total} = $orderinfo{ecost} * $infos->{quantity};
279                     } else {
280                         $orderinfo{listprice} = 0;
281                     }
282
283                     # remove uncertainprice flag if we have found a price in the MARC record
284                     $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
285                     my $order = Koha::Acquisition::Order->new( \%orderinfo )->insert;
286                 }
287             }
288         } else {
289             # 3rd add order
290             my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
291             # get quantity in the MARC record (1 if none)
292             my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
293             my %orderinfo = (
294                 biblionumber       => $biblionumber,
295                 basketno           => $cgiparams->{'basketno'},
296                 quantity           => $c_quantity,
297                 branchcode         => $patron->{branchcode},
298                 budget_id          => $c_budget_id,
299                 uncertainprice     => 1,
300                 sort1              => $c_sort1,
301                 sort2              => $c_sort2,
302                 order_internalnote => $cgiparams->{'all_order_internalnote'},
303                 order_vendornote   => $cgiparams->{'all_order_vendornote'},
304                 currency           => $cgiparams->{'all_currency'},
305             );
306             # get the price if there is one.
307             my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
308             if ($price){
309                 # in France, the cents separator is the , but sometimes, ppl use a .
310                 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
311                 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
312                 $price = Koha::Number::Price->new($price)->unformat;
313                 $orderinfo{gstrate} = $bookseller->{gstrate};
314                 my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
315                 if ( $bookseller->{listincgst} ) {
316                     if ( $c_discount ) {
317                         $orderinfo{ecost} = $price;
318                         $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
319                     } else {
320                         $orderinfo{ecost} = $price * ( 1 - $c );
321                         $orderinfo{rrp}   = $price;
322                     }
323                 } else {
324                     if ( $c_discount ) {
325                         $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
326                         $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
327                     } else {
328                         $orderinfo{rrp}   = $price / ( 1 + $orderinfo{gstrate} );
329                         $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
330                     }
331                 }
332                 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
333                 $orderinfo{unitprice} = $orderinfo{ecost};
334                 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
335             } else {
336                 $orderinfo{listprice} = 0;
337             }
338
339         # remove uncertainprice flag if we have found a price in the MARC record
340         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
341
342         %orderinfo = %{
343             C4::Acquisition::populate_order_with_prices(
344                 {
345                     order        => \%orderinfo,
346                     booksellerid => $booksellerid,
347                     ordering     => 1,
348                     receiving    => 1,
349                 }
350             )
351         };
352
353         my $order = Koha::Acquisition::Order->new( \%orderinfo )->insert;
354
355         # 4th, add items if applicable
356         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
357         # this is not optimised, but it's working !
358         my $basket = GetBasket($cgiparams->{basketno});
359         if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$basket->{is_standing} ) {
360             my @tags         = $input->multi_param('tag');
361             my @subfields    = $input->multi_param('subfield');
362             my @field_values = $input->multi_param('field_value');
363             my @serials      = $input->multi_param('serial');
364             my @ind_tag   = $input->multi_param('ind_tag');
365             my @indicator = $input->multi_param('indicator');
366             my $item;
367             push @{ $item->{tags} },         $tags[0];
368             push @{ $item->{subfields} },    $subfields[0];
369             push @{ $item->{field_values} }, $field_values[0];
370             push @{ $item->{ind_tag} },      $ind_tag[0];
371             push @{ $item->{indicator} },    $indicator[0];
372             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@indicator, \@ind_tag );
373             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
374             for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
375                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
376                 $order->add_item( $itemnumber );
377             }
378             } else {
379                 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
380             }
381         }
382         $imported++;
383     }
384     # go to basket page
385     if ( $imported ) {
386         print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
387     } else {
388         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");
389     }
390     exit;
391 }
392
393 my $budgets = GetBudgets();
394 my $budget_id = @$budgets[0]->{'budget_id'};
395 # build bookfund list
396 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
397 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
398 my $budget = GetBudget($budget_id);
399
400 # build budget list
401 my $budget_loop = [];
402 my $budgets_hierarchy = GetBudgetHierarchy;
403 foreach my $r ( @{$budgets_hierarchy} ) {
404     next unless (CanUserUseBudget($borrower, $r, $userflags));
405     if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
406         next;
407     }
408     push @{$budget_loop},
409       { b_id  => $r->{budget_id},
410         b_txt => $r->{budget_name},
411         b_code => $r->{budget_code},
412         b_sort1_authcat => $r->{'sort1_authcat'},
413         b_sort2_authcat => $r->{'sort2_authcat'},
414         b_active => $r->{budget_period_active},
415         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
416       };
417 }
418
419 @{$budget_loop} =
420   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
421
422 $template->param( budget_loop    => $budget_loop,);
423
424 output_html_with_http_headers $input, $cookie, $template->output;
425
426
427 sub import_batches_list {
428     my ($template) = @_;
429     my $batches = GetImportBatchRangeDesc();
430
431     my @list = ();
432     foreach my $batch (@$batches) {
433         if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
434             # check if there is at least 1 line still staged
435             my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
436             if (scalar @$stagedList) {
437                 push @list, {
438                         import_batch_id => $batch->{'import_batch_id'},
439                         num_records => $batch->{'num_records'},
440                         num_items => $batch->{'num_items'},
441                         staged_date => $batch->{'upload_timestamp'},
442                         import_status => $batch->{'import_status'},
443                         file_name => $batch->{'file_name'},
444                         comments => $batch->{'comments'},
445                 };
446             } else {
447                 # if there are no more line to includes, set the status to imported
448                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
449             }
450         }
451     }
452     $template->param(batch_list => \@list); 
453     my $num_batches = GetNumberOfNonZ3950ImportBatches();
454     $template->param(num_results => $num_batches);
455 }
456
457 sub import_biblios_list {
458     my ($template, $import_batch_id) = @_;
459     my $batch = GetImportBatch($import_batch_id,'staged');
460     return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
461     my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
462     my @list = ();
463     my $item_error = 0;
464
465     my $ccodes    = GetKohaAuthorisedValues("items.ccode");
466     my $locations = GetKohaAuthorisedValues("items.location");
467     # location list
468     my @locations;
469     foreach (sort keys %$locations) {
470         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
471     }
472     my @ccodes;
473     foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
474         push @ccodes, { code => $_, description => $ccodes->{$_} };
475     }
476
477
478     my $biblio_count = 0;
479     foreach my $biblio (@$biblios) {
480         my $item_id = 1;
481         $biblio_count++;
482         my $citation = $biblio->{'title'};
483         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
484         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
485         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
486         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
487         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
488         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
489         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
490         my %cellrecord = (
491             import_record_id => $biblio->{'import_record_id'},
492             citation => $citation,
493             import  => 1,
494             status => $biblio->{'status'},
495             record_sequence => $biblio->{'record_sequence'},
496             overlay_status => $biblio->{'overlay_status'},
497             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
498             match_citation     => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
499             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
500         );
501         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
502         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
503
504         my $infos = get_infos_syspref('MarcFieldsToOrder', $marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2']);
505         my $price = $infos->{price};
506         my $quantity = $infos->{quantity};
507         my $budget_code = $infos->{budget_code};
508         my $discount = $infos->{discount};
509         my $sort1 = $infos->{sort1};
510         my $sort2 = $infos->{sort2};
511         my $budget_id;
512         if($budget_code) {
513             my $biblio_budget = GetBudgetByCode($budget_code);
514             if($biblio_budget) {
515                 $budget_id = $biblio_budget->{budget_id};
516             }
517         }
518
519         # Items
520         my @itemlist = ();
521         my $all_items_quantity = 0;
522         my $alliteminfos = get_infos_syspref_on_item('MarcItemFieldsToOrder', $marcrecord, ['homebranch', 'holdingbranch', 'itype', 'nonpublic_note', 'public_note', 'loc', 'ccode', 'notforloan', 'uri', 'copyno', 'price', 'quantity', 'budget_code']);
523         if ($alliteminfos != -1) {
524             foreach my $iteminfos (@$alliteminfos) {
525                 my $item_homebranch = $iteminfos->{homebranch};
526                 my $item_holdingbranch = $iteminfos->{holdingbranch};
527                 my $item_itype = $iteminfos->{itype};
528                 my $item_nonpublic_note = $iteminfos->{nonpublic_note};
529                 my $item_public_note = $iteminfos->{public_note};
530                 my $item_loc = $iteminfos->{loc};
531                 my $item_ccode = $iteminfos->{ccode};
532                 my $item_notforloan = $iteminfos->{notforloan};
533                 my $item_uri = $iteminfos->{uri};
534                 my $item_copyno = $iteminfos->{copyno};
535                 my $item_quantity = $iteminfos->{quantity} || 1;
536                 my $item_budget_code = $iteminfos->{budget_code};
537                 my $item_price = $iteminfos->{price};
538
539                 for (my $i = 0; $i < $item_quantity; $i++) {
540
541                     my %itemrecord = (
542                         'item_id' => $item_id++,
543                         'biblio_count' => $biblio_count,
544                         'homebranch' => $item_homebranch,
545                         'holdingbranch' => $item_holdingbranch,
546                         'itype' => $item_itype,
547                         'nonpublic_note' => $item_nonpublic_note,
548                         'public_note' => $item_public_note,
549                         'loc' => $item_loc,
550                         'ccode' => $item_ccode,
551                         'notforloan' => $item_notforloan,
552                         'uri' => $item_uri,
553                         'copyno' => $item_copyno,
554                         'quantity' => $item_quantity,
555                         'budget_code' => $item_budget_code || $budget_code,
556                         'itemprice' => $item_price || $price,
557                     );
558                     $all_items_quantity++;
559                     push @itemlist, \%itemrecord;
560
561                 }
562             }
563
564             $cellrecord{'iteminfos'} = \@itemlist;
565         } else {
566             $item_error = 1;
567         }
568         push @list, \%cellrecord;
569
570         if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
571             $cellrecord{price} = $price || '';
572             $cellrecord{quantity} = $quantity || '';
573             $cellrecord{budget_id} = $budget_id || '';
574             $cellrecord{discount} = $discount || '';
575             $cellrecord{sort1} = $sort1 || '';
576             $cellrecord{sort2} = $sort2 || '';
577         } else {
578             $cellrecord{quantity} = $all_items_quantity;
579         }
580
581     }
582     my $num_records = $batch->{'num_records'};
583     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
584     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
585     my $item_action = GetImportBatchItemAction($import_batch_id);
586     my @itypes = Koha::ItemTypes->search;
587     $template->param(biblio_list => \@list,
588                         num_results => $num_records,
589                         import_batch_id => $import_batch_id,
590                         "overlay_action_${overlay_action}" => 1,
591                         overlay_action => $overlay_action,
592                         "nomatch_action_${nomatch_action}" => 1,
593                         nomatch_action => $nomatch_action,
594                         "item_action_${item_action}" => 1,
595                         item_action => $item_action,
596                         item_error => $item_error,
597                         libraries => scalar Koha::Libraries->search(),
598                         locationloop => \@locations,
599                         itypeloop => \@itypes,
600                         ccodeloop => \@ccodes,
601                     );
602     batch_info($template, $batch);
603 }
604
605 sub batch_info {
606     my ($template, $batch) = @_;
607     $template->param(batch_info => 1,
608                                       file_name => $batch->{'file_name'},
609                                           comments => $batch->{'comments'},
610                                           import_status => $batch->{'import_status'},
611                                           upload_timestamp => $batch->{'upload_timestamp'},
612                                           num_records => $batch->{'num_records'},
613                                           num_items => $batch->{'num_items'});
614     if ($batch->{'num_records'} > 0) {
615         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
616             $template->param(can_commit => 1);
617         }
618         if ($batch->{'import_status'} eq 'imported') {
619             $template->param(can_revert => 1);
620         }
621     }
622     if (defined $batch->{'matcher_id'}) {
623         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
624         if (defined $matcher) {
625             $template->param('current_matcher_id' => $batch->{'matcher_id'},
626                                               'current_matcher_code' => $matcher->code(),
627                                               'current_matcher_description' => $matcher->description());
628         }
629     }
630     add_matcher_list($batch->{'matcher_id'}, $template);
631 }
632
633 sub add_matcher_list {
634     my ($current_matcher_id, $template) = @_;
635     my @matchers = C4::Matcher::GetMatcherList();
636     if (defined $current_matcher_id) {
637         for (my $i = 0; $i <= $#matchers; $i++) {
638             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
639                 $matchers[$i]->{'selected'} = 1;
640             }
641         }
642     }
643     $template->param(available_matchers => \@matchers);
644 }
645
646 sub get_infos_syspref {
647     my ($syspref_name, $record, $field_list) = @_;
648     my $syspref = C4::Context->preference($syspref_name);
649     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
650     my $yaml = eval {
651         YAML::Load($syspref);
652     };
653     if ( $@ ) {
654         warn "Unable to parse $syspref syspref : $@";
655         return ();
656     }
657     my $r;
658     for my $field_name ( @$field_list ) {
659         next unless exists $yaml->{$field_name};
660         my @fields = split /\|/, $yaml->{$field_name};
661         for my $field ( @fields ) {
662             my ( $f, $sf ) = split /\$/, $field;
663             next unless $f and $sf;
664             if ( my $v = $record->subfield( $f, $sf ) ) {
665                 $r->{$field_name} = $v;
666             }
667             last if $yaml->{$field};
668         }
669     }
670     return $r;
671 }
672
673 sub equal_number_of_fields {
674     my ($tags_list, $record) = @_;
675     my $refcount = 0;
676     my $count = 0;
677     for my $tag (@$tags_list) {
678         return -1 if $count != $refcount;
679         $count = 0;
680         for my $field ($record->field($tag)) {
681             $count++;
682         }
683         $refcount = $count if ($refcount == 0);
684     }
685     return -1 if $count != $refcount;
686     return $count;
687 }
688
689 sub get_infos_syspref_on_item {
690     my ($syspref_name, $record, $field_list) = @_;
691     my $syspref = C4::Context->preference($syspref_name);
692     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
693     my $yaml = eval {
694         YAML::Load($syspref);
695     };
696     if ( $@ ) {
697         warn "Unable to parse $syspref syspref : $@";
698         return ();
699     }
700     my @result;
701     my @tags_list;
702
703     # Check tags in syspref definition
704     for my $field_name ( @$field_list ) {
705         next unless exists $yaml->{$field_name};
706         my @fields = split /\|/, $yaml->{$field_name};
707         for my $field ( @fields ) {
708             my ( $f, $sf ) = split /\$/, $field;
709             next unless $f and $sf;
710             push @tags_list, $f;
711         }
712     }
713     @tags_list = List::MoreUtils::uniq(@tags_list);
714
715     my $tags_count = equal_number_of_fields(\@tags_list, $record);
716     # Return if the number of theses fields in the record is not the same.
717     return -1 if $tags_count == -1;
718
719     # Gather the fields
720     my $fields_hash;
721     foreach my $tag (@tags_list) {
722         my @tmp_fields;
723         foreach my $field ($record->field($tag)) {
724             push @tmp_fields, $field;
725         }
726         $fields_hash->{$tag} = \@tmp_fields;
727     }
728
729     for (my $i = 0; $i < $tags_count; $i++) {
730         my $r;
731         for my $field_name ( @$field_list ) {
732             next unless exists $yaml->{$field_name};
733             my @fields = split /\|/, $yaml->{$field_name};
734             for my $field ( @fields ) {
735                 my ( $f, $sf ) = split /\$/, $field;
736                 next unless $f and $sf;
737                 my $v = $fields_hash->{$f}[$i]->subfield( $sf );
738                 $r->{$field_name} = $v if (defined $v);
739                 last if $yaml->{$field};
740             }
741         }
742         push @result, $r;
743     }
744     return \@result;
745 }