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 he wants 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>.
40 use C4::Suggestions; # GetSuggestion
43 use Koha::Number::Price;
44 use Koha::Acquisition::Currencies;
45 use Koha::Acquisition::Order;
46 use Koha::Acquisition::Bookseller;
49 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
50 template_name => "acqui/addorderiso2709.tt",
54 flagsrequired => { acquisition => 'order_manage' },
58 my $cgiparams = $input->Vars;
59 my $op = $cgiparams->{'op'} || '';
60 my $booksellerid = $input->param('booksellerid');
61 my $allmatch = $input->param('allmatch');
62 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
64 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
65 booksellerid => $booksellerid,
66 booksellername => $bookseller->{name},
69 if ($cgiparams->{'import_batch_id'} && $op eq ""){
70 $op = "batch_details";
74 if (! $cgiparams->{'basketno'}){
75 die "Basketnumber required to order from iso2709 file import";
79 # 1st step = choose the file to import into acquisition
82 $template->param("basketno" => $cgiparams->{'basketno'});
84 import_batches_list($template);
86 # 2nd step = display the content of the chosen file
88 } elsif ($op eq "batch_details"){
89 #display lines inside the selected batch
90 # get currencies (for change rates calcs if needed)
91 my @currencies = Koha::Acquisition::Currencies->search;
93 $template->param("batch_details" => 1,
94 "basketno" => $cgiparams->{'basketno'},
95 currencies => \@currencies,
96 bookseller => $bookseller,
97 "allmatch" => $allmatch,
99 import_biblios_list($template, $cgiparams->{'import_batch_id'});
100 my $basket = GetBasket($cgiparams->{basketno});
101 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$basket->{is_standing} ) {
102 # prepare empty item form
103 my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
105 # warn "==> ".Data::Dumper::Dumper($cell);
107 $cell = PrepareItemrecordDisplay( '', '', '', '' );
108 $template->param( 'NoACQframework' => 1 );
111 push @itemloop, $cell;
113 $template->param( items => \@itemloop );
116 # 3rd step = import the records
118 } elsif ( $op eq 'import_records' ) {
119 #import selected lines
120 $template->param('basketno' => $cgiparams->{'basketno'});
121 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
122 my $budgets = GetBudgets();
123 if (scalar @$budgets == 0){
124 die "No budgets defined, can't continue";
126 my $budget_id = @$budgets[0]->{'budget_id'};
127 #get all records from a batch, and check their import status to see if they are checked.
128 #(default values: quantity 1, uncertainprice yes, first budget)
130 # retrieve the file you want to import
131 my $import_batch_id = $cgiparams->{'import_batch_id'};
132 my $biblios = GetImportRecordsRange($import_batch_id);
135 my @import_record_id_selected = $input->multi_param("import_record_id");
136 my @quantities = $input->multi_param('quantity');
137 my @prices = $input->multi_param('price');
138 my @budgets_id = $input->multi_param('budget_id');
139 my @discount = $input->multi_param('discount');
140 my @sort1 = $input->multi_param('sort1');
141 my @sort2 = $input->multi_param('sort2');
142 my $matcher_id = $input->multi_param('matcher_id');
143 my $active_currency = Koha::Acquisition::Currencies->get_active;
144 for my $biblio (@$biblios){
145 # Check if this import_record_id was selected
146 next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
147 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
148 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
149 my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
150 my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
151 my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
152 my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
153 my $c_discount = shift ( @discount);
154 $c_discount = $c_discount / 100 if $c_discount > 1;
155 my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
156 my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
158 # 1st insert the biblio, or find it through matcher
159 unless ( $biblionumber ) {
161 my $matcher = C4::Matcher->fetch($matcher_id);
162 my @matches = $matcher->get_matches( $marcrecord, my $max_matches = 1 );
164 $duplinbatch = $import_batch_id;
172 my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
173 if ( $marcrecord->field($isbnfield) ) {
174 foreach my $field ( $marcrecord->field($isbnfield) ) {
175 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
176 my $newisbn = $field->subfield($isbnsubfield);
178 $field->update( $isbnsubfield => $newisbn );
182 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
183 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
184 # 2nd add authorities if applicable
185 if (C4::Context->preference("BiblioAddsAuthorities")){
186 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
189 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
192 my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
193 # get quantity in the MARC record (1 if none)
194 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
196 biblionumber => $biblionumber,
197 basketno => $cgiparams->{'basketno'},
198 quantity => $c_quantity,
199 branchcode => $patron->{branchcode},
200 budget_id => $c_budget_id,
204 order_internalnote => $cgiparams->{'all_order_internalnote'},
205 order_vendornote => $cgiparams->{'all_order_vendornote'},
206 currency => $cgiparams->{'all_currency'},
208 # get the price if there is one.
209 my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
211 # in France, the cents separator is the , but sometimes, ppl use a .
212 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
213 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
214 $price = Koha::Number::Price->new($price)->unformat;
215 $orderinfo{tax_rate} = $bookseller->{tax_rate};
216 my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
217 if ( $bookseller->{listincgst} ) {
219 $orderinfo{ecost} = $price;
220 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
222 $orderinfo{ecost} = $price * ( 1 - $c );
223 $orderinfo{rrp} = $price;
227 $orderinfo{ecost} = $price / ( 1 + $orderinfo{tax_rate} );
228 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
230 $orderinfo{rrp} = $price / ( 1 + $orderinfo{tax_rate} );
231 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
234 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
235 $orderinfo{unitprice} = $orderinfo{ecost};
236 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
238 $orderinfo{listprice} = 0;
241 # remove uncertainprice flag if we have found a price in the MARC record
242 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
245 C4::Acquisition::populate_order_with_prices(
247 order => \%orderinfo,
248 booksellerid => $booksellerid,
255 my $order = Koha::Acquisition::Order->new( \%orderinfo )->insert;
257 # 4th, add items if applicable
258 # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
259 # this is not optimised, but it's working !
260 my $basket = GetBasket($cgiparams->{basketno});
261 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$basket->{is_standing} ) {
262 my @tags = $input->multi_param('tag');
263 my @subfields = $input->multi_param('subfield');
264 my @field_values = $input->multi_param('field_value');
265 my @serials = $input->multi_param('serial');
266 my @ind_tag = $input->multi_param('ind_tag');
267 my @indicator = $input->multi_param('indicator');
269 push @{ $item->{tags} }, $tags[0];
270 push @{ $item->{subfields} }, $subfields[0];
271 push @{ $item->{field_values} }, $field_values[0];
272 push @{ $item->{ind_tag} }, $ind_tag[0];
273 push @{ $item->{indicator} }, $indicator[0];
274 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@indicator, \@ind_tag );
275 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
276 for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
277 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
278 $order->add_item( $itemnumber );
281 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
287 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&duplinbatch=$duplinbatch");
289 print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&basketno=".$cgiparams->{'basketno'}."&booksellerid=$booksellerid&allmatch=1");
294 my $budgets = GetBudgets();
295 my $budget_id = @$budgets[0]->{'budget_id'};
296 # build bookfund list
297 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
298 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
299 my $budget = GetBudget($budget_id);
302 my $budget_loop = [];
303 my $budgets_hierarchy = GetBudgetHierarchy;
304 foreach my $r ( @{$budgets_hierarchy} ) {
305 next unless (CanUserUseBudget($borrower, $r, $userflags));
306 if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
309 push @{$budget_loop},
310 { b_id => $r->{budget_id},
311 b_txt => $r->{budget_name},
312 b_sort1_authcat => $r->{'sort1_authcat'},
313 b_sort2_authcat => $r->{'sort2_authcat'},
314 b_active => $r->{budget_period_active},
315 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
320 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
322 $template->param( budget_loop => $budget_loop,);
324 output_html_with_http_headers $input, $cookie, $template->output;
327 sub import_batches_list {
329 my $batches = GetImportBatchRangeDesc();
332 foreach my $batch (@$batches) {
333 if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
334 # check if there is at least 1 line still staged
335 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
336 if (scalar @$stagedList) {
338 import_batch_id => $batch->{'import_batch_id'},
339 num_records => $batch->{'num_records'},
340 num_items => $batch->{'num_items'},
341 staged_date => $batch->{'upload_timestamp'},
342 import_status => $batch->{'import_status'},
343 file_name => $batch->{'file_name'},
344 comments => $batch->{'comments'},
347 # if there are no more line to includes, set the status to imported
348 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
352 $template->param(batch_list => \@list);
353 my $num_batches = GetNumberOfNonZ3950ImportBatches();
354 $template->param(num_results => $num_batches);
357 sub import_biblios_list {
358 my ($template, $import_batch_id) = @_;
359 my $batch = GetImportBatch($import_batch_id,'staged');
360 return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
361 my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
364 foreach my $biblio (@$biblios) {
365 my $citation = $biblio->{'title'};
366 $citation .= " $biblio->{'author'}" if $biblio->{'author'};
367 $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
368 $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
369 $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
370 $citation .= $biblio->{'issn'} if $biblio->{'issn'};
371 $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
372 my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
374 import_record_id => $biblio->{'import_record_id'},
375 citation => $citation,
377 status => $biblio->{'status'},
378 record_sequence => $biblio->{'record_sequence'},
379 overlay_status => $biblio->{'overlay_status'},
380 match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
381 match_citation => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
382 match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
384 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
385 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
386 my $infos = get_infos_syspref($marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2']);
387 my $price = $infos->{price};
388 my $quantity = $infos->{quantity};
389 my $budget_code = $infos->{budget_code};
390 my $discount = $infos->{discount};
391 my $sort1 = $infos->{sort1};
392 my $sort2 = $infos->{sort2};
395 my $biblio_budget = GetBudgetByCode($budget_code);
397 $budget_id = $biblio_budget->{budget_id};
400 $cellrecord{price} = $price || '';
401 $cellrecord{quantity} = $quantity || '';
402 $cellrecord{budget_id} = $budget_id || '';
403 $cellrecord{discount} = $discount || '';
404 $cellrecord{sort1} = $sort1 || '';
405 $cellrecord{sort2} = $sort2 || '';
407 push @list, \%cellrecord;
409 my $num_records = $batch->{'num_records'};
410 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
411 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
412 my $item_action = GetImportBatchItemAction($import_batch_id);
413 $template->param(biblio_list => \@list,
414 num_results => $num_records,
415 import_batch_id => $import_batch_id,
416 "overlay_action_${overlay_action}" => 1,
417 overlay_action => $overlay_action,
418 "nomatch_action_${nomatch_action}" => 1,
419 nomatch_action => $nomatch_action,
420 "item_action_${item_action}" => 1,
421 item_action => $item_action
423 batch_info($template, $batch);
427 my ($template, $batch) = @_;
428 $template->param(batch_info => 1,
429 file_name => $batch->{'file_name'},
430 comments => $batch->{'comments'},
431 import_status => $batch->{'import_status'},
432 upload_timestamp => $batch->{'upload_timestamp'},
433 num_records => $batch->{'num_records'},
434 num_items => $batch->{'num_items'});
435 if ($batch->{'num_records'} > 0) {
436 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
437 $template->param(can_commit => 1);
439 if ($batch->{'import_status'} eq 'imported') {
440 $template->param(can_revert => 1);
443 if (defined $batch->{'matcher_id'}) {
444 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
445 if (defined $matcher) {
446 $template->param('current_matcher_id' => $batch->{'matcher_id'},
447 'current_matcher_code' => $matcher->code(),
448 'current_matcher_description' => $matcher->description());
451 add_matcher_list($batch->{'matcher_id'}, $template);
454 sub add_matcher_list {
455 my ($current_matcher_id, $template) = @_;
456 my @matchers = C4::Matcher::GetMatcherList();
457 if (defined $current_matcher_id) {
458 for (my $i = 0; $i <= $#matchers; $i++) {
459 if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
460 $matchers[$i]->{'selected'} = 1;
464 $template->param(available_matchers => \@matchers);
467 sub get_infos_syspref {
468 my ($record, $field_list) = @_;
469 my $syspref = C4::Context->preference('MarcFieldsToOrder');
470 $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
472 YAML::Load($syspref);
475 warn "Unable to parse MarcFieldsToOrder syspref : $@";
479 for my $field_name ( @$field_list ) {
480 next unless exists $yaml->{$field_name};
481 my @fields = split /\|/, $yaml->{$field_name};
482 for my $field ( @fields ) {
483 my ( $f, $sf ) = split /\$/, $field;
484 next unless $f and $sf;
485 if ( my $v = $record->subfield( $f, $sf ) ) {
486 $r->{$field_name} = $v;
488 last if $yaml->{$field};