Bug 25756: remove erroneous hyphen
[koha.git] / acqui / addorderiso2709.pl
blob224f38a0ab29c9d51bfd26df58caf41eb982e8a6
1 #!/usr/bin/perl
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
7 # Copyright 2008 - 2011 BibLibre SARL
9 # This file is part of Koha.
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.
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.
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>.
24 use Modern::Perl;
25 use CGI qw ( -utf8 );
26 use Carp;
27 use YAML qw/Load/;
28 use List::MoreUtils qw/uniq/;
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;
45 use Koha::Number::Price;
46 use Koha::Libraries;
47 use Koha::Acquisition::Baskets;
48 use Koha::Acquisition::Currencies;
49 use Koha::Acquisition::Orders;
50 use Koha::Acquisition::Booksellers;
51 use Koha::Patrons;
53 my $input = new CGI;
54 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
55 template_name => "acqui/addorderiso2709.tt",
56 query => $input,
57 type => "intranet",
58 authnotrequired => 0,
59 flagsrequired => { acquisition => 'order_manage' },
60 debug => 1,
61 });
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 );
69 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
70 booksellerid => $booksellerid,
71 booksellername => $bookseller->name,
74 if ($cgiparams->{'import_batch_id'} && $op eq ""){
75 $op = "batch_details";
78 #Needed parameters:
79 if (! $cgiparams->{'basketno'}){
80 die "Basketnumber required to order from iso2709 file import";
82 my $basket = Koha::Acquisition::Baskets->find( $cgiparams->{basketno} );
85 # 1st step = choose the file to import into acquisition
87 if ($op eq ""){
88 $template->param("basketno" => $cgiparams->{'basketno'});
89 #display batches
90 import_batches_list($template);
92 # 2nd step = display the content of the chosen file
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;
99 $template->param("batch_details" => 1,
100 "basketno" => $cgiparams->{'basketno'},
101 currencies => \@currencies,
102 bookseller => $bookseller,
103 "allmatch" => $allmatch,
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' );
110 # warn "==> ".Data::Dumper::Dumper($cell);
111 unless ($cell) {
112 $cell = PrepareItemrecordDisplay( '', '', '', '' );
113 $template->param( 'NoACQframework' => 1 );
115 my @itemloop;
116 push @itemloop, $cell;
118 $template->param( items => \@itemloop );
121 # 3rd step = import the records
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";
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)
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') || '';
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);
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;
179 $duplinbatch = $import_batch_id and next if $duplifound;
182 # add the biblio
183 my $bibitemnum;
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 );
196 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
197 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
198 } else {
199 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
202 # Add items from MarcItemFieldsToOrder
203 my @homebranches = $input->multi_param('homebranch_' . $biblio_count);
204 my $count = scalar @homebranches;
205 my @holdingbranches = $input->multi_param('holdingbranch_' . $biblio_count);
206 my @itypes = $input->multi_param('itype_' . $biblio_count);
207 my @nonpublic_notes = $input->multi_param('nonpublic_note_' . $biblio_count);
208 my @public_notes = $input->multi_param('public_note_' . $biblio_count);
209 my @locs = $input->multi_param('loc_' . $biblio_count);
210 my @ccodes = $input->multi_param('ccode_' . $biblio_count);
211 my @notforloans = $input->multi_param('notforloan_' . $biblio_count);
212 my @uris = $input->multi_param('uri_' . $biblio_count);
213 my @copynos = $input->multi_param('copyno_' . $biblio_count);
214 my @budget_codes = $input->multi_param('budget_code_' . $biblio_count);
215 my @itemprices = $input->multi_param('itemprice_' . $biblio_count);
216 my @replacementprices = $input->multi_param('replacementprice_' . $biblio_count);
217 my @itemcallnumbers = $input->multi_param('itemcallnumber_' . $biblio_count);
218 my $itemcreation = 0;
220 my @itemnumbers;
221 for (my $i = 0; $i < $count; $i++) {
222 $itemcreation = 1;
223 my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({
224 homebranch => $homebranches[$i],
225 holdingbranch => $holdingbranches[$i],
226 itemnotes_nonpublic => $nonpublic_notes[$i],
227 itemnotes => $public_notes[$i],
228 location => $locs[$i],
229 ccode => $ccodes[$i],
230 itype => $itypes[$i],
231 notforloan => $notforloans[$i],
232 uri => $uris[$i],
233 copynumber => $copynos[$i],
234 price => $itemprices[$i],
235 replacementprice => $replacementprices[$i],
236 itemcallnumber => $itemcallnumbers[$i],
237 }, $biblionumber);
238 push( @itemnumbers, $itemnumber );
240 if ($itemcreation == 1) {
241 # Group orderlines from MarcItemFieldsToOrder
242 my $budget_hash;
243 for (my $i = 0; $i < $count; $i++) {
244 $budget_hash->{$budget_codes[$i]}->{quantity} += 1;
245 $budget_hash->{$budget_codes[$i]}->{price} = $itemprices[$i];
246 $budget_hash->{$budget_codes[$i]}->{replacementprice} = $replacementprices[$i];
247 $budget_hash->{$budget_codes[$i]}->{itemnumbers} //= [];
248 push @{ $budget_hash->{$budget_codes[$i]}->{itemnumbers} }, $itemnumbers[$i];
251 # Create orderlines from MarcItemFieldsToOrder
252 while(my ($budget_id, $infos) = each %$budget_hash) {
253 if ($budget_id) {
254 my %orderinfo = (
255 biblionumber => $biblionumber,
256 basketno => $cgiparams->{'basketno'},
257 quantity => $infos->{quantity},
258 budget_id => $budget_id,
259 currency => $cgiparams->{'all_currency'},
262 my $price = $infos->{price};
263 if ($price){
264 # in France, the cents separator is the , but sometimes, ppl use a .
265 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
266 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
267 $price = Koha::Number::Price->new($price)->unformat;
268 $orderinfo{tax_rate} = $bookseller->tax_rate;
269 my $c = $c_discount ? $c_discount : $bookseller->discount / 100;
270 $orderinfo{discount} = $c;
271 if ( $c_discount ) {
272 $orderinfo{ecost} = $price;
273 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
274 } else {
275 $orderinfo{ecost} = $price * ( 1 - $c );
276 $orderinfo{rrp} = $price;
278 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
279 $orderinfo{unitprice} = $orderinfo{ecost};
280 $orderinfo{total} = $orderinfo{ecost} * $infos->{quantity};
281 } else {
282 $orderinfo{listprice} = 0;
284 $orderinfo{replacementprice} = $infos->{replacementprice} || 0;
286 # remove uncertainprice flag if we have found a price in the MARC record
287 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
289 %orderinfo = %{
290 C4::Acquisition::populate_order_with_prices(
292 order => \%orderinfo,
293 booksellerid => $booksellerid,
294 ordering => 1,
295 receiving => 1,
300 my $order = Koha::Acquisition::Order->new( \%orderinfo )->store;
301 $order->add_item( $_ ) for @{ $budget_hash->{$budget_id}->{itemnumbers} };
304 } else {
305 # 3rd add order
306 my $patron = Koha::Patrons->find( $loggedinuser );
307 # get quantity in the MARC record (1 if none)
308 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
309 my %orderinfo = (
310 biblionumber => $biblionumber,
311 basketno => $cgiparams->{'basketno'},
312 quantity => $c_quantity,
313 branchcode => $patron->branchcode,
314 budget_id => $c_budget_id,
315 uncertainprice => 1,
316 sort1 => $c_sort1,
317 sort2 => $c_sort2,
318 order_internalnote => $cgiparams->{'all_order_internalnote'},
319 order_vendornote => $cgiparams->{'all_order_vendornote'},
320 currency => $cgiparams->{'all_currency'},
321 replacementprice => shift( @orderreplacementprices ),
323 # get the price if there is one.
324 my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
325 if ($price){
326 # in France, the cents separator is the , but sometimes, ppl use a .
327 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
328 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
329 $price = Koha::Number::Price->new($price)->unformat;
330 $orderinfo{tax_rate} = $bookseller->tax_rate;
331 my $c = $c_discount ? $c_discount : $bookseller->discount / 100;
332 $orderinfo{discount} = $c;
333 if ( $c_discount ) {
334 $orderinfo{ecost} = $price;
335 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
336 } else {
337 $orderinfo{ecost} = $price * ( 1 - $c );
338 $orderinfo{rrp} = $price;
340 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
341 $orderinfo{unitprice} = $orderinfo{ecost};
342 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
343 } else {
344 $orderinfo{listprice} = 0;
347 # remove uncertainprice flag if we have found a price in the MARC record
348 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
350 %orderinfo = %{
351 C4::Acquisition::populate_order_with_prices(
353 order => \%orderinfo,
354 booksellerid => $booksellerid,
355 ordering => 1,
356 receiving => 1,
361 my $order = Koha::Acquisition::Order->new( \%orderinfo )->store;
363 # 4th, add items if applicable
364 # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
365 # this is not optimised, but it's working !
366 if ( $basket->effective_create_items eq 'ordering' && !$basket->is_standing ) {
367 my @tags = $input->multi_param('tag');
368 my @subfields = $input->multi_param('subfield');
369 my @field_values = $input->multi_param('field_value');
370 my @serials = $input->multi_param('serial');
371 my @ind_tag = $input->multi_param('ind_tag');
372 my @indicator = $input->multi_param('indicator');
373 my $item;
374 push @{ $item->{tags} }, $tags[0];
375 push @{ $item->{subfields} }, $subfields[0];
376 push @{ $item->{field_values} }, $field_values[0];
377 push @{ $item->{ind_tag} }, $ind_tag[0];
378 push @{ $item->{indicator} }, $indicator[0];
379 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@indicator, \@ind_tag );
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 );
385 } else {
386 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
389 $imported++;
391 # go to basket page
392 if ( $imported ) {
393 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
394 } else {
395 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");
397 exit;
400 my $budgets = GetBudgets();
401 my $budget_id = @$budgets[0]->{'budget_id'};
402 # build bookfund list
403 my $patron = Koha::Patrons->find( $loggedinuser )->unblessed;
404 my $budget = GetBudget($budget_id);
406 # build budget list
407 my $budget_loop = [];
408 my $budgets_hierarchy = GetBudgetHierarchy;
409 foreach my $r ( @{$budgets_hierarchy} ) {
410 next unless (CanUserUseBudget($patron, $r, $userflags));
411 if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
412 next;
414 push @{$budget_loop},
415 { b_id => $r->{budget_id},
416 b_txt => $r->{budget_name},
417 b_code => $r->{budget_code},
418 b_sort1_authcat => $r->{'sort1_authcat'},
419 b_sort2_authcat => $r->{'sort2_authcat'},
420 b_active => $r->{budget_period_active},
421 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
425 @{$budget_loop} =
426 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
428 $template->param( budget_loop => $budget_loop,);
430 output_html_with_http_headers $input, $cookie, $template->output;
433 sub import_batches_list {
434 my ($template) = @_;
435 my $batches = GetImportBatchRangeDesc();
437 my @list = ();
438 foreach my $batch (@$batches) {
439 if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
440 # check if there is at least 1 line still staged
441 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
442 if (scalar @$stagedList) {
443 push @list, {
444 import_batch_id => $batch->{'import_batch_id'},
445 num_records => $batch->{'num_records'},
446 num_items => $batch->{'num_items'},
447 staged_date => $batch->{'upload_timestamp'},
448 import_status => $batch->{'import_status'},
449 file_name => $batch->{'file_name'},
450 comments => $batch->{'comments'},
452 } else {
453 # if there are no more line to includes, set the status to imported
454 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
458 $template->param(batch_list => \@list);
459 my $num_batches = GetNumberOfNonZ3950ImportBatches();
460 $template->param(num_results => $num_batches);
463 sub import_biblios_list {
464 my ($template, $import_batch_id) = @_;
465 my $batch = GetImportBatch($import_batch_id,'staged');
466 return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
467 my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
468 my @list = ();
469 my $item_error = 0;
471 my $ccodes = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' } ) };
472 my $locations = { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
473 my $notforloans = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.notforloan' } ) };
474 # location list
475 my @locations;
476 foreach (sort keys %$locations) {
477 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
479 my @ccodes;
480 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
481 push @ccodes, { code => $_, description => $ccodes->{$_} };
483 my @notforloans;
484 foreach (sort {$notforloans->{$a} cmp $notforloans->{$b}} keys %$notforloans) {
485 push @notforloans, { code => $_, description => $notforloans->{$_} };
488 my $biblio_count = 0;
489 foreach my $biblio (@$biblios) {
490 my $item_id = 1;
491 $biblio_count++;
492 my $citation = $biblio->{'title'};
493 $citation .= " $biblio->{'author'}" if $biblio->{'author'};
494 $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
495 $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
496 $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
497 $citation .= $biblio->{'issn'} if $biblio->{'issn'};
498 $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
499 my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
500 my %cellrecord = (
501 import_record_id => $biblio->{'import_record_id'},
502 citation => $citation,
503 import => 1,
504 status => $biblio->{'status'},
505 record_sequence => $biblio->{'record_sequence'},
506 overlay_status => $biblio->{'overlay_status'},
507 match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
508 match_citation => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
509 match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
511 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
512 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
514 my $infos = get_infos_syspref('MarcFieldsToOrder', $marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2','replacementprice']);
515 my $price = $infos->{price};
516 my $replacementprice = $infos->{replacementprice};
517 my $quantity = $infos->{quantity};
518 my $budget_code = $infos->{budget_code};
519 my $discount = $infos->{discount};
520 my $sort1 = $infos->{sort1};
521 my $sort2 = $infos->{sort2};
522 my $budget_id;
523 if($budget_code) {
524 my $biblio_budget = GetBudgetByCode($budget_code);
525 if($biblio_budget) {
526 $budget_id = $biblio_budget->{budget_id};
530 # Items
531 my @itemlist = ();
532 my $all_items_quantity = 0;
533 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']);
534 if ($alliteminfos != -1) {
535 foreach my $iteminfos (@$alliteminfos) {
536 my $item_homebranch = $iteminfos->{homebranch};
537 my $item_holdingbranch = $iteminfos->{holdingbranch};
538 my $item_itype = $iteminfos->{itype};
539 my $item_nonpublic_note = $iteminfos->{nonpublic_note};
540 my $item_public_note = $iteminfos->{public_note};
541 my $item_loc = $iteminfos->{loc};
542 my $item_ccode = $iteminfos->{ccode};
543 my $item_notforloan = $iteminfos->{notforloan};
544 my $item_uri = $iteminfos->{uri};
545 my $item_copyno = $iteminfos->{copyno};
546 my $item_quantity = $iteminfos->{quantity} || 1;
547 my $item_budget_code = $iteminfos->{budget_code};
548 my $item_budget_id;
549 if ( $iteminfos->{budget_code} ) {
550 my $item_budget = GetBudgetByCode( $iteminfos->{budget_code} );
551 if ( $item_budget ) {
552 $item_budget_id = $item_budget->{budget_id};
555 my $item_price = $iteminfos->{price};
556 my $item_replacement_price = $iteminfos->{replacementprice};
557 my $item_callnumber = $iteminfos->{itemcallnumber};
559 for (my $i = 0; $i < $item_quantity; $i++) {
561 my %itemrecord = (
562 'item_id' => $item_id++,
563 'biblio_count' => $biblio_count,
564 'homebranch' => $item_homebranch,
565 'holdingbranch' => $item_holdingbranch,
566 'itype' => $item_itype,
567 'nonpublic_note' => $item_nonpublic_note,
568 'public_note' => $item_public_note,
569 'loc' => $item_loc,
570 'ccode' => $item_ccode,
571 'notforloan' => $item_notforloan,
572 'uri' => $item_uri,
573 'copyno' => $item_copyno,
574 'quantity' => $item_quantity,
575 'budget_id' => $item_budget_id || $budget_id,
576 'itemprice' => $item_price || $price,
577 'replacementprice' => $item_replacement_price || $replacementprice,
578 'itemcallnumber' => $item_callnumber,
580 $all_items_quantity++;
581 push @itemlist, \%itemrecord;
586 $cellrecord{'iteminfos'} = \@itemlist;
587 } else {
588 $cellrecord{'item_error'} = 1;
590 push @list, \%cellrecord;
592 if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
593 $cellrecord{price} = $price || '';
594 $cellrecord{replacementprice} = $replacementprice || '';
595 $cellrecord{quantity} = $quantity || '';
596 $cellrecord{budget_id} = $budget_id || '';
597 $cellrecord{discount} = $discount || '';
598 $cellrecord{sort1} = $sort1 || '';
599 $cellrecord{sort2} = $sort2 || '';
600 } else {
601 $cellrecord{quantity} = $all_items_quantity;
605 my $num_records = $batch->{'num_records'};
606 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
607 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
608 my $item_action = GetImportBatchItemAction($import_batch_id);
609 my @itypes = Koha::ItemTypes->search;
610 $template->param(biblio_list => \@list,
611 num_results => $num_records,
612 import_batch_id => $import_batch_id,
613 "overlay_action_${overlay_action}" => 1,
614 overlay_action => $overlay_action,
615 "nomatch_action_${nomatch_action}" => 1,
616 nomatch_action => $nomatch_action,
617 "item_action_${item_action}" => 1,
618 item_action => $item_action,
619 item_error => $item_error,
620 libraries => scalar Koha::Libraries->search(),
621 locationloop => \@locations,
622 itypeloop => \@itypes,
623 ccodeloop => \@ccodes,
624 notforloanloop => \@notforloans,
626 batch_info($template, $batch);
629 sub batch_info {
630 my ($template, $batch) = @_;
631 $template->param(batch_info => 1,
632 file_name => $batch->{'file_name'},
633 comments => $batch->{'comments'},
634 import_status => $batch->{'import_status'},
635 upload_timestamp => $batch->{'upload_timestamp'},
636 num_records => $batch->{'num_records'},
637 num_items => $batch->{'num_items'});
638 if ($batch->{'num_records'} > 0) {
639 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
640 $template->param(can_commit => 1);
642 if ($batch->{'import_status'} eq 'imported') {
643 $template->param(can_revert => 1);
646 if (defined $batch->{'matcher_id'}) {
647 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
648 if (defined $matcher) {
649 $template->param('current_matcher_id' => $batch->{'matcher_id'},
650 'current_matcher_code' => $matcher->code(),
651 'current_matcher_description' => $matcher->description());
654 add_matcher_list($batch->{'matcher_id'}, $template);
657 sub add_matcher_list {
658 my ($current_matcher_id, $template) = @_;
659 my @matchers = C4::Matcher::GetMatcherList();
660 if (defined $current_matcher_id) {
661 for (my $i = 0; $i <= $#matchers; $i++) {
662 if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
663 $matchers[$i]->{'selected'} = 1;
667 $template->param(available_matchers => \@matchers);
670 sub get_infos_syspref {
671 my ($syspref_name, $record, $field_list) = @_;
672 my $syspref = C4::Context->preference($syspref_name);
673 $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
674 my $yaml = eval {
675 YAML::Load($syspref);
677 if ( $@ ) {
678 warn "Unable to parse $syspref syspref : $@";
679 return ();
681 my $r;
682 for my $field_name ( @$field_list ) {
683 next unless exists $yaml->{$field_name};
684 my @fields = split /\|/, $yaml->{$field_name};
685 for my $field ( @fields ) {
686 my ( $f, $sf ) = split /\$/, $field;
687 next unless $f and $sf;
688 if ( my $v = $record->subfield( $f, $sf ) ) {
689 $r->{$field_name} = $v;
691 last if $yaml->{$field};
694 return $r;
697 sub equal_number_of_fields {
698 my ($tags_list, $record) = @_;
699 my $tag_fields_count;
700 for my $tag (@$tags_list) {
701 my @fields = $record->field($tag);
702 $tag_fields_count->{$tag} = scalar @fields;
705 my $tags_count;
706 foreach my $key ( keys %$tag_fields_count ) {
707 if ( $tag_fields_count->{$key} > 0 ) { # Having 0 of a field is ok
708 $tags_count //= $tag_fields_count->{$key}; # Start with the count from the first occurrence
709 return -1 if $tag_fields_count->{$key} != $tags_count; # All counts of various fields should be equal if they exist
713 return $tags_count;
716 sub get_infos_syspref_on_item {
717 my ($syspref_name, $record, $field_list) = @_;
718 my $syspref = C4::Context->preference($syspref_name);
719 $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
720 my $yaml = eval {
721 YAML::Load($syspref);
723 if ( $@ ) {
724 warn "Unable to parse $syspref syspref : $@";
725 return ();
727 my @result;
728 my @tags_list;
730 # Check tags in syspref definition
731 for my $field_name ( @$field_list ) {
732 next unless exists $yaml->{$field_name};
733 my @fields = split /\|/, $yaml->{$field_name};
734 for my $field ( @fields ) {
735 my ( $f, $sf ) = split /\$/, $field;
736 next unless $f and $sf;
737 push @tags_list, $f;
740 @tags_list = List::MoreUtils::uniq(@tags_list);
742 my $tags_count = equal_number_of_fields(\@tags_list, $record);
743 # Return if the number of these fields in the record is not the same.
744 return -1 if $tags_count == -1;
746 # Gather the fields
747 my $fields_hash;
748 foreach my $tag (@tags_list) {
749 my @tmp_fields;
750 foreach my $field ($record->field($tag)) {
751 push @tmp_fields, $field;
753 $fields_hash->{$tag} = \@tmp_fields;
756 for (my $i = 0; $i < $tags_count; $i++) {
757 my $r;
758 for my $field_name ( @$field_list ) {
759 next unless exists $yaml->{$field_name};
760 my @fields = split /\|/, $yaml->{$field_name};
761 for my $field ( @fields ) {
762 my ( $f, $sf ) = split /\$/, $field;
763 next unless $f and $sf;
764 my $v = $fields_hash->{$f}[$i] ? $fields_hash->{$f}[$i]->subfield( $sf ) : undef;
765 $r->{$field_name} = $v if (defined $v);
766 last if $yaml->{$field};
769 push @result, $r;
771 return \@result;