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>.
35 use C4::Search qw/FindDuplicate/;
42 use C4::Suggestions; # GetSuggestion
43 use C4::Branch; # GetBranches
46 use Koha::Number::Price;
47 use Koha::Acquisition::Order;
48 use Koha::Acquisition::Bookseller;
51 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
52 template_name => "acqui/addorderiso2709.tt",
56 flagsrequired => { acquisition => 'order_manage' },
60 my $cgiparams = $input->Vars;
61 my $op = $cgiparams->{'op'} || '';
62 my $booksellerid = $input->param('booksellerid');
63 my $allmatch = $input->param('allmatch');
64 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
67 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
68 booksellerid => $booksellerid,
69 booksellername => $bookseller->{name},
72 if ($cgiparams->{'import_batch_id'} && $op eq ""){
73 $op = "batch_details";
77 if (! $cgiparams->{'basketno'}){
78 die "Basketnumber required to order from iso2709 file import";
82 # 1st step = choose the file to import into acquisition
85 $template->param("basketno" => $cgiparams->{'basketno'});
87 import_batches_list($template);
89 # 2nd step = display the content of the chosen file
91 } elsif ($op eq "batch_details"){
92 #display lines inside the selected batch
93 # get currencies (for change rates calcs if needed)
94 my $active_currency = GetCurrency();
96 if (! $data->{currency} ) { # New order no currency set
97 if ( $bookseller->{listprice} ) {
98 $default_currency = $bookseller->{listprice};
101 $default_currency = $active_currency->{currency};
104 my @rates = GetCurrencies();
108 my @loop_currency = ();
109 for my $curr ( @rates ) {
111 if ($data->{currency} ) {
112 $selected = $curr->{currency} eq $data->{currency};
115 $selected = $curr->{currency} eq $default_currency;
117 push @loop_currency, {
118 currcode => $curr->{currency},
119 rate => $curr->{rate},
120 selected => $selected,
124 $template->param("batch_details" => 1,
125 "basketno" => $cgiparams->{'basketno'},
126 loop_currencies => \@loop_currency,
127 "allmatch" => $allmatch,
129 import_biblios_list($template, $cgiparams->{'import_batch_id'});
130 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
131 # prepare empty item form
132 my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
134 # warn "==> ".Data::Dumper::Dumper($cell);
136 $cell = PrepareItemrecordDisplay( '', '', '', '' );
137 $template->param( 'NoACQframework' => 1 );
140 push @itemloop, $cell;
142 $template->param( items => \@itemloop );
145 # 3rd step = import the records
147 } elsif ( $op eq 'import_records' ) {
148 #import selected lines
149 $template->param('basketno' => $cgiparams->{'basketno'});
150 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
151 my $budgets = GetBudgets();
152 if (scalar @$budgets == 0){
153 die "No budgets defined, can't continue";
155 my $budget_id = @$budgets[0]->{'budget_id'};
156 #get all records from a batch, and check their import status to see if they are checked.
157 #(default values: quantity 1, uncertainprice yes, first budget)
159 # retrieve the file you want to import
160 my $import_batch_id = $cgiparams->{'import_batch_id'};
161 my $biblios = GetImportRecordsRange($import_batch_id);
164 my @import_record_id_selected = $input->param("import_record_id");
165 my @quantities = $input->param('quantity');
166 my @prices = $input->param('price');
167 my @budgets_id = $input->param('budget_id');
168 my @discount = $input->param('discount');
169 my @sort1 = $input->param('sort1');
170 my @sort2 = $input->param('sort2');
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 ) {
188 $duplinbatch=$import_batch_id and next if FindDuplicate($marcrecord);
193 my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
194 if ( $marcrecord->field($isbnfield) ) {
195 foreach my $field ( $marcrecord->field($isbnfield) ) {
196 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
197 my $newisbn = $field->subfield($isbnsubfield);
199 $field->update( $isbnsubfield => $newisbn );
203 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
204 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
205 # 2nd add authorities if applicable
206 if (C4::Context->preference("BiblioAddsAuthorities")){
207 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
210 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
213 my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
214 my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
215 # get quantity in the MARC record (1 if none)
216 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
218 biblionumber => $biblionumber,
219 basketno => $cgiparams->{'basketno'},
220 quantity => $c_quantity,
221 branchcode => $patron->{branchcode},
222 budget_id => $c_budget_id,
226 order_internalnote => $cgiparams->{'all_order_internalnote'},
227 order_vendornote => $cgiparams->{'all_order_vendornote'},
228 currency => $cgiparams->{'all_currency'},
230 # get the price if there is one.
231 my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
233 # in France, the cents separator is the , but sometimes, ppl use a .
234 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
235 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
236 $price = Koha::Number::Price->new($price)->unformat;
237 $orderinfo{gstrate} = $bookseller->{gstrate};
238 my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
239 if ( $bookseller->{listincgst} ) {
241 $orderinfo{ecost} = $price;
242 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
244 $orderinfo{ecost} = $price * ( 1 - $c );
245 $orderinfo{rrp} = $price;
249 $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
250 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
252 $orderinfo{rrp} = $price / ( 1 + $orderinfo{gstrate} );
253 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
256 $orderinfo{listprice} = $orderinfo{rrp} / $cur->{rate};
257 $orderinfo{unitprice} = $orderinfo{ecost};
258 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
260 $orderinfo{listprice} = 0;
263 # remove uncertainprice flag if we have found a price in the MARC record
264 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
265 my $order = Koha::Acquisition::Order->new( \%orderinfo )->insert;
267 # 4th, add items if applicable
268 # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
269 # this is not optimised, but it's working !
270 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
271 my @tags = $input->param('tag');
272 my @subfields = $input->param('subfield');
273 my @field_values = $input->param('field_value');
274 my @serials = $input->param('serial');
275 my @ind_tag = $input->param('ind_tag');
276 my @indicator = $input->param('indicator');
278 push @{ $item->{tags} }, $tags[0];
279 push @{ $item->{subfields} }, $subfields[0];
280 push @{ $item->{field_values} }, $field_values[0];
281 push @{ $item->{ind_tag} }, $ind_tag[0];
282 push @{ $item->{indicator} }, $indicator[0];
283 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@ind_tag, \@indicator );
284 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
285 for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
286 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
287 $order->add_item( $itemnumber );
290 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
296 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&duplinbatch=$duplinbatch");
298 print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&basketno=".$cgiparams->{'basketno'}."&booksellerid=$booksellerid&allmatch=1");
303 my $budgets = GetBudgets();
304 my $budget_id = @$budgets[0]->{'budget_id'};
305 # build bookfund list
306 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
307 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
308 my $budget = GetBudget($budget_id);
311 my $budget_loop = [];
312 my $budgets_hierarchy = GetBudgetHierarchy;
313 foreach my $r ( @{$budgets_hierarchy} ) {
314 next unless (CanUserUseBudget($borrower, $r, $userflags));
315 if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
318 push @{$budget_loop},
319 { b_id => $r->{budget_id},
320 b_txt => $r->{budget_name},
321 b_sort1_authcat => $r->{'sort1_authcat'},
322 b_sort2_authcat => $r->{'sort2_authcat'},
323 b_active => $r->{budget_period_active},
324 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
329 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
331 $template->param( budget_loop => $budget_loop,);
333 output_html_with_http_headers $input, $cookie, $template->output;
336 sub import_batches_list {
338 my $batches = GetImportBatchRangeDesc();
341 foreach my $batch (@$batches) {
342 if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ ) {
343 # check if there is at least 1 line still staged
344 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
345 if (scalar @$stagedList) {
347 import_batch_id => $batch->{'import_batch_id'},
348 num_records => $batch->{'num_records'},
349 num_items => $batch->{'num_items'},
350 staged_date => $batch->{'upload_timestamp'},
351 import_status => $batch->{'import_status'},
352 file_name => $batch->{'file_name'},
353 comments => $batch->{'comments'},
356 # if there are no more line to includes, set the status to imported
357 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
361 $template->param(batch_list => \@list);
362 my $num_batches = GetNumberOfNonZ3950ImportBatches();
363 $template->param(num_results => $num_batches);
366 sub import_biblios_list {
367 my ($template, $import_batch_id) = @_;
368 my $batch = GetImportBatch($import_batch_id,'staged');
369 return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
370 my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
373 foreach my $biblio (@$biblios) {
374 my $citation = $biblio->{'title'};
375 $citation .= " $biblio->{'author'}" if $biblio->{'author'};
376 $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
377 $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
378 $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
379 $citation .= $biblio->{'issn'} if $biblio->{'issn'};
380 $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
381 my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
383 import_record_id => $biblio->{'import_record_id'},
384 citation => $citation,
386 status => $biblio->{'status'},
387 record_sequence => $biblio->{'record_sequence'},
388 overlay_status => $biblio->{'overlay_status'},
389 match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
390 match_citation => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
391 match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
393 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
394 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
395 my $infos = get_infos_syspref($marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2']);
396 my $price = $infos->{price};
397 my $quantity = $infos->{quantity};
398 my $budget_code = $infos->{budget_code};
399 my $discount = $infos->{discount};
400 my $sort1 = $infos->{sort1};
401 my $sort2 = $infos->{sort2};
404 my $biblio_budget = GetBudgetByCode($budget_code);
406 $budget_id = $biblio_budget->{budget_id};
409 $cellrecord{price} = $price || '';
410 $cellrecord{quantity} = $quantity || '';
411 $cellrecord{budget_id} = $budget_id || '';
412 $cellrecord{discount} = $discount || '';
413 $cellrecord{sort1} = $sort1 || '';
414 $cellrecord{sort2} = $sort2 || '';
416 push @list, \%cellrecord;
418 my $num_records = $batch->{'num_records'};
419 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
420 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
421 my $item_action = GetImportBatchItemAction($import_batch_id);
422 $template->param(biblio_list => \@list,
423 num_results => $num_records,
424 import_batch_id => $import_batch_id,
425 "overlay_action_${overlay_action}" => 1,
426 overlay_action => $overlay_action,
427 "nomatch_action_${nomatch_action}" => 1,
428 nomatch_action => $nomatch_action,
429 "item_action_${item_action}" => 1,
430 item_action => $item_action
432 batch_info($template, $batch);
436 my ($template, $batch) = @_;
437 $template->param(batch_info => 1,
438 file_name => $batch->{'file_name'},
439 comments => $batch->{'comments'},
440 import_status => $batch->{'import_status'},
441 upload_timestamp => $batch->{'upload_timestamp'},
442 num_records => $batch->{'num_records'},
443 num_items => $batch->{'num_items'});
444 if ($batch->{'num_records'} > 0) {
445 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
446 $template->param(can_commit => 1);
448 if ($batch->{'import_status'} eq 'imported') {
449 $template->param(can_revert => 1);
452 if (defined $batch->{'matcher_id'}) {
453 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
454 if (defined $matcher) {
455 $template->param('current_matcher_id' => $batch->{'matcher_id'},
456 'current_matcher_code' => $matcher->code(),
457 'current_matcher_description' => $matcher->description());
460 add_matcher_list($batch->{'matcher_id'}, $template);
463 sub add_matcher_list {
464 my ($current_matcher_id, $template) = @_;
465 my @matchers = C4::Matcher::GetMatcherList();
466 if (defined $current_matcher_id) {
467 for (my $i = 0; $i <= $#matchers; $i++) {
468 if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
469 $matchers[$i]->{'selected'} = 1;
473 $template->param(available_matchers => \@matchers);
476 sub get_infos_syspref {
477 my ($record, $field_list) = @_;
478 my $syspref = C4::Context->preference('MarcFieldsToOrder');
479 $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
481 YAML::Load($syspref);
484 warn "Unable to parse MarcFieldsToOrder syspref : $@";
488 for my $field_name ( @$field_list ) {
489 next unless exists $yaml->{$field_name};
490 my @fields = split /\|/, $yaml->{$field_name};
491 for my $field ( @fields ) {
492 my ( $f, $sf ) = split /\$/, $field;
493 next unless $f and $sf;
494 if ( my $v = $record->subfield( $f, $sf ) ) {
495 $r->{$field_name} = $v;
497 last if $yaml->{$field};