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 under the
12 # terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 2 of the License, or (at your option) any later
16 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
17 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License along
21 # with Koha; if not, write to the Free Software Foundation, Inc.,
22 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 use Number::Format qw(:all);
36 use C4::Search qw/FindDuplicate/;
43 use C4::Bookseller qw/GetBookSellerFromId/;
44 use C4::Suggestions; # GetSuggestion
45 use C4::Branch; # GetBranches
49 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
50 template_name => "acqui/addorderiso2709.tmpl",
54 flagsrequired => { acquisition => 'order_manage' },
58 my $cgiparams = $input->Vars;
59 my $op = $cgiparams->{'op'} || '';
60 my $booksellerid = $input->param('booksellerid');
61 my $bookseller = GetBookSellerFromId($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 choosen 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 $active_currency = GetCurrency();
93 if (! $data->{currency} ) { # New order no currency set
94 if ( $bookseller->{listprice} ) {
95 $default_currency = $bookseller->{listprice};
98 $default_currency = $active_currency->{currency};
101 my @rates = GetCurrencies();
105 my @loop_currency = ();
106 for my $curr ( @rates ) {
108 if ($data->{currency} ) {
109 $selected = $curr->{currency} eq $data->{currency};
112 $selected = $curr->{currency} eq $default_currency;
114 push @loop_currency, {
115 currcode => $curr->{currency},
116 rate => $curr->{rate},
117 selected => $selected,
121 $template->param("batch_details" => 1,
122 "basketno" => $cgiparams->{'basketno'},
123 loop_currencies => \@loop_currency,
125 import_biblios_list($template, $cgiparams->{'import_batch_id'});
126 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
127 # prepare empty item form
128 my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
130 # warn "==> ".Data::Dumper::Dumper($cell);
132 $cell = PrepareItemrecordDisplay( '', '', '', '' );
133 $template->param( 'NoACQframework' => 1 );
136 push @itemloop, $cell;
138 $template->param( items => \@itemloop );
141 # 3rd step = import the records
143 } elsif ( $op eq 'import_records' ) {
144 my $num=FormatNumber();
145 #import selected lines
146 $template->param('basketno' => $cgiparams->{'basketno'});
147 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
148 my $budgets = GetBudgets();
149 if (scalar @$budgets == 0){
150 die "No budgets defined, can't continue";
152 my $budget_id = @$budgets[0]->{'budget_id'};
153 #get all records from a batch, and check their import status to see if they are checked.
154 #(default values: quantity 1, uncertainprice yes, first budget)
156 # retrieve the file you want to import
157 my $import_batch_id = $cgiparams->{'import_batch_id'};
158 my $biblios = GetImportRecordsRange($import_batch_id);
159 my @import_record_id_selected = $input->param("import_record_id");
160 my @quantities = $input->param('quantity');
161 my @prices = $input->param('price');
162 my @budgets_id = $input->param('budget_id');
163 my @discount = $input->param('discount');
164 my @sort1 = $input->param('sort1');
165 my @sort2 = $input->param('sort2');
166 my $cur = GetCurrency();
167 for my $biblio (@$biblios){
168 # Check if this import_record_id was selected
169 next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
170 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
171 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
172 my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
173 my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
174 my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
175 my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
176 my $c_discount = shift ( @discount);
177 $c_discount = $c_discount / 100 if $c_discount > 100;
178 my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
179 my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
181 # 1st insert the biblio, or find it through matcher
182 unless ( $biblionumber ) {
187 my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
188 if ( $marcrecord->field($isbnfield) ) {
189 foreach my $field ( $marcrecord->field($isbnfield) ) {
190 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
191 my $newisbn = $field->subfield($isbnsubfield);
193 $field->update( $isbnsubfield => $newisbn );
197 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
198 # 2nd add authorities if applicable
199 if (C4::Context->preference("BiblioAddsAuthorities")){
200 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
203 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
206 my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
207 my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
208 # get quantity in the MARC record (1 if none)
209 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
211 biblionumber => $biblionumber,
212 basketno => $cgiparams->{'basketno'},
213 quantity => $c_quantity,
214 branchcode => $patron->{branchcode},
215 budget_id => $c_budget_id,
219 order_internalnote => $cgiparams->{'all_order_internalnote'},
220 order_vendornote => $cgiparams->{'all_order_vendornote'},
221 currency => $cgiparams->{'all_currency'},
223 # get the price if there is one.
224 my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
226 # in France, the cents separator is the , but sometimes, ppl use a .
227 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
228 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
229 $price = $num->unformat_number($price);
230 $orderinfo{gstrate} = $bookseller->{gstrate};
231 my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
232 if ( $bookseller->{listincgst} ) {
234 $orderinfo{ecost} = $price;
235 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
237 $orderinfo{ecost} = $price * ( 1 - $c );
238 $orderinfo{rrp} = $price;
242 $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
243 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
245 $orderinfo{rrp} = $price / ( 1 + $orderinfo{gstrate} );
246 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
249 $orderinfo{listprice} = $orderinfo{rrp} / $cur->{rate};
250 $orderinfo{unitprice} = $orderinfo{ecost};
251 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
253 $orderinfo{listprice} = 0;
256 # remove uncertainprice flag if we have found a price in the MARC record
257 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
258 my ( $basketno, $ordernumber ) = NewOrder( \%orderinfo );
260 # 4th, add items if applicable
261 # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
262 # this is not optimised, but it's working !
263 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
264 my @tags = $input->param('tag');
265 my @subfields = $input->param('subfield');
266 my @field_values = $input->param('field_value');
267 my @serials = $input->param('serial');
268 my @ind_tag = $input->param('ind_tag');
269 my @indicator = $input->param('indicator');
271 push @{ $item->{tags} }, $tags[0];
272 push @{ $item->{subfields} }, $subfields[0];
273 push @{ $item->{field_values} }, $field_values[0];
274 push @{ $item->{ind_tag} }, $ind_tag[0];
275 push @{ $item->{indicator} }, $indicator[0];
276 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@ind_tag, \@indicator );
277 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
278 for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
279 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
280 NewOrderItem( $itemnumber, $ordernumber );
285 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'});
289 my $budgets = GetBudgets();
290 my $budget_id = @$budgets[0]->{'budget_id'};
291 # build bookfund list
292 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
293 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
294 my $budget = GetBudget($budget_id);
297 my $budget_loop = [];
298 my $budgets_hierarchy = GetBudgetHierarchy;
299 foreach my $r ( @{$budgets_hierarchy} ) {
300 next unless (CanUserUseBudget($borrower, $r, $userflags));
301 if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
304 push @{$budget_loop},
305 { b_id => $r->{budget_id},
306 b_txt => $r->{budget_name},
307 b_sort1_authcat => $r->{'sort1_authcat'},
308 b_sort2_authcat => $r->{'sort2_authcat'},
309 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
312 $template->param( budget_loop => $budget_loop,);
315 if ($budget) { # its a mod ..
316 if ( defined $budget->{'sort1_authcat'} ) { # with custom Asort* planning values
317 $CGIsort1 = GetAuthvalueDropbox( $budget->{'sort1_authcat'}, $data->{'sort1'} );
319 } elsif ( scalar(@$budgets) ) {
320 } elsif ( scalar(@$budgets_hierarchy) ) {
321 $CGIsort1 = GetAuthvalueDropbox( @$budgets_hierarchy[0]->{'sort1_authcat'}, '' );
323 # if CGIsort is successfully fetched, the use it
324 # else - failback to plain input-field
326 $template->param( CGIsort1 => $CGIsort1 );
328 $template->param( sort1 => $data->{'sort1'} );
333 if ( defined $budget->{'sort2_authcat'} ) {
334 $CGIsort2 = GetAuthvalueDropbox( $budget->{'sort2_authcat'}, $data->{'sort2'} );
336 } elsif ( scalar(@$budgets_hierarchy) ) {
337 $CGIsort2 = GetAuthvalueDropbox( @$budgets_hierarchy[0]->{sort2_authcat}, '' );
340 $template->param( CGIsort2 => $CGIsort2 );
342 $template->param( sort2 => $data->{'sort2'} );
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$/ ) {
355 # check if there is at least 1 line still staged
356 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, undef, $batch->{import_status});
357 if (scalar @$stagedList) {
359 import_batch_id => $batch->{'import_batch_id'},
360 num_biblios => $batch->{'num_biblios'},
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_biblios = $batch->{'num_biblios'};
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_biblios,
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_biblios => $batch->{'num_biblios'},
455 num_items => $batch->{'num_biblios'});
456 if ($batch->{'num_biblios'} > 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};