Bug 24469: Record biblionumber in import_biblio when adding to basket via 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::XS;
28 use List::MoreUtils qw/uniq/;
29 use Encode;
30
31 use C4::Context;
32 use C4::Auth;
33 use C4::Output;
34 use C4::ImportBatch;
35 use C4::Matcher;
36 use C4::Search qw/FindDuplicate/;
37 use C4::Acquisition;
38 use C4::Biblio;
39 use C4::Items;
40 use C4::Koha;
41 use C4::Budgets;
42 use C4::Acquisition;
43 use C4::Suggestions;    # GetSuggestion
44 use C4::Members;
45
46 use Koha::Number::Price;
47 use Koha::Libraries;
48 use Koha::Acquisition::Baskets;
49 use Koha::Acquisition::Currencies;
50 use Koha::Acquisition::Orders;
51 use Koha::Acquisition::Booksellers;
52 use Koha::Patrons;
53
54 my $input = CGI->new;
55 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
56     template_name => "acqui/addorderiso2709.tt",
57     query => $input,
58     type => "intranet",
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     if ( $basket->effective_create_items eq 'ordering' && !$basket->is_standing ) {
107         # prepare empty item form
108         my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
109
110         #     warn "==> ".Data::Dumper::Dumper($cell);
111         unless ($cell) {
112             $cell = PrepareItemrecordDisplay( '', '', '', '' );
113             $template->param( 'NoACQframework' => 1 );
114         }
115         my @itemloop;
116         push @itemloop, $cell;
117
118         $template->param( items => \@itemloop );
119     }
120 #
121 # 3rd step = import the records
122 #
123 } elsif ( $op eq 'import_records' ) {
124 #import selected lines
125     $template->param('basketno' => $cgiparams->{'basketno'});
126 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
127     my $budgets = GetBudgets();
128     if (scalar @$budgets == 0){
129         die "No budgets defined, can't continue";
130     }
131     my $budget_id = @$budgets[0]->{'budget_id'};
132 #get all records from a batch, and check their import status to see if they are checked.
133 #(default values: quantity 1, uncertainprice yes, first budget)
134
135     # retrieve the file you want to import
136     my $import_batch_id = $cgiparams->{'import_batch_id'};
137     my $biblios = GetImportRecordsRange($import_batch_id);
138     my $duplinbatch;
139     my $imported = 0;
140     my @import_record_id_selected = $input->multi_param("import_record_id");
141     my @quantities = $input->multi_param('quantity');
142     my @prices = $input->multi_param('price');
143     my @orderreplacementprices = $input->multi_param('replacementprice');
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         # 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         } else {
199             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
200         }
201
202         my $dbh = C4::Context->dbh;
203         $dbh->do(
204             q|UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?|,
205             undef, $biblionumber, $biblio->{import_record_id}
206         );
207
208         # Add items from MarcItemFieldsToOrder
209         my @homebranches = $input->multi_param('homebranch_' . $biblio_count);
210         my $count = scalar @homebranches;
211         my @holdingbranches = $input->multi_param('holdingbranch_' . $biblio_count);
212         my @itypes = $input->multi_param('itype_' . $biblio_count);
213         my @nonpublic_notes = $input->multi_param('nonpublic_note_' . $biblio_count);
214         my @public_notes = $input->multi_param('public_note_' . $biblio_count);
215         my @locs = $input->multi_param('loc_' . $biblio_count);
216         my @ccodes = $input->multi_param('ccode_' . $biblio_count);
217         my @notforloans = $input->multi_param('notforloan_' . $biblio_count);
218         my @uris = $input->multi_param('uri_' . $biblio_count);
219         my @copynos = $input->multi_param('copyno_' . $biblio_count);
220         my @budget_codes = $input->multi_param('budget_code_' . $biblio_count);
221         my @itemprices = $input->multi_param('itemprice_' . $biblio_count);
222         my @replacementprices = $input->multi_param('replacementprice_' . $biblio_count);
223         my @itemcallnumbers = $input->multi_param('itemcallnumber_' . $biblio_count);
224         my $itemcreation = 0;
225
226         my @itemnumbers;
227         for (my $i = 0; $i < $count; $i++) {
228             $itemcreation = 1;
229             my $item = Koha::Item->new(
230                 {
231                     biblionumber        => $biblionumber,
232                     homebranch          => $homebranches[$i],
233                     holdingbranch       => $holdingbranches[$i],
234                     itemnotes_nonpublic => $nonpublic_notes[$i],
235                     itemnotes           => $public_notes[$i],
236                     location            => $locs[$i],
237                     ccode               => $ccodes[$i],
238                     itype               => $itypes[$i],
239                     notforloan          => $notforloans[$i],
240                     uri                 => $uris[$i],
241                     copynumber          => $copynos[$i],
242                     price               => $itemprices[$i],
243                     replacementprice    => $replacementprices[$i],
244                     itemcallnumber      => $itemcallnumbers[$i],
245                 }
246             )->store;
247             push( @itemnumbers, $item->itemnumber );
248         }
249         if ($itemcreation == 1) {
250             # Group orderlines from MarcItemFieldsToOrder
251             my $budget_hash;
252             for (my $i = 0; $i < $count; $i++) {
253                 $budget_hash->{$budget_codes[$i]}->{quantity} += 1;
254                 $budget_hash->{$budget_codes[$i]}->{price} = $itemprices[$i];
255                 $budget_hash->{$budget_codes[$i]}->{replacementprice} = $replacementprices[$i];
256                 $budget_hash->{$budget_codes[$i]}->{itemnumbers} //= [];
257                 push @{ $budget_hash->{$budget_codes[$i]}->{itemnumbers} }, $itemnumbers[$i];
258             }
259
260             # Create orderlines from MarcItemFieldsToOrder
261             while(my ($budget_id, $infos) = each %$budget_hash) {
262                 if ($budget_id) {
263                     my %orderinfo = (
264                         biblionumber       => $biblionumber,
265                         basketno           => $cgiparams->{'basketno'},
266                         quantity           => $infos->{quantity},
267                         budget_id          => $budget_id,
268                         currency           => $cgiparams->{'all_currency'},
269                     );
270
271                     my $price = $infos->{price};
272                     if ($price){
273                         # in France, the cents separator is the , but sometimes, ppl use a .
274                         # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
275                         $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
276                         $price = Koha::Number::Price->new($price)->unformat;
277                         $orderinfo{tax_rate} = $bookseller->tax_rate;
278                         my $c = $c_discount ? $c_discount : $bookseller->discount / 100;
279                         $orderinfo{discount} = $c;
280                         if ( $c_discount ) {
281                             $orderinfo{ecost} = $price;
282                             $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
283                         } else {
284                             $orderinfo{ecost} = $price * ( 1 - $c );
285                             $orderinfo{rrp}   = $price;
286                         }
287                         $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
288                         $orderinfo{unitprice} = $orderinfo{ecost};
289                         $orderinfo{total} = $orderinfo{ecost} * $infos->{quantity};
290                     } else {
291                         $orderinfo{listprice} = 0;
292                     }
293                     $orderinfo{replacementprice} = $infos->{replacementprice} || 0;
294
295                     # remove uncertainprice flag if we have found a price in the MARC record
296                     $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
297
298                     %orderinfo = %{
299                         C4::Acquisition::populate_order_with_prices(
300                             {
301                                 order        => \%orderinfo,
302                                 booksellerid => $booksellerid,
303                                 ordering     => 1,
304                                 receiving    => 1,
305                             }
306                         )
307                     };
308
309                     my $order = Koha::Acquisition::Order->new( \%orderinfo )->store;
310                     $order->add_item( $_ ) for @{ $budget_hash->{$budget_id}->{itemnumbers} };
311                 }
312             }
313         } else {
314             # 3rd add order
315             my $patron = Koha::Patrons->find( $loggedinuser );
316             # get quantity in the MARC record (1 if none)
317             my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
318             my %orderinfo = (
319                 biblionumber       => $biblionumber,
320                 basketno           => $cgiparams->{'basketno'},
321                 quantity           => $c_quantity,
322                 branchcode         => $patron->branchcode,
323                 budget_id          => $c_budget_id,
324                 uncertainprice     => 1,
325                 sort1              => $c_sort1,
326                 sort2              => $c_sort2,
327                 order_internalnote => $cgiparams->{'all_order_internalnote'},
328                 order_vendornote   => $cgiparams->{'all_order_vendornote'},
329                 currency           => $cgiparams->{'all_currency'},
330                 replacementprice   => shift( @orderreplacementprices ),
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 ( $c_discount ) {
343                     $orderinfo{ecost} = $price;
344                     $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
345                 } else {
346                     $orderinfo{ecost} = $price * ( 1 - $c );
347                     $orderinfo{rrp}   = $price;
348                 }
349                 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
350                 $orderinfo{unitprice} = $orderinfo{ecost};
351                 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
352             } else {
353                 $orderinfo{listprice} = 0;
354             }
355
356         # remove uncertainprice flag if we have found a price in the MARC record
357         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
358
359         %orderinfo = %{
360             C4::Acquisition::populate_order_with_prices(
361                 {
362                     order        => \%orderinfo,
363                     booksellerid => $booksellerid,
364                     ordering     => 1,
365                     receiving    => 1,
366                 }
367             )
368         };
369
370         my $order = Koha::Acquisition::Order->new( \%orderinfo )->store;
371
372         # 4th, add items if applicable
373         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
374         # this is not optimised, but it's working !
375         if ( $basket->effective_create_items eq 'ordering' && !$basket->is_standing ) {
376             my @tags         = $input->multi_param('tag');
377             my @subfields    = $input->multi_param('subfield');
378             my @field_values = $input->multi_param('field_value');
379             my @serials      = $input->multi_param('serial');
380             my @ind_tag   = $input->multi_param('ind_tag');
381             my @indicator = $input->multi_param('indicator');
382             my $item;
383             push @{ $item->{tags} },         $tags[0];
384             push @{ $item->{subfields} },    $subfields[0];
385             push @{ $item->{field_values} }, $field_values[0];
386             push @{ $item->{ind_tag} },      $ind_tag[0];
387             push @{ $item->{indicator} },    $indicator[0];
388             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@indicator, \@ind_tag );
389             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
390             for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
391                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
392                 $order->add_item( $itemnumber );
393                 }
394             } else {
395                 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
396             }
397         }
398         $imported++;
399     }
400
401     # If all bibliographic records from the batch have been imported we modifying the status of the batch accordingly
402     SetImportBatchStatus( $import_batch_id, 'imported' )
403         if    @{ GetImportRecordsRange( $import_batch_id, undef, undef, 'imported' )}
404            == @{ GetImportRecordsRange( $import_batch_id )};
405
406     # go to basket page
407     if ( $imported ) {
408         print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
409     } else {
410         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");
411     }
412     exit;
413 }
414
415 my $budgets = GetBudgets();
416 my $budget_id = @$budgets[0]->{'budget_id'};
417 # build bookfund list
418 my $patron = Koha::Patrons->find( $loggedinuser )->unblessed;
419 my $budget = GetBudget($budget_id);
420
421 # build budget list
422 my $budget_loop = [];
423 my $budgets_hierarchy = GetBudgetHierarchy;
424 foreach my $r ( @{$budgets_hierarchy} ) {
425     next unless (CanUserUseBudget($patron, $r, $userflags));
426     push @{$budget_loop},
427       { b_id  => $r->{budget_id},
428         b_txt => $r->{budget_name},
429         b_code => $r->{budget_code},
430         b_sort1_authcat => $r->{'sort1_authcat'},
431         b_sort2_authcat => $r->{'sort2_authcat'},
432         b_active => $r->{budget_period_active},
433         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
434       };
435 }
436
437 @{$budget_loop} =
438   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
439
440 $template->param( budget_loop    => $budget_loop,);
441
442 output_html_with_http_headers $input, $cookie, $template->output;
443
444
445 sub import_batches_list {
446     my ($template) = @_;
447     my $batches = GetImportBatchRangeDesc();
448
449     my @list = ();
450     foreach my $batch (@$batches) {
451         if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
452             # check if there is at least 1 line still staged
453             my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
454             if (scalar @$stagedList) {
455                 push @list, {
456                         import_batch_id => $batch->{'import_batch_id'},
457                         num_records => $batch->{'num_records'},
458                         num_items => $batch->{'num_items'},
459                         staged_date => $batch->{'upload_timestamp'},
460                         import_status => $batch->{'import_status'},
461                         file_name => $batch->{'file_name'},
462                         comments => $batch->{'comments'},
463                 };
464             } else {
465                 # if there are no more line to includes, set the status to imported
466                 # FIXME This should be removed in the future.
467                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
468             }
469         }
470     }
471     $template->param(batch_list => \@list); 
472     my $num_batches = GetNumberOfNonZ3950ImportBatches();
473     $template->param(num_results => $num_batches);
474 }
475
476 sub import_biblios_list {
477     my ($template, $import_batch_id) = @_;
478     my $batch = GetImportBatch($import_batch_id,'staged');
479     return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
480     my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
481     my @list = ();
482     my $item_error = 0;
483
484     my $ccodes = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' } ) };
485     my $locations = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
486     my $notforloans = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.notforloan' } ) };
487     # location list
488     my @locations;
489     foreach (sort keys %$locations) {
490         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
491     }
492     my @ccodes;
493     foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
494         push @ccodes, { code => $_, description => $ccodes->{$_} };
495     }
496     my @notforloans;
497     foreach (sort {$notforloans->{$a} cmp $notforloans->{$b}} keys %$notforloans) {
498         push @notforloans, { code => $_, description => $notforloans->{$_} };
499     }
500
501     my $biblio_count = 0;
502     foreach my $biblio (@$biblios) {
503         my $item_id = 1;
504         $biblio_count++;
505         my $citation = $biblio->{'title'};
506         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
507         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
508         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
509         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
510         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
511         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
512         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
513         my %cellrecord = (
514             import_record_id => $biblio->{'import_record_id'},
515             citation => $citation,
516             import  => 1,
517             status => $biblio->{'status'},
518             record_sequence => $biblio->{'record_sequence'},
519             overlay_status => $biblio->{'overlay_status'},
520             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
521             match_citation     => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
522             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
523         );
524         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
525         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
526
527         my $infos = get_infos_syspref('MarcFieldsToOrder', $marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2','replacementprice']);
528         my $price = $infos->{price};
529         my $replacementprice = $infos->{replacementprice};
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_budget_id;
562                 if ( $iteminfos->{budget_code} ) {
563                     my $item_budget = GetBudgetByCode( $iteminfos->{budget_code} );
564                     if ( $item_budget ) {
565                         $item_budget_id = $item_budget->{budget_id};
566                     }
567                 }
568                 my $item_price = $iteminfos->{price};
569                 my $item_replacement_price = $iteminfos->{replacementprice};
570                 my $item_callnumber = $iteminfos->{itemcallnumber};
571
572                 for (my $i = 0; $i < $item_quantity; $i++) {
573
574                     my %itemrecord = (
575                         'item_id' => $item_id++,
576                         'biblio_count' => $biblio_count,
577                         'homebranch' => $item_homebranch,
578                         'holdingbranch' => $item_holdingbranch,
579                         'itype' => $item_itype,
580                         'nonpublic_note' => $item_nonpublic_note,
581                         'public_note' => $item_public_note,
582                         'loc' => $item_loc,
583                         'ccode' => $item_ccode,
584                         'notforloan' => $item_notforloan,
585                         'uri' => $item_uri,
586                         'copyno' => $item_copyno,
587                         'quantity' => $item_quantity,
588                         'budget_id' => $item_budget_id || $budget_id,
589                         'itemprice' => $item_price || $price,
590                         'replacementprice' => $item_replacement_price || $replacementprice,
591                         'itemcallnumber' => $item_callnumber,
592                     );
593                     $all_items_quantity++;
594                     push @itemlist, \%itemrecord;
595
596                 }
597             }
598
599             $cellrecord{'iteminfos'} = \@itemlist;
600         } else {
601             $cellrecord{'item_error'} = 1;
602         }
603         push @list, \%cellrecord;
604
605         if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
606             $cellrecord{price} = $price || '';
607             $cellrecord{replacementprice} = $replacementprice || '';
608             $cellrecord{quantity} = $quantity || '';
609             $cellrecord{budget_id} = $budget_id || '';
610             $cellrecord{discount} = $discount || '';
611             $cellrecord{sort1} = $sort1 || '';
612             $cellrecord{sort2} = $sort2 || '';
613         } else {
614             $cellrecord{quantity} = $all_items_quantity;
615         }
616
617     }
618     my $num_records = $batch->{'num_records'};
619     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
620     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
621     my $item_action = GetImportBatchItemAction($import_batch_id);
622     my @itypes = Koha::ItemTypes->search;
623     $template->param(biblio_list => \@list,
624                         num_results => $num_records,
625                         import_batch_id => $import_batch_id,
626                         "overlay_action_${overlay_action}" => 1,
627                         overlay_action => $overlay_action,
628                         "nomatch_action_${nomatch_action}" => 1,
629                         nomatch_action => $nomatch_action,
630                         "item_action_${item_action}" => 1,
631                         item_action => $item_action,
632                         item_error => $item_error,
633                         libraries => scalar Koha::Libraries->search(),
634                         locationloop => \@locations,
635                         itypeloop => \@itypes,
636                         ccodeloop => \@ccodes,
637                         notforloanloop => \@notforloans,
638                     );
639     batch_info($template, $batch);
640 }
641
642 sub batch_info {
643     my ($template, $batch) = @_;
644     $template->param(batch_info => 1,
645                                       file_name => $batch->{'file_name'},
646                                           comments => $batch->{'comments'},
647                                           import_status => $batch->{'import_status'},
648                                           upload_timestamp => $batch->{'upload_timestamp'},
649                                           num_records => $batch->{'num_records'},
650                                           num_items => $batch->{'num_items'});
651     if ($batch->{'num_records'} > 0) {
652         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
653             $template->param(can_commit => 1);
654         }
655         if ($batch->{'import_status'} eq 'imported') {
656             $template->param(can_revert => 1);
657         }
658     }
659     if (defined $batch->{'matcher_id'}) {
660         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
661         if (defined $matcher) {
662             $template->param('current_matcher_id' => $batch->{'matcher_id'},
663                                               'current_matcher_code' => $matcher->code(),
664                                               'current_matcher_description' => $matcher->description());
665         }
666     }
667     add_matcher_list($batch->{'matcher_id'}, $template);
668 }
669
670 sub add_matcher_list {
671     my ($current_matcher_id, $template) = @_;
672     my @matchers = C4::Matcher::GetMatcherList();
673     if (defined $current_matcher_id) {
674         for (my $i = 0; $i <= $#matchers; $i++) {
675             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
676                 $matchers[$i]->{'selected'} = 1;
677             }
678         }
679     }
680     $template->param(available_matchers => \@matchers);
681 }
682
683 sub get_infos_syspref {
684     my ($syspref_name, $record, $field_list) = @_;
685     my $syspref = C4::Context->preference($syspref_name);
686     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
687     my $yaml = eval {
688         YAML::XS::Load(Encode::encode_utf8($syspref));
689     };
690     if ( $@ ) {
691         warn "Unable to parse $syspref syspref : $@";
692         return ();
693     }
694     my $r;
695     for my $field_name ( @$field_list ) {
696         next unless exists $yaml->{$field_name};
697         my @fields = split /\|/, $yaml->{$field_name};
698         for my $field ( @fields ) {
699             my ( $f, $sf ) = split /\$/, $field;
700             next unless $f and $sf;
701             if ( my $v = $record->subfield( $f, $sf ) ) {
702                 $r->{$field_name} = $v;
703             }
704             last if $yaml->{$field};
705         }
706     }
707     return $r;
708 }
709
710 sub equal_number_of_fields {
711     my ($tags_list, $record) = @_;
712     my $tag_fields_count;
713     for my $tag (@$tags_list) {
714         my @fields = $record->field($tag);
715         $tag_fields_count->{$tag} = scalar @fields;
716     }
717
718     my $tags_count;
719     foreach my $key ( keys %$tag_fields_count ) {
720         if ( $tag_fields_count->{$key} > 0 ) { # Having 0 of a field is ok
721             $tags_count //= $tag_fields_count->{$key}; # Start with the count from the first occurrence
722             return -1 if $tag_fields_count->{$key} != $tags_count; # All counts of various fields should be equal if they exist
723         }
724     }
725
726     return $tags_count;
727 }
728
729 sub get_infos_syspref_on_item {
730     my ($syspref_name, $record, $field_list) = @_;
731     my $syspref = C4::Context->preference($syspref_name);
732     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
733     my $yaml = eval {
734         YAML::XS::Load(Encode::encode_utf8($syspref));
735     };
736     if ( $@ ) {
737         warn "Unable to parse $syspref syspref : $@";
738         return ();
739     }
740     my @result;
741     my @tags_list;
742
743     # Check tags in syspref definition
744     for my $field_name ( @$field_list ) {
745         next unless exists $yaml->{$field_name};
746         my @fields = split /\|/, $yaml->{$field_name};
747         for my $field ( @fields ) {
748             my ( $f, $sf ) = split /\$/, $field;
749             next unless $f and $sf;
750             push @tags_list, $f;
751         }
752     }
753     @tags_list = List::MoreUtils::uniq(@tags_list);
754
755     my $tags_count = equal_number_of_fields(\@tags_list, $record);
756     # Return if the number of these fields in the record is not the same.
757     return -1 if $tags_count == -1;
758
759     # Gather the fields
760     my $fields_hash;
761     foreach my $tag (@tags_list) {
762         my @tmp_fields;
763         foreach my $field ($record->field($tag)) {
764             push @tmp_fields, $field;
765         }
766         $fields_hash->{$tag} = \@tmp_fields;
767     }
768
769     for (my $i = 0; $i < $tags_count; $i++) {
770         my $r;
771         for my $field_name ( @$field_list ) {
772             next unless exists $yaml->{$field_name};
773             my @fields = split /\|/, $yaml->{$field_name};
774             for my $field ( @fields ) {
775                 my ( $f, $sf ) = split /\$/, $field;
776                 next unless $f and $sf;
777                 my $v = $fields_hash->{$f}[$i] ? $fields_hash->{$f}[$i]->subfield( $sf ) : undef;
778                 $r->{$field_name} = $v if (defined $v);
779                 last if $yaml->{$field};
780             }
781         }
782         push @result, $r;
783     }
784     return \@result;
785 }