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>.
28 use Scalar::Util qw( looks_like_number );
31 use C4::Auth qw( get_template_and_user );
32 use C4::Output qw( output_html_with_http_headers );
33 use C4::ImportBatch qw( SetImportBatchStatus GetImportBatch GetImportBatchRangeDesc GetNumberOfNonZ3950ImportBatches GetImportBatchOverlayAction GetImportBatchNoMatchAction GetImportBatchItemAction );
35 use C4::Search qw( FindDuplicate );
43 use C4::Items qw( PrepareItemrecordDisplay AddItemFromMarc );
44 use C4::Budgets qw( GetBudget GetBudgets GetBudgetHierarchy CanUserUseBudget GetBudgetByCode );
45 use C4::Suggestions; # GetSuggestion
48 use Koha::Number::Price;
50 use Koha::Acquisition::Baskets;
51 use Koha::Acquisition::Currencies;
52 use Koha::Acquisition::Orders;
53 use Koha::Acquisition::Booksellers;
54 use Koha::ImportBatches;
55 use Koha::Import::Records;
59 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
60 template_name => "acqui/addorderiso2709.tt",
63 flagsrequired => { acquisition => 'order_manage' },
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 );
72 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
73 booksellerid => $booksellerid,
74 booksellername => $bookseller->name,
77 if ($cgiparams->{'import_batch_id'} && $op eq ""){
78 $op = "batch_details";
82 if (! $cgiparams->{'basketno'}){
83 die "Basketnumber required to order from iso2709 file import";
85 my $basket = Koha::Acquisition::Baskets->find( $cgiparams->{basketno} );
88 # 1st step = choose the file to import into acquisition
91 $template->param("basketno" => $cgiparams->{'basketno'});
93 import_batches_list($template);
95 # 2nd step = display the content of the chosen file
97 } elsif ($op eq "batch_details"){
98 #display lines inside the selected batch
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,
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' );
112 # warn "==> ".Data::Dumper::Dumper($cell);
114 $cell = PrepareItemrecordDisplay( '', '', undef, '' );
115 $template->param( 'NoACQframework' => 1 );
118 push @itemloop, $cell;
120 $template->param( items => \@itemloop );
123 # 3rd step = import the records
125 } elsif ( $op eq 'cud-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";
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)
137 # retrieve the file you want to import
138 my $import_batch_id = $cgiparams->{'import_batch_id'};
139 my $import_batch = Koha::ImportBatches->find( $import_batch_id );
140 my $overlay_action = $import_batch->overlay_action;
141 my $import_records = Koha::Import::Records->search({
142 import_batch_id => $import_batch_id,
146 my @import_record_id_selected = $input->multi_param("import_record_id");
147 my $matcher_id = $input->param('matcher_id');
148 my $active_currency = Koha::Acquisition::Currencies->get_active;
149 my $biblio_count = 0;
150 while( my $import_record = $import_records->next ){
153 # Check if this import_record_id was selected
154 next if not grep { $_ eq $import_record->import_record_id } @import_record_id_selected;
155 my $marcrecord = $import_record->get_marc_record || die "couldn't translate marc information";
156 my $matches = $import_record->get_import_record_matches({ chosen => 1 });
157 my $match = $matches->count ? $matches->next : undef;
158 my $biblionumber = $match ? $match->candidate_match_id : 0;
160 $input->param( 'quantity_' . $import_record->import_record_id )
161 || GetMarcQuantity( $marcrecord, C4::Context->preference('marcflavour') )
164 $input->param( 'budget_id_' . $import_record->import_record_id )
165 || $input->param('all_budget_id')
167 my $c_discount = $input->param( 'discount_' . $import_record->import_record_id );
168 my $c_sort1 = $input->param( 'sort1_' . $import_record->import_record_id ) || $input->param('all_sort1') || '';
169 my $c_sort2 = $input->param( 'sort2_' . $import_record->import_record_id ) || $input->param('all_sort2') || '';
170 my $c_replacement_price = $input->param( 'replacementprice_' . $import_record->import_record_id );
171 my $c_price = $input->param( 'price_' . $import_record->import_record_id );
172 # Insert the biblio, or find it through matcher
173 if ( $biblionumber ) { # If matched during staging we can continue
174 $import_record->status('imported')->store;
175 if( $overlay_action eq 'replace' ){
176 my $biblio = Koha::Biblios->find( $biblionumber );
177 $import_record->replace({ biblio => $biblio });
179 } else { # Otherwise we check for duplicates, and skip if they exist
181 if ( $matcher_id eq '_TITLE_AUTHOR_' ) {
182 $duplifound = 1 if FindDuplicate($marcrecord);
185 my $matcher = C4::Matcher->fetch($matcher_id);
186 my @matches = $matcher->get_matches( $marcrecord, my $max_matches = 1 );
187 $duplifound = 1 if @matches;
190 $duplinbatch = $import_batch_id and next if $duplifound;
193 # remove hyphens (-) from ISBN
194 # FIXME: This should probably be optional
195 my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn' );
196 if ( $marcrecord->field($isbnfield) ) {
197 foreach my $field ( $marcrecord->field($isbnfield) ) {
198 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
199 my $newisbn = $field->subfield($isbnsubfield);
201 $field->update( $isbnsubfield => $newisbn );
207 ( $biblionumber, undef ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
208 $import_record->status('imported')->store;
211 $import_record->import_biblio->matched_biblionumber($biblionumber)->store;
213 # Add items from MarcItemFieldsToOrder
214 my @homebranches = $input->multi_param( 'homebranch_' . $import_record->import_record_id );
215 my $count = scalar @homebranches;
216 my @holdingbranches = $input->multi_param( 'holdingbranch_' . $import_record->import_record_id );
217 my @itypes = $input->multi_param( 'itype_' . $import_record->import_record_id );
218 my @nonpublic_notes = $input->multi_param( 'nonpublic_note_' . $import_record->import_record_id );
219 my @public_notes = $input->multi_param( 'public_note_' . $import_record->import_record_id );
220 my @locs = $input->multi_param( 'loc_' . $import_record->import_record_id );
221 my @ccodes = $input->multi_param( 'ccode_' . $import_record->import_record_id );
222 my @notforloans = $input->multi_param( 'notforloan_' . $import_record->import_record_id );
223 my @uris = $input->multi_param( 'uri_' . $import_record->import_record_id );
224 my @copynos = $input->multi_param( 'copyno_' . $import_record->import_record_id );
226 $input->multi_param( 'budget_code_' . $import_record->import_record_id ); # bad field name used in template!
227 my @itemprices = $input->multi_param( 'itemprice_' . $import_record->import_record_id );
228 my @replacementprices = $input->multi_param( 'itemreplacementprice_' . $import_record->import_record_id );
229 my @itemcallnumbers = $input->multi_param( 'itemcallnumber_' . $import_record->import_record_id );
230 my @coded_location_qualifiers =
231 $input->multi_param( 'coded_location_qualifier_' . $import_record->import_record_id );
232 my @barcodes = $input->multi_param( 'barcode_' . $import_record->import_record_id );
233 my @enumchrons = $input->multi_param( 'enumchron_' . $import_record->import_record_id );
234 my $itemcreation = 0;
237 for (my $i = 0; $i < $count; $i++) {
239 my $item = Koha::Item->new(
241 biblionumber => $biblionumber,
242 homebranch => $homebranches[$i],
243 holdingbranch => $holdingbranches[$i],
244 itemnotes_nonpublic => $nonpublic_notes[$i],
245 itemnotes => $public_notes[$i],
246 location => $locs[$i],
247 ccode => $ccodes[$i],
248 itype => $itypes[$i],
249 notforloan => $notforloans[$i],
251 copynumber => $copynos[$i],
252 price => $itemprices[$i],
253 replacementprice => $replacementprices[$i],
254 itemcallnumber => $itemcallnumbers[$i],
255 coded_location_qualifier => $coded_location_qualifiers[$i],
256 barcode => $barcodes[$i],
257 enumchron => $enumchrons[$i],
260 push( @itemnumbers, $item->itemnumber );
262 if ($itemcreation == 1) {
263 # Group orderlines from MarcItemFieldsToOrder
265 for (my $i = 0; $i < $count; $i++) {
266 $budget_ids[$i] = $budget_id if !$budget_ids[$i]; # Use default budget if no budget selected in the UI
267 $budget_hash->{ $budget_ids[$i] }->{quantity} += 1;
268 $budget_hash->{ $budget_ids[$i] }->{price} = $itemprices[$i];
269 $budget_hash->{ $budget_ids[$i] }->{replacementprice} =
270 $replacementprices[$i];
271 $budget_hash->{ $budget_ids[$i] }->{itemnumbers} //= [];
272 push @{ $budget_hash->{ $budget_ids[$i] }->{itemnumbers} },
276 # Create orderlines from MarcItemFieldsToOrder
277 while(my ($budget_id, $infos) = each %$budget_hash) {
280 biblionumber => $biblionumber,
281 basketno => $cgiparams->{'basketno'},
282 quantity => $infos->{quantity},
283 budget_id => $budget_id,
284 currency => $cgiparams->{'all_currency'},
287 my $price = $infos->{price};
289 # in France, the cents separator is the , but sometimes, ppl use a .
290 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
291 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
292 $price = Koha::Number::Price->new($price)->unformat;
293 $orderinfo{tax_rate_on_ordering} = $bookseller->tax_rate;
294 $orderinfo{tax_rate_on_receiving} = $bookseller->tax_rate;
295 my $order_discount = $c_discount ? $c_discount : $bookseller->discount;
296 $orderinfo{discount} = $order_discount;
297 $orderinfo{rrp} = $price;
298 $orderinfo{ecost} = $order_discount ? $price * ( 1 - $order_discount / 100 ) : $price;
299 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
300 $orderinfo{unitprice} = $orderinfo{ecost};
301 $orderinfo{sort1} = $c_sort1;
302 $orderinfo{sort2} = $c_sort2;
304 $orderinfo{listprice} = 0;
306 $orderinfo{replacementprice} = $infos->{replacementprice} || 0;
308 # remove uncertainprice flag if we have found a price in the MARC record
309 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
311 my $order = Koha::Acquisition::Order->new( \%orderinfo );
312 $order->populate_with_prices_for_ordering();
313 $order->populate_with_prices_for_receiving();
315 $order->add_item( $_ ) for @{ $budget_hash->{$budget_id}->{itemnumbers} };
320 my $patron = Koha::Patrons->find( $loggedinuser );
321 # get quantity in the MARC record (1 if none)
322 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
324 biblionumber => $biblionumber,
325 basketno => $cgiparams->{'basketno'},
326 quantity => $c_quantity,
327 branchcode => $patron->branchcode,
328 budget_id => $c_budget_id,
332 order_internalnote => $cgiparams->{'all_order_internalnote'},
333 order_vendornote => $cgiparams->{'all_order_vendornote'},
334 currency => $cgiparams->{'all_currency'},
335 replacementprice => $c_replacement_price,
337 # get the price if there is one.
339 # in France, the cents separator is the , but sometimes, ppl use a .
340 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
341 $c_price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
342 $c_price = Koha::Number::Price->new($c_price)->unformat;
343 $orderinfo{tax_rate_on_ordering} = $bookseller->tax_rate;
344 $orderinfo{tax_rate_on_receiving} = $bookseller->tax_rate;
345 my $order_discount = $c_discount ? $c_discount : $bookseller->discount;
346 $orderinfo{discount} = $order_discount;
347 $orderinfo{rrp} = $c_price;
348 $orderinfo{ecost} = $order_discount ? $c_price * ( 1 - $order_discount / 100 ) : $c_price;
349 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
350 $orderinfo{unitprice} = $orderinfo{ecost};
352 $orderinfo{listprice} = 0;
355 # remove uncertainprice flag if we have found a price in the MARC record
356 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
358 my $order = Koha::Acquisition::Order->new( \%orderinfo );
359 $order->populate_with_prices_for_ordering();
360 $order->populate_with_prices_for_receiving();
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 $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values );
372 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
373 for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
374 my ( $biblionumber, undef, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
375 $order->add_item( $itemnumber );
382 # If all bibliographic records from the batch have been imported we modifying the status of the batch accordingly
383 SetImportBatchStatus( $import_batch_id, 'imported' )
384 if Koha::Import::Records->search({import_batch_id => $import_batch_id, status => 'imported' })->count
385 == Koha::Import::Records->search({import_batch_id => $import_batch_id})->count;
389 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&duplinbatch=$duplinbatch");
391 print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&basketno=".$cgiparams->{'basketno'}."&booksellerid=$booksellerid&allmatch=1");
396 my $budgets = GetBudgets();
397 my $budget_id = @$budgets[0]->{'budget_id'};
398 # build bookfund list
399 my $patron = Koha::Patrons->find( $loggedinuser )->unblessed;
400 my $budget = GetBudget($budget_id);
403 my $budget_loop = [];
404 my $budgets_hierarchy = GetBudgetHierarchy;
405 foreach my $r ( @{$budgets_hierarchy} ) {
406 next unless (CanUserUseBudget($patron, $r, $userflags));
407 push @{$budget_loop},
408 { b_id => $r->{budget_id},
409 b_txt => $r->{budget_name},
410 b_code => $r->{budget_code},
411 b_sort1_authcat => $r->{'sort1_authcat'},
412 b_sort2_authcat => $r->{'sort2_authcat'},
413 b_active => $r->{budget_period_active},
414 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
419 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
421 $template->param( budget_loop => $budget_loop,);
423 output_html_with_http_headers $input, $cookie, $template->output;
426 sub import_batches_list {
428 my $batches = GetImportBatchRangeDesc();
431 foreach my $batch (@$batches) {
432 if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
433 # check if there is at least 1 line still staged
434 my $import_records_count = Koha::Import::Records->search({
435 import_batch_id => $batch->{'import_batch_id'},
436 status => $batch->{import_status}
438 if ( $import_records_count ) {
440 import_batch_id => $batch->{'import_batch_id'},
441 num_records => $batch->{'num_records'},
442 num_items => $batch->{'num_items'},
443 staged_date => $batch->{'upload_timestamp'},
444 import_status => $batch->{'import_status'},
445 file_name => $batch->{'file_name'},
446 comments => $batch->{'comments'},
449 # if there are no more line to includes, set the status to imported
450 # FIXME This should be removed in the future.
451 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
455 $template->param(batch_list => \@list);
456 my $num_batches = GetNumberOfNonZ3950ImportBatches();
457 $template->param(num_results => $num_batches);
460 sub import_biblios_list {
461 my ($template, $import_batch_id) = @_;
462 my $batch = GetImportBatch($import_batch_id,'staged');
463 return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
464 my $import_records = Koha::Import::Records->search({
465 import_batch_id => $import_batch_id,
466 status => $batch->{import_status}
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' } ) };
476 foreach (sort keys %$locations) {
477 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
480 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
481 push @ccodes, { code => $_, description => $ccodes->{$_} };
484 foreach (sort {$notforloans->{$a} cmp $notforloans->{$b}} keys %$notforloans) {
485 push @notforloans, { code => $_, description => $notforloans->{$_} };
488 my $biblio_count = 0;
489 while ( my $import_record = $import_records->next ) {
492 my $matches = $import_record->get_import_record_matches({ chosen => 1 });
493 my $match = $matches->count ? $matches->next : undef;
494 my $match_biblio = $match ? Koha::Biblios->find({ biblionumber => $match->candidate_match_id }) : undef;
496 import_record_id => $import_record->import_record_id,
497 import_biblio => $import_record->import_biblio,
499 status => $import_record->status,
500 record_sequence => $import_record->record_sequence,
501 overlay_status => $import_record->overlay_status,
502 match_biblionumber => $match ? $match->candidate_match_id : 0,
503 match_citation => $match_biblio ? ($match_biblio->title || '') . ' ' .( $match_biblio->author || ''): '',
504 match_score => $match ? $match->score : 0,
506 my $marcrecord = $import_record->get_marc_record || die "couldn't translate marc information";
508 my $infos = get_infos_syspref('MarcFieldsToOrder', $marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2','replacementprice']);
509 my $price = looks_like_number($infos->{price}) ? $infos->{price} : GetMarcPrice( $marcrecord, C4::Context->preference('marcflavour') );
510 my $replacementprice = $infos->{replacementprice};
511 my $quantity = $infos->{quantity};
512 my $budget_code = $infos->{budget_code};
513 my $discount = $infos->{discount};
514 my $sort1 = $infos->{sort1};
515 my $sort2 = $infos->{sort2};
519 my $biblio_budget = GetBudgetByCode($budget_code);
520 if ($biblio_budget) {
521 $budget_id = $biblio_budget->{budget_id};
527 my $all_items_quantity = 0;
528 my $alliteminfos = get_marc_item_fields_to_order($marcrecord);
529 if ($alliteminfos != -1) {
530 foreach my $iteminfos (@$alliteminfos) {
531 # Quantity is required, default to one if not supplied
532 my $quantity = delete $iteminfos->{quantity} || 1;
534 # Handle incorrectly named original parameters for MarcItemFieldsToOrder
535 $iteminfos->{location} = delete $iteminfos->{loc} if $iteminfos->{loc};
536 $iteminfos->{copynumber} = delete $iteminfos->{copyno} if $iteminfos->{copyno};
537 # Price is handled as "itemprice" in the UI form to distinguish from MarcFieldsToOrder
538 $iteminfos->{itemprice} = delete $iteminfos->{price} if $iteminfos->{price};
540 # Convert budge code to a budget id
541 my $item_budget_code = delete $iteminfos->{budget_code};
542 if ( $item_budget_code ) {
543 my $item_budget = GetBudgetByCode( $item_budget_code );
544 $iteminfos->{budget_id} = $item_budget->{budget_id} || $budget_id;
547 $iteminfos->{price} ||= $price; # Fallback to order price if no item price was defined
549 # Clone the item data for the needed quantity
550 # Add the incremented item id for each item in that quantity
551 for (my $i = 0; $i < $quantity; $i++) {
552 my $itemrecord = { %$iteminfos };
553 $itemrecord->{item_id} = $item_id++;
554 $all_items_quantity++;
555 push @itemlist, $itemrecord;
559 $cellrecord{'iteminfos'} = \@itemlist;
561 $cellrecord{'item_error'} = 1;
563 push @list, \%cellrecord;
565 # If MarcItemFieldsToOrder is not set, we use MarcFieldsToOrder to populate the order form.
566 if ($alliteminfos == -1 || scalar(@$alliteminfos) == 0) {
567 $cellrecord{price} = $price || '';
568 $cellrecord{replacementprice} = $replacementprice || '';
569 $cellrecord{quantity} = $quantity || '';
570 $cellrecord{budget_id} = $budget_id || '';
572 # When using MarcItemFields to order we want the order to have the same quantity as total items
573 $cellrecord{quantity} = $all_items_quantity;
575 # The fields discount, sort1, and sort2 only exist at the order level, so always use MarcItemFieldsToOrder
576 $cellrecord{discount} = $discount || '';
577 $cellrecord{sort1} = $sort1 || '';
578 $cellrecord{sort2} = $sort2 || '';
581 my $num_records = $batch->{'num_records'};
582 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
583 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
584 my $item_action = GetImportBatchItemAction($import_batch_id);
585 $template->param(import_biblio_list => \@list,
586 num_results => $num_records,
587 import_batch_id => $import_batch_id,
588 "overlay_action_${overlay_action}" => 1,
589 overlay_action => $overlay_action,
590 "nomatch_action_${nomatch_action}" => 1,
591 nomatch_action => $nomatch_action,
592 "item_action_${item_action}" => 1,
593 item_action => $item_action,
594 item_error => $item_error,
595 libraries => Koha::Libraries->search,
596 locationloop => \@locations,
597 itemtypes => Koha::ItemTypes->search,
598 ccodeloop => \@ccodes,
599 notforloanloop => \@notforloans,
601 batch_info($template, $batch);
605 my ($template, $batch) = @_;
606 $template->param(batch_info => 1,
607 file_name => $batch->{'file_name'},
608 comments => $batch->{'comments'},
609 import_status => $batch->{'import_status'},
610 upload_timestamp => $batch->{'upload_timestamp'},
611 num_records => $batch->{'num_records'},
612 num_items => $batch->{'num_items'});
613 if ($batch->{'num_records'} > 0) {
614 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
615 $template->param(can_commit => 1);
617 if ($batch->{'import_status'} eq 'imported') {
618 $template->param(can_revert => 1);
621 if (defined $batch->{'matcher_id'}) {
622 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
623 if (defined $matcher) {
624 $template->param('current_matcher_id' => $batch->{'matcher_id'},
625 'current_matcher_code' => $matcher->code(),
626 'current_matcher_description' => $matcher->description());
629 add_matcher_list($batch->{'matcher_id'}, $template);
632 sub add_matcher_list {
633 my ($current_matcher_id, $template) = @_;
634 my @matchers = C4::Matcher::GetMatcherList();
635 if (defined $current_matcher_id) {
636 for (my $i = 0; $i <= $#matchers; $i++) {
637 if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
638 $matchers[$i]->{'selected'} = 1;
642 $template->param(available_matchers => \@matchers);
645 sub get_infos_syspref {
646 my ($syspref_name, $record, $field_list) = @_;
647 my $yaml = C4::Context->yaml_preference($syspref_name);
650 for my $field_name ( @$field_list ) {
651 next unless exists $yaml->{$field_name};
652 my @fields = split /\|/, $yaml->{$field_name};
653 for my $field ( @fields ) {
654 my ( $f, $sf ) = split /\$/, $field;
655 next unless $f and $sf;
656 if ( my $v = $record->subfield( $f, $sf ) ) {
657 $r->{$field_name} = $v;
659 last if $yaml->{$field};
665 sub equal_number_of_fields {
666 my ($tags_list, $record) = @_;
667 my $tag_fields_count;
668 for my $tag (@$tags_list) {
669 my @fields = $record->field($tag);
670 $tag_fields_count->{$tag} = scalar @fields;
674 foreach my $key ( keys %$tag_fields_count ) {
675 if ( $tag_fields_count->{$key} > 0 ) { # Having 0 of a field is ok
676 $tags_count //= $tag_fields_count->{$key}; # Start with the count from the first occurrence
677 return -1 if $tag_fields_count->{$key} != $tags_count; # All counts of various fields should be equal if they exist
684 sub get_marc_item_fields_to_order {
687 my $syspref = C4::Context->preference('MarcItemFieldsToOrder');
688 $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
690 YAML::XS::Load(Encode::encode_utf8($syspref));
693 warn "Unable to parse $syspref syspref : $@";
700 # Check tags in syspref definition
701 for my $field_name ( keys %$yaml ) {
702 my @fields = split /\|/, $yaml->{$field_name};
703 for my $field ( @fields ) {
704 my ( $f, $sf ) = split /\$/, $field;
705 next unless $f and $sf;
709 @tags_list = List::MoreUtils::uniq(@tags_list);
711 my $tags_count = equal_number_of_fields(\@tags_list, $record);
712 # Return if the number of these fields in the record is not the same.
713 return -1 if $tags_count == -1;
717 foreach my $tag (@tags_list) {
719 foreach my $field ($record->field($tag)) {
720 push @tmp_fields, $field;
722 $fields_hash->{$tag} = \@tmp_fields;
725 for (my $i = 0; $i < $tags_count; $i++) {
727 for my $field_name ( keys %$yaml ) {
728 my @fields = split /\|/, $yaml->{$field_name};
729 for my $field ( @fields ) {
730 my ( $f, $sf ) = split /\$/, $field;
731 next unless $f and $sf;
732 my $v = $fields_hash->{$f}[$i] ? $fields_hash->{$f}[$i]->subfield( $sf ) : undef;
733 $r->{$field_name} = $v if (defined $v);
734 last if $yaml->{$field};