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>.
34 use C4::Search qw/FindDuplicate/;
41 use C4::Suggestions; # GetSuggestion
42 use C4::Branch; # GetBranches
45 use Koha::Number::Price;
46 use Koha::Acquisition::Order;
47 use Koha::Acquisition::Bookseller;
50 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
51 template_name => "acqui/addorderiso2709.tt",
55 flagsrequired => { acquisition => 'order_manage' },
59 my $cgiparams = $input->Vars;
60 my $op = $cgiparams->{'op'} || '';
61 my $booksellerid = $input->param('booksellerid');
62 my $allmatch = $input->param('allmatch');
63 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
66 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
67 booksellerid => $booksellerid,
68 booksellername => $bookseller->{name},
71 if ($cgiparams->{'import_batch_id'} && $op eq ""){
72 $op = "batch_details";
76 if (! $cgiparams->{'basketno'}){
77 die "Basketnumber required to order from iso2709 file import";
81 # 1st step = choose the file to import into acquisition
84 $template->param("basketno" => $cgiparams->{'basketno'});
86 import_batches_list($template);
88 # 2nd step = display the content of the chosen file
90 } elsif ($op eq "batch_details"){
91 #display lines inside the selected batch
92 # get currencies (for change rates calcs if needed)
93 my $active_currency = GetCurrency();
95 if (! $data->{currency} ) { # New order no currency set
96 if ( $bookseller->{listprice} ) {
97 $default_currency = $bookseller->{listprice};
100 $default_currency = $active_currency->{currency};
103 my @rates = GetCurrencies();
107 my @loop_currency = ();
108 for my $curr ( @rates ) {
110 if ($data->{currency} ) {
111 $selected = $curr->{currency} eq $data->{currency};
114 $selected = $curr->{currency} eq $default_currency;
116 push @loop_currency, {
117 currcode => $curr->{currency},
118 rate => $curr->{rate},
119 selected => $selected,
123 $template->param("batch_details" => 1,
124 "basketno" => $cgiparams->{'basketno'},
125 loop_currencies => \@loop_currency,
126 "allmatch" => $allmatch,
128 import_biblios_list($template, $cgiparams->{'import_batch_id'});
129 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
130 # prepare empty item form
131 my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
133 # warn "==> ".Data::Dumper::Dumper($cell);
135 $cell = PrepareItemrecordDisplay( '', '', '', '' );
136 $template->param( 'NoACQframework' => 1 );
139 push @itemloop, $cell;
141 $template->param( items => \@itemloop );
144 # 3rd step = import the records
146 } elsif ( $op eq 'import_records' ) {
147 #import selected lines
148 $template->param('basketno' => $cgiparams->{'basketno'});
149 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
150 my $budgets = GetBudgets();
151 if (scalar @$budgets == 0){
152 die "No budgets defined, can't continue";
154 my $budget_id = @$budgets[0]->{'budget_id'};
155 #get all records from a batch, and check their import status to see if they are checked.
156 #(default values: quantity 1, uncertainprice yes, first budget)
158 # retrieve the file you want to import
159 my $import_batch_id = $cgiparams->{'import_batch_id'};
160 my $biblios = GetImportRecordsRange($import_batch_id);
163 my @import_record_id_selected = $input->multi_param("import_record_id");
164 my @quantities = $input->multi_param('quantity');
165 my @prices = $input->multi_param('price');
166 my @budgets_id = $input->multi_param('budget_id');
167 my @discount = $input->multi_param('discount');
168 my @sort1 = $input->multi_param('sort1');
169 my @sort2 = $input->multi_param('sort2');
170 my $matcher_id = $input->param('matcher_id');
171 my $cur = GetCurrency();
172 for my $biblio (@$biblios){
173 # Check if this import_record_id was selected
174 next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
175 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
176 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
177 my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
178 my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
179 my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
180 my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
181 my $c_discount = shift ( @discount);
182 $c_discount = $c_discount / 100 if $c_discount > 1;
183 my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
184 my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
186 # 1st insert the biblio, or find it through matcher
187 unless ( $biblionumber ) {
189 if ( $matcher_id eq '_TITLE_AUTHOR_' ) {
190 $duplinbatch = $import_batch_id if FindDuplicate($marcrecord);
193 my $matcher = C4::Matcher->fetch($matcher_id);
194 my @matches = $matcher->get_matches( $marcrecord, my $max_matches = 1 );
195 $duplinbatch = $import_batch_id if @matches;
198 next if $duplinbatch;
205 my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
206 if ( $marcrecord->field($isbnfield) ) {
207 foreach my $field ( $marcrecord->field($isbnfield) ) {
208 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
209 my $newisbn = $field->subfield($isbnsubfield);
211 $field->update( $isbnsubfield => $newisbn );
215 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
216 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
217 # 2nd add authorities if applicable
218 if (C4::Context->preference("BiblioAddsAuthorities")){
219 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
222 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
225 my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
226 my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
227 # get quantity in the MARC record (1 if none)
228 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
230 biblionumber => $biblionumber,
231 basketno => $cgiparams->{'basketno'},
232 quantity => $c_quantity,
233 branchcode => $patron->{branchcode},
234 budget_id => $c_budget_id,
238 order_internalnote => $cgiparams->{'all_order_internalnote'},
239 order_vendornote => $cgiparams->{'all_order_vendornote'},
240 currency => $cgiparams->{'all_currency'},
242 # get the price if there is one.
243 my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
245 # in France, the cents separator is the , but sometimes, ppl use a .
246 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
247 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
248 $price = Koha::Number::Price->new($price)->unformat;
249 $orderinfo{gstrate} = $bookseller->{gstrate};
250 my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
251 if ( $bookseller->{listincgst} ) {
253 $orderinfo{ecost} = $price;
254 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
256 $orderinfo{ecost} = $price * ( 1 - $c );
257 $orderinfo{rrp} = $price;
261 $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
262 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
264 $orderinfo{rrp} = $price / ( 1 + $orderinfo{gstrate} );
265 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
268 $orderinfo{listprice} = $orderinfo{rrp} / $cur->{rate};
269 $orderinfo{unitprice} = $orderinfo{ecost};
270 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
272 $orderinfo{listprice} = 0;
275 # remove uncertainprice flag if we have found a price in the MARC record
276 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
277 my $order = Koha::Acquisition::Order->new( \%orderinfo )->insert;
279 # 4th, add items if applicable
280 # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
281 # this is not optimised, but it's working !
282 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
283 my @tags = $input->multi_param('tag');
284 my @subfields = $input->multi_param('subfield');
285 my @field_values = $input->multi_param('field_value');
286 my @serials = $input->multi_param('serial');
287 my @ind_tag = $input->multi_param('ind_tag');
288 my @indicator = $input->multi_param('indicator');
290 push @{ $item->{tags} }, $tags[0];
291 push @{ $item->{subfields} }, $subfields[0];
292 push @{ $item->{field_values} }, $field_values[0];
293 push @{ $item->{ind_tag} }, $ind_tag[0];
294 push @{ $item->{indicator} }, $indicator[0];
295 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@indicator, \@ind_tag );
296 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
297 for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
298 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
299 $order->add_item( $itemnumber );
302 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
308 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&duplinbatch=$duplinbatch");
310 print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&basketno=".$cgiparams->{'basketno'}."&booksellerid=$booksellerid&allmatch=1");
315 my $budgets = GetBudgets();
316 my $budget_id = @$budgets[0]->{'budget_id'};
317 # build bookfund list
318 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
319 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
320 my $budget = GetBudget($budget_id);
323 my $budget_loop = [];
324 my $budgets_hierarchy = GetBudgetHierarchy;
325 foreach my $r ( @{$budgets_hierarchy} ) {
326 next unless (CanUserUseBudget($borrower, $r, $userflags));
327 if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
330 push @{$budget_loop},
331 { b_id => $r->{budget_id},
332 b_txt => $r->{budget_name},
333 b_sort1_authcat => $r->{'sort1_authcat'},
334 b_sort2_authcat => $r->{'sort2_authcat'},
335 b_active => $r->{budget_period_active},
336 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
341 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
343 $template->param( budget_loop => $budget_loop,);
345 output_html_with_http_headers $input, $cookie, $template->output;
348 sub import_batches_list {
350 my $batches = GetImportBatchRangeDesc();
353 foreach my $batch (@$batches) {
354 if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
355 # check if there is at least 1 line still staged
356 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
357 if (scalar @$stagedList) {
359 import_batch_id => $batch->{'import_batch_id'},
360 num_records => $batch->{'num_records'},
361 num_items => $batch->{'num_items'},
362 staged_date => $batch->{'upload_timestamp'},
363 import_status => $batch->{'import_status'},
364 file_name => $batch->{'file_name'},
365 comments => $batch->{'comments'},
368 # if there are no more line to includes, set the status to imported
369 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
373 $template->param(batch_list => \@list);
374 my $num_batches = GetNumberOfNonZ3950ImportBatches();
375 $template->param(num_results => $num_batches);
378 sub import_biblios_list {
379 my ($template, $import_batch_id) = @_;
380 my $batch = GetImportBatch($import_batch_id,'staged');
381 return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
382 my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
385 foreach my $biblio (@$biblios) {
386 my $citation = $biblio->{'title'};
387 $citation .= " $biblio->{'author'}" if $biblio->{'author'};
388 $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
389 $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
390 $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
391 $citation .= $biblio->{'issn'} if $biblio->{'issn'};
392 $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
393 my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
395 import_record_id => $biblio->{'import_record_id'},
396 citation => $citation,
398 status => $biblio->{'status'},
399 record_sequence => $biblio->{'record_sequence'},
400 overlay_status => $biblio->{'overlay_status'},
401 match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
402 match_citation => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
403 match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
405 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
406 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
407 my $infos = get_infos_syspref($marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2']);
408 my $price = $infos->{price};
409 my $quantity = $infos->{quantity};
410 my $budget_code = $infos->{budget_code};
411 my $discount = $infos->{discount};
412 my $sort1 = $infos->{sort1};
413 my $sort2 = $infos->{sort2};
416 my $biblio_budget = GetBudgetByCode($budget_code);
418 $budget_id = $biblio_budget->{budget_id};
421 $cellrecord{price} = $price || '';
422 $cellrecord{quantity} = $quantity || '';
423 $cellrecord{budget_id} = $budget_id || '';
424 $cellrecord{discount} = $discount || '';
425 $cellrecord{sort1} = $sort1 || '';
426 $cellrecord{sort2} = $sort2 || '';
428 push @list, \%cellrecord;
430 my $num_records = $batch->{'num_records'};
431 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
432 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
433 my $item_action = GetImportBatchItemAction($import_batch_id);
434 $template->param(biblio_list => \@list,
435 num_results => $num_records,
436 import_batch_id => $import_batch_id,
437 "overlay_action_${overlay_action}" => 1,
438 overlay_action => $overlay_action,
439 "nomatch_action_${nomatch_action}" => 1,
440 nomatch_action => $nomatch_action,
441 "item_action_${item_action}" => 1,
442 item_action => $item_action
444 batch_info($template, $batch);
448 my ($template, $batch) = @_;
449 $template->param(batch_info => 1,
450 file_name => $batch->{'file_name'},
451 comments => $batch->{'comments'},
452 import_status => $batch->{'import_status'},
453 upload_timestamp => $batch->{'upload_timestamp'},
454 num_records => $batch->{'num_records'},
455 num_items => $batch->{'num_items'});
456 if ($batch->{'num_records'} > 0) {
457 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
458 $template->param(can_commit => 1);
460 if ($batch->{'import_status'} eq 'imported') {
461 $template->param(can_revert => 1);
464 if (defined $batch->{'matcher_id'}) {
465 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
466 if (defined $matcher) {
467 $template->param('current_matcher_id' => $batch->{'matcher_id'},
468 'current_matcher_code' => $matcher->code(),
469 'current_matcher_description' => $matcher->description());
472 add_matcher_list($batch->{'matcher_id'}, $template);
475 sub add_matcher_list {
476 my ($current_matcher_id, $template) = @_;
477 my @matchers = C4::Matcher::GetMatcherList();
478 if (defined $current_matcher_id) {
479 for (my $i = 0; $i <= $#matchers; $i++) {
480 if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
481 $matchers[$i]->{'selected'} = 1;
485 $template->param(available_matchers => \@matchers);
488 sub get_infos_syspref {
489 my ($record, $field_list) = @_;
490 my $syspref = C4::Context->preference('MarcFieldsToOrder');
491 $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
493 YAML::Load($syspref);
496 warn "Unable to parse MarcFieldsToOrder syspref : $@";
500 for my $field_name ( @$field_list ) {
501 next unless exists $yaml->{$field_name};
502 my @fields = split /\|/, $yaml->{$field_name};
503 for my $field ( @fields ) {
504 my ( $f, $sf ) = split /\$/, $field;
505 next unless $f and $sf;
506 if ( my $v = $record->subfield( $f, $sf ) ) {
507 $r->{$field_name} = $v;
509 last if $yaml->{$field};