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