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