Bug 30477: Add new UNIMARC installer translation files
[koha.git] / acqui / addorderiso2709.pl
1 #!/usr/bin/perl
2
3 #A script that lets the user populate a basket from an iso2709 file
4 #the script first displays a list of import batches, then when a batch is selected displays all the biblios in it.
5 #The user can then pick which biblios 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 YAML::XS;
27 use List::MoreUtils;
28 use Encode;
29
30 use C4::Context;
31 use C4::Auth qw( get_template_and_user );
32 use C4::Output qw( output_html_with_http_headers );
33 use C4::ImportBatch qw( GetImportRecordsRange GetImportRecordMarc GetImportRecordMatches SetImportRecordStatus SetMatchedBiblionumber SetImportBatchStatus GetImportBatch GetImportBatchRangeDesc GetNumberOfNonZ3950ImportBatches GetImportBatchOverlayAction GetImportBatchNoMatchAction GetImportBatchItemAction );
34 use C4::Matcher;
35 use C4::Search qw( FindDuplicate );
36 use C4::Acquisition qw( populate_order_with_prices );
37 use C4::Biblio qw(
38     AddBiblio
39     GetMarcFromKohaField
40     GetMarcPrice
41     GetMarcQuantity
42     TransformHtmlToXml
43 );
44 use C4::Items qw( PrepareItemrecordDisplay AddItemFromMarc );
45 use C4::Budgets qw( GetBudget GetBudgets GetBudgetHierarchy CanUserUseBudget GetBudgetByCode );
46 use C4::Acquisition qw( populate_order_with_prices );
47 use C4::Suggestions;    # GetSuggestion
48 use C4::Members;
49
50 use Koha::Number::Price;
51 use Koha::Libraries;
52 use Koha::Acquisition::Baskets;
53 use Koha::Acquisition::Currencies;
54 use Koha::Acquisition::Orders;
55 use Koha::Acquisition::Booksellers;
56 use Koha::Patrons;
57
58 my $input = CGI->new;
59 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
60     template_name => "acqui/addorderiso2709.tt",
61     query => $input,
62     type => "intranet",
63     flagsrequired   => { acquisition => 'order_manage' },
64 });
65
66 my $cgiparams = $input->Vars;
67 my $op = $cgiparams->{'op'} || '';
68 my $booksellerid  = $input->param('booksellerid');
69 my $allmatch = $input->param('allmatch');
70 my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
71
72 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
73                 booksellerid => $booksellerid,
74                 booksellername => $bookseller->name,
75                 );
76
77 if ($cgiparams->{'import_batch_id'} && $op eq ""){
78     $op = "batch_details";
79 }
80
81 #Needed parameters:
82 if (! $cgiparams->{'basketno'}){
83     die "Basketnumber required to order from iso2709 file import";
84 }
85 my $basket = Koha::Acquisition::Baskets->find( $cgiparams->{basketno} );
86
87 #
88 # 1st step = choose the file to import into acquisition
89 #
90 if ($op eq ""){
91     $template->param("basketno" => $cgiparams->{'basketno'});
92 #display batches
93     import_batches_list($template);
94 #
95 # 2nd step = display the content of the chosen file
96 #
97 } elsif ($op eq "batch_details"){
98 #display lines inside the selected batch
99
100     $template->param("batch_details" => 1,
101                      "basketno"      => $cgiparams->{'basketno'},
102                      # get currencies (for change rates calcs if needed)
103                      currencies => Koha::Acquisition::Currencies->search,
104                      bookseller => $bookseller,
105                      "allmatch" => $allmatch,
106                      );
107     import_biblios_list($template, $cgiparams->{'import_batch_id'});
108     if ( $basket->effective_create_items eq 'ordering' && !$basket->is_standing ) {
109         # prepare empty item form
110         my $cell = PrepareItemrecordDisplay( '', '', undef, 'ACQ' );
111
112         #     warn "==> ".Data::Dumper::Dumper($cell);
113         unless ($cell) {
114             $cell = PrepareItemrecordDisplay( '', '', undef, '' );
115             $template->param( 'NoACQframework' => 1 );
116         }
117         my @itemloop;
118         push @itemloop, $cell;
119
120         $template->param( items => \@itemloop );
121     }
122 #
123 # 3rd step = import the records
124 #
125 } elsif ( $op eq 'import_records' ) {
126 #import selected lines
127     $template->param('basketno' => $cgiparams->{'basketno'});
128 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
129     my $budgets = GetBudgets();
130     if (scalar @$budgets == 0){
131         die "No budgets defined, can't continue";
132     }
133     my $budget_id = @$budgets[0]->{'budget_id'};
134 #get all records from a batch, and check their import status to see if they are checked.
135 #(default values: quantity 1, uncertainprice yes, first budget)
136
137     # retrieve the file you want to import
138     my $import_batch_id = $cgiparams->{'import_batch_id'};
139     my $biblios = GetImportRecordsRange($import_batch_id);
140     my $duplinbatch;
141     my $imported = 0;
142     my @import_record_id_selected = $input->multi_param("import_record_id");
143     my @quantities = $input->multi_param('quantity');
144     my @prices = $input->multi_param('price');
145     my @orderreplacementprices = $input->multi_param('replacementprice');
146     my @budgets_id = $input->multi_param('budget_id');
147     my @discount = $input->multi_param('discount');
148     my @sort1 = $input->multi_param('sort1');
149     my @sort2 = $input->multi_param('sort2');
150     my $matcher_id = $input->param('matcher_id');
151     my $active_currency = Koha::Acquisition::Currencies->get_active;
152     my $biblio_count = 0;
153     for my $biblio (@$biblios){
154         $biblio_count++;
155         my $duplifound = 0;
156         # Check if this import_record_id was selected
157         next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
158         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
159         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
160         my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
161         my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
162         my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
163         my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
164         my $c_discount = shift ( @discount);
165         $c_discount = $c_discount / 100 if $c_discount > 1;
166         my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
167         my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
168         my $c_replacement_price = shift( @orderreplacementprices );
169         my $c_price = shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
170
171         # Insert the biblio, or find it through matcher
172         unless ( $biblionumber ) {
173             if ($matcher_id) {
174                 if ( $matcher_id eq '_TITLE_AUTHOR_' ) {
175                     $duplifound = 1 if FindDuplicate($marcrecord);
176                 }
177                 else {
178                     my $matcher = C4::Matcher->fetch($matcher_id);
179                     my @matches = $matcher->get_matches( $marcrecord, my $max_matches = 1 );
180                     $duplifound = 1 if @matches;
181                 }
182
183                 $duplinbatch = $import_batch_id and next if $duplifound;
184             }
185
186             # add the biblio
187             my $bibitemnum;
188
189             # remove ISBN -
190             my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn' );
191             if ( $marcrecord->field($isbnfield) ) {
192                 foreach my $field ( $marcrecord->field($isbnfield) ) {
193                     foreach my $subfield ( $field->subfield($isbnsubfield) ) {
194                         my $newisbn = $field->subfield($isbnsubfield);
195                         $newisbn =~ s/-//g;
196                         $field->update( $isbnsubfield => $newisbn );
197                     }
198                 }
199             }
200             ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
201             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
202         } else {
203             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
204         }
205
206         SetMatchedBiblionumber( $biblio->{import_record_id}, $biblionumber );
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   => $c_replacement_price,
331             );
332             # get the price if there is one.
333             if ($c_price){
334                 # in France, the cents separator is the , but sometimes, ppl use a .
335                 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
336                 $c_price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
337                 $c_price = Koha::Number::Price->new($c_price)->unformat;
338                 $orderinfo{tax_rate} = $bookseller->tax_rate;
339                 my $c = $c_discount ? $c_discount : $bookseller->discount / 100;
340                 $orderinfo{discount} = $c;
341                 if ( $c_discount ) {
342                     $orderinfo{ecost} = $c_price;
343                     $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
344                 } else {
345                     $orderinfo{ecost} = $c_price * ( 1 - $c );
346                     $orderinfo{rrp}   = $c_price;
347                 }
348                 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
349                 $orderinfo{unitprice} = $orderinfo{ecost};
350                 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
351             } else {
352                 $orderinfo{listprice} = 0;
353             }
354
355         # remove uncertainprice flag if we have found a price in the MARC record
356         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
357
358         %orderinfo = %{
359             C4::Acquisition::populate_order_with_prices(
360                 {
361                     order        => \%orderinfo,
362                     booksellerid => $booksellerid,
363                     ordering     => 1,
364                     receiving    => 1,
365                 }
366             )
367         };
368
369         my $order = Koha::Acquisition::Order->new( \%orderinfo )->store;
370
371         # 4th, add items if applicable
372         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
373         # this is not optimised, but it's working !
374         if ( $basket->effective_create_items eq 'ordering' && !$basket->is_standing ) {
375             my @tags         = $input->multi_param('tag');
376             my @subfields    = $input->multi_param('subfield');
377             my @field_values = $input->multi_param('field_value');
378             my @serials      = $input->multi_param('serial');
379             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values );
380             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
381             for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
382                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
383                 $order->add_item( $itemnumber );
384                 }
385             } else {
386                 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
387             }
388         }
389         $imported++;
390     }
391
392     # If all bibliographic records from the batch have been imported we modifying the status of the batch accordingly
393     SetImportBatchStatus( $import_batch_id, 'imported' )
394         if    @{ GetImportRecordsRange( $import_batch_id, undef, undef, 'imported' )}
395            == @{ GetImportRecordsRange( $import_batch_id )};
396
397     # go to basket page
398     if ( $imported ) {
399         print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
400     } else {
401         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");
402     }
403     exit;
404 }
405
406 my $budgets = GetBudgets();
407 my $budget_id = @$budgets[0]->{'budget_id'};
408 # build bookfund list
409 my $patron = Koha::Patrons->find( $loggedinuser )->unblessed;
410 my $budget = GetBudget($budget_id);
411
412 # build budget list
413 my $budget_loop = [];
414 my $budgets_hierarchy = GetBudgetHierarchy;
415 foreach my $r ( @{$budgets_hierarchy} ) {
416     next unless (CanUserUseBudget($patron, $r, $userflags));
417     push @{$budget_loop},
418       { b_id  => $r->{budget_id},
419         b_txt => $r->{budget_name},
420         b_code => $r->{budget_code},
421         b_sort1_authcat => $r->{'sort1_authcat'},
422         b_sort2_authcat => $r->{'sort2_authcat'},
423         b_active => $r->{budget_period_active},
424         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
425       };
426 }
427
428 @{$budget_loop} =
429   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
430
431 $template->param( budget_loop    => $budget_loop,);
432
433 output_html_with_http_headers $input, $cookie, $template->output;
434
435
436 sub import_batches_list {
437     my ($template) = @_;
438     my $batches = GetImportBatchRangeDesc();
439
440     my @list = ();
441     foreach my $batch (@$batches) {
442         if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
443             # check if there is at least 1 line still staged
444             my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
445             if (scalar @$stagedList) {
446                 push @list, {
447                         import_batch_id => $batch->{'import_batch_id'},
448                         num_records => $batch->{'num_records'},
449                         num_items => $batch->{'num_items'},
450                         staged_date => $batch->{'upload_timestamp'},
451                         import_status => $batch->{'import_status'},
452                         file_name => $batch->{'file_name'},
453                         comments => $batch->{'comments'},
454                 };
455             } else {
456                 # if there are no more line to includes, set the status to imported
457                 # FIXME This should be removed in the future.
458                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
459             }
460         }
461     }
462     $template->param(batch_list => \@list); 
463     my $num_batches = GetNumberOfNonZ3950ImportBatches();
464     $template->param(num_results => $num_batches);
465 }
466
467 sub import_biblios_list {
468     my ($template, $import_batch_id) = @_;
469     my $batch = GetImportBatch($import_batch_id,'staged');
470     return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
471     my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
472     my @list = ();
473     my $item_error = 0;
474
475     my $ccodes = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' } ) };
476     my $locations = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
477     my $notforloans = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.notforloan' } ) };
478     # location list
479     my @locations;
480     foreach (sort keys %$locations) {
481         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
482     }
483     my @ccodes;
484     foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
485         push @ccodes, { code => $_, description => $ccodes->{$_} };
486     }
487     my @notforloans;
488     foreach (sort {$notforloans->{$a} cmp $notforloans->{$b}} keys %$notforloans) {
489         push @notforloans, { code => $_, description => $notforloans->{$_} };
490     }
491
492     my $biblio_count = 0;
493     foreach my $biblio (@$biblios) {
494         my $item_id = 1;
495         $biblio_count++;
496         my $citation = $biblio->{'title'};
497         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
498         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
499         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
500         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
501         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
502         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
503         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
504         my %cellrecord = (
505             import_record_id => $biblio->{'import_record_id'},
506             citation => $citation,
507             import  => 1,
508             status => $biblio->{'status'},
509             record_sequence => $biblio->{'record_sequence'},
510             overlay_status => $biblio->{'overlay_status'},
511             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
512             match_citation     => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
513             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
514         );
515         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
516         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
517
518         my $infos = get_infos_syspref('MarcFieldsToOrder', $marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2','replacementprice']);
519         my $price = $infos->{price};
520         my $replacementprice = $infos->{replacementprice};
521         my $quantity = $infos->{quantity};
522         my $budget_code = $infos->{budget_code};
523         my $discount = $infos->{discount};
524         my $sort1 = $infos->{sort1};
525         my $sort2 = $infos->{sort2};
526         my $budget_id;
527         if($budget_code) {
528             my $biblio_budget = GetBudgetByCode($budget_code);
529             if($biblio_budget) {
530                 $budget_id = $biblio_budget->{budget_id};
531             }
532         }
533
534         # Items
535         my @itemlist = ();
536         my $all_items_quantity = 0;
537         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']);
538         if ($alliteminfos != -1) {
539             foreach my $iteminfos (@$alliteminfos) {
540                 my $item_homebranch = $iteminfos->{homebranch};
541                 my $item_holdingbranch = $iteminfos->{holdingbranch};
542                 my $item_itype = $iteminfos->{itype};
543                 my $item_nonpublic_note = $iteminfos->{nonpublic_note};
544                 my $item_public_note = $iteminfos->{public_note};
545                 my $item_loc = $iteminfos->{loc};
546                 my $item_ccode = $iteminfos->{ccode};
547                 my $item_notforloan = $iteminfos->{notforloan};
548                 my $item_uri = $iteminfos->{uri};
549                 my $item_copyno = $iteminfos->{copyno};
550                 my $item_quantity = $iteminfos->{quantity} || 1;
551                 my $item_budget_code = $iteminfos->{budget_code};
552                 my $item_budget_id;
553                 if ( $iteminfos->{budget_code} ) {
554                     my $item_budget = GetBudgetByCode( $iteminfos->{budget_code} );
555                     if ( $item_budget ) {
556                         $item_budget_id = $item_budget->{budget_id};
557                     }
558                 }
559                 my $item_price = $iteminfos->{price};
560                 my $item_replacement_price = $iteminfos->{replacementprice};
561                 my $item_callnumber = $iteminfos->{itemcallnumber};
562
563                 for (my $i = 0; $i < $item_quantity; $i++) {
564
565                     my %itemrecord = (
566                         'item_id' => $item_id++,
567                         'biblio_count' => $biblio_count,
568                         'homebranch' => $item_homebranch,
569                         'holdingbranch' => $item_holdingbranch,
570                         'itype' => $item_itype,
571                         'nonpublic_note' => $item_nonpublic_note,
572                         'public_note' => $item_public_note,
573                         'loc' => $item_loc,
574                         'ccode' => $item_ccode,
575                         'notforloan' => $item_notforloan,
576                         'uri' => $item_uri,
577                         'copyno' => $item_copyno,
578                         'quantity' => $item_quantity,
579                         'budget_id' => $item_budget_id || $budget_id,
580                         'itemprice' => $item_price || $price,
581                         'replacementprice' => $item_replacement_price || $replacementprice,
582                         'itemcallnumber' => $item_callnumber,
583                     );
584                     $all_items_quantity++;
585                     push @itemlist, \%itemrecord;
586
587                 }
588             }
589
590             $cellrecord{'iteminfos'} = \@itemlist;
591         } else {
592             $cellrecord{'item_error'} = 1;
593         }
594         push @list, \%cellrecord;
595
596         if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
597             $cellrecord{price} = $price || '';
598             $cellrecord{replacementprice} = $replacementprice || '';
599             $cellrecord{quantity} = $quantity || '';
600             $cellrecord{budget_id} = $budget_id || '';
601             $cellrecord{discount} = $discount || '';
602             $cellrecord{sort1} = $sort1 || '';
603             $cellrecord{sort2} = $sort2 || '';
604         } else {
605             $cellrecord{quantity} = $all_items_quantity;
606         }
607
608     }
609     my $num_records = $batch->{'num_records'};
610     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
611     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
612     my $item_action = GetImportBatchItemAction($import_batch_id);
613     $template->param(biblio_list => \@list,
614                         num_results => $num_records,
615                         import_batch_id => $import_batch_id,
616                         "overlay_action_${overlay_action}" => 1,
617                         overlay_action => $overlay_action,
618                         "nomatch_action_${nomatch_action}" => 1,
619                         nomatch_action => $nomatch_action,
620                         "item_action_${item_action}" => 1,
621                         item_action => $item_action,
622                         item_error => $item_error,
623                         libraries => Koha::Libraries->search,
624                         locationloop => \@locations,
625                         itemtypes => Koha::ItemTypes->search,
626                         ccodeloop => \@ccodes,
627                         notforloanloop => \@notforloans,
628                     );
629     batch_info($template, $batch);
630 }
631
632 sub batch_info {
633     my ($template, $batch) = @_;
634     $template->param(batch_info => 1,
635                                       file_name => $batch->{'file_name'},
636                                           comments => $batch->{'comments'},
637                                           import_status => $batch->{'import_status'},
638                                           upload_timestamp => $batch->{'upload_timestamp'},
639                                           num_records => $batch->{'num_records'},
640                                           num_items => $batch->{'num_items'});
641     if ($batch->{'num_records'} > 0) {
642         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
643             $template->param(can_commit => 1);
644         }
645         if ($batch->{'import_status'} eq 'imported') {
646             $template->param(can_revert => 1);
647         }
648     }
649     if (defined $batch->{'matcher_id'}) {
650         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
651         if (defined $matcher) {
652             $template->param('current_matcher_id' => $batch->{'matcher_id'},
653                                               'current_matcher_code' => $matcher->code(),
654                                               'current_matcher_description' => $matcher->description());
655         }
656     }
657     add_matcher_list($batch->{'matcher_id'}, $template);
658 }
659
660 sub add_matcher_list {
661     my ($current_matcher_id, $template) = @_;
662     my @matchers = C4::Matcher::GetMatcherList();
663     if (defined $current_matcher_id) {
664         for (my $i = 0; $i <= $#matchers; $i++) {
665             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
666                 $matchers[$i]->{'selected'} = 1;
667             }
668         }
669     }
670     $template->param(available_matchers => \@matchers);
671 }
672
673 sub get_infos_syspref {
674     my ($syspref_name, $record, $field_list) = @_;
675     my $syspref = C4::Context->preference($syspref_name);
676     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
677     my $yaml = eval {
678         YAML::XS::Load(Encode::encode_utf8($syspref));
679     };
680     if ( $@ ) {
681         warn "Unable to parse $syspref syspref : $@";
682         return ();
683     }
684     my $r;
685     for my $field_name ( @$field_list ) {
686         next unless exists $yaml->{$field_name};
687         my @fields = split /\|/, $yaml->{$field_name};
688         for my $field ( @fields ) {
689             my ( $f, $sf ) = split /\$/, $field;
690             next unless $f and $sf;
691             if ( my $v = $record->subfield( $f, $sf ) ) {
692                 $r->{$field_name} = $v;
693             }
694             last if $yaml->{$field};
695         }
696     }
697     return $r;
698 }
699
700 sub equal_number_of_fields {
701     my ($tags_list, $record) = @_;
702     my $tag_fields_count;
703     for my $tag (@$tags_list) {
704         my @fields = $record->field($tag);
705         $tag_fields_count->{$tag} = scalar @fields;
706     }
707
708     my $tags_count;
709     foreach my $key ( keys %$tag_fields_count ) {
710         if ( $tag_fields_count->{$key} > 0 ) { # Having 0 of a field is ok
711             $tags_count //= $tag_fields_count->{$key}; # Start with the count from the first occurrence
712             return -1 if $tag_fields_count->{$key} != $tags_count; # All counts of various fields should be equal if they exist
713         }
714     }
715
716     return $tags_count;
717 }
718
719 sub get_infos_syspref_on_item {
720     my ($syspref_name, $record, $field_list) = @_;
721     my $syspref = C4::Context->preference($syspref_name);
722     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
723     my $yaml = eval {
724         YAML::XS::Load(Encode::encode_utf8($syspref));
725     };
726     if ( $@ ) {
727         warn "Unable to parse $syspref syspref : $@";
728         return ();
729     }
730     my @result;
731     my @tags_list;
732
733     # Check tags in syspref definition
734     for my $field_name ( @$field_list ) {
735         next unless exists $yaml->{$field_name};
736         my @fields = split /\|/, $yaml->{$field_name};
737         for my $field ( @fields ) {
738             my ( $f, $sf ) = split /\$/, $field;
739             next unless $f and $sf;
740             push @tags_list, $f;
741         }
742     }
743     @tags_list = List::MoreUtils::uniq(@tags_list);
744
745     my $tags_count = equal_number_of_fields(\@tags_list, $record);
746     # Return if the number of these fields in the record is not the same.
747     return -1 if $tags_count == -1;
748
749     # Gather the fields
750     my $fields_hash;
751     foreach my $tag (@tags_list) {
752         my @tmp_fields;
753         foreach my $field ($record->field($tag)) {
754             push @tmp_fields, $field;
755         }
756         $fields_hash->{$tag} = \@tmp_fields;
757     }
758
759     for (my $i = 0; $i < $tags_count; $i++) {
760         my $r;
761         for my $field_name ( @$field_list ) {
762             next unless exists $yaml->{$field_name};
763             my @fields = split /\|/, $yaml->{$field_name};
764             for my $field ( @fields ) {
765                 my ( $f, $sf ) = split /\$/, $field;
766                 next unless $f and $sf;
767                 my $v = $fields_hash->{$f}[$i] ? $fields_hash->{$f}[$i]->subfield( $sf ) : undef;
768                 $r->{$field_name} = $v if (defined $v);
769                 last if $yaml->{$field};
770             }
771         }
772         push @result, $r;
773     }
774     return \@result;
775 }