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