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