Bug 12612: Remove CGI::scrolling_list from auth_tag_structure.pl
[koha.git] / acqui / addorderiso2709.pl
blobf4d1a257d1ad3d2f86c7972395241fd35b6b19d2
1 #!/usr/bin/perl
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
14 # version.
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.
24 use Modern::Perl;
25 use CGI;
26 use Carp;
27 use Number::Format qw(:all);
28 use YAML qw/Load/;
30 use C4::Context;
31 use C4::Auth;
32 use C4::Input;
33 use C4::Output;
34 use C4::ImportBatch;
35 use C4::Matcher;
36 use C4::Search qw/FindDuplicate/;
37 use C4::Acquisition;
38 use C4::Biblio;
39 use C4::Items;
40 use C4::Koha;
41 use C4::Budgets;
42 use C4::Acquisition;
43 use C4::Bookseller qw/GetBookSellerFromId/;
44 use C4::Suggestions; # GetSuggestion
45 use C4::Branch; # GetBranches
46 use C4::Members;
48 my $input = new CGI;
49 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
50 template_name => "acqui/addorderiso2709.tt",
51 query => $input,
52 type => "intranet",
53 authnotrequired => 0,
54 flagsrequired => { acquisition => 'order_manage' },
55 debug => 1,
56 });
58 my $cgiparams = $input->Vars;
59 my $op = $cgiparams->{'op'} || '';
60 my $booksellerid = $input->param('booksellerid');
61 my $bookseller = GetBookSellerFromId($booksellerid);
62 my $data;
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";
73 #Needed parameters:
74 if (! $cgiparams->{'basketno'}){
75 die "Basketnumber required to order from iso2709 file import";
79 # 1st step = choose the file to import into acquisition
81 if ($op eq ""){
82 $template->param("basketno" => $cgiparams->{'basketno'});
83 #display batches
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();
92 my $default_currency;
93 if (! $data->{currency} ) { # New order no currency set
94 if ( $bookseller->{listprice} ) {
95 $default_currency = $bookseller->{listprice};
97 else {
98 $default_currency = $active_currency->{currency};
101 my @rates = GetCurrencies();
103 # ## @rates
105 my @loop_currency = ();
106 for my $curr ( @rates ) {
107 my $selected;
108 if ($data->{currency} ) {
109 $selected = $curr->{currency} eq $data->{currency};
111 else {
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);
131 unless ($cell) {
132 $cell = PrepareItemrecordDisplay( '', '', '', '' );
133 $template->param( 'NoACQframework' => 1 );
135 my @itemloop;
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 > 1;
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 ) {
183 # add the biblio
184 my $bibitemnum;
186 # remove ISBN -
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);
192 $newisbn =~ s/-//g;
193 $field->update( $isbnsubfield => $newisbn );
197 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
198 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
199 # 2nd add authorities if applicable
200 if (C4::Context->preference("BiblioAddsAuthorities")){
201 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
203 } else {
204 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
206 # 3rd add order
207 my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
208 my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
209 # get quantity in the MARC record (1 if none)
210 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
211 my %orderinfo = (
212 biblionumber => $biblionumber,
213 basketno => $cgiparams->{'basketno'},
214 quantity => $c_quantity,
215 branchcode => $patron->{branchcode},
216 budget_id => $c_budget_id,
217 uncertainprice => 1,
218 sort1 => $c_sort1,
219 sort2 => $c_sort2,
220 order_internalnote => $cgiparams->{'all_order_internalnote'},
221 order_vendornote => $cgiparams->{'all_order_vendornote'},
222 currency => $cgiparams->{'all_currency'},
224 # get the price if there is one.
225 my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
226 if ($price){
227 # in France, the cents separator is the , but sometimes, ppl use a .
228 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
229 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
230 $price = $num->unformat_number($price);
231 $orderinfo{gstrate} = $bookseller->{gstrate};
232 my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
233 if ( $bookseller->{listincgst} ) {
234 if ( $c_discount ) {
235 $orderinfo{ecost} = $price;
236 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
237 } else {
238 $orderinfo{ecost} = $price * ( 1 - $c );
239 $orderinfo{rrp} = $price;
241 } else {
242 if ( $c_discount ) {
243 $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
244 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
245 } else {
246 $orderinfo{rrp} = $price / ( 1 + $orderinfo{gstrate} );
247 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
250 $orderinfo{listprice} = $orderinfo{rrp} / $cur->{rate};
251 $orderinfo{unitprice} = $orderinfo{ecost};
252 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
253 } else {
254 $orderinfo{listprice} = 0;
257 # remove uncertainprice flag if we have found a price in the MARC record
258 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
259 my ( $basketno, $ordernumber ) = NewOrder( \%orderinfo );
261 # 4th, add items if applicable
262 # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
263 # this is not optimised, but it's working !
264 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
265 my @tags = $input->param('tag');
266 my @subfields = $input->param('subfield');
267 my @field_values = $input->param('field_value');
268 my @serials = $input->param('serial');
269 my @ind_tag = $input->param('ind_tag');
270 my @indicator = $input->param('indicator');
271 my $item;
272 push @{ $item->{tags} }, $tags[0];
273 push @{ $item->{subfields} }, $subfields[0];
274 push @{ $item->{field_values} }, $field_values[0];
275 push @{ $item->{ind_tag} }, $ind_tag[0];
276 push @{ $item->{indicator} }, $indicator[0];
277 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@ind_tag, \@indicator );
278 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
279 for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
280 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
281 NewOrderItem( $itemnumber, $ordernumber );
283 } else {
284 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
287 # go to basket page
288 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'});
289 exit;
292 my $budgets = GetBudgets();
293 my $budget_id = @$budgets[0]->{'budget_id'};
294 # build bookfund list
295 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
296 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
297 my $budget = GetBudget($budget_id);
299 # build budget list
300 my $budget_loop = [];
301 my $budgets_hierarchy = GetBudgetHierarchy;
302 foreach my $r ( @{$budgets_hierarchy} ) {
303 next unless (CanUserUseBudget($borrower, $r, $userflags));
304 if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
305 next;
307 push @{$budget_loop},
308 { b_id => $r->{budget_id},
309 b_txt => $r->{budget_name},
310 b_sort1_authcat => $r->{'sort1_authcat'},
311 b_sort2_authcat => $r->{'sort2_authcat'},
312 b_active => $r->{budget_period_active},
313 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
317 @{$budget_loop} =
318 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
320 $template->param( budget_loop => $budget_loop,);
322 output_html_with_http_headers $input, $cookie, $template->output;
325 sub import_batches_list {
326 my ($template) = @_;
327 my $batches = GetImportBatchRangeDesc();
329 my @list = ();
330 foreach my $batch (@$batches) {
331 if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ ) {
332 # check if there is at least 1 line still staged
333 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, undef, $batch->{import_status}, { order_by_direction => 'ASC' });
334 if (scalar @$stagedList) {
335 push @list, {
336 import_batch_id => $batch->{'import_batch_id'},
337 num_records => $batch->{'num_records'},
338 num_items => $batch->{'num_items'},
339 staged_date => $batch->{'upload_timestamp'},
340 import_status => $batch->{'import_status'},
341 file_name => $batch->{'file_name'},
342 comments => $batch->{'comments'},
344 } else {
345 # if there are no more line to includes, set the status to imported
346 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
350 $template->param(batch_list => \@list);
351 my $num_batches = GetNumberOfNonZ3950ImportBatches();
352 $template->param(num_results => $num_batches);
355 sub import_biblios_list {
356 my ($template, $import_batch_id) = @_;
357 my $batch = GetImportBatch($import_batch_id,'staged');
358 return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
359 my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
360 my @list = ();
362 foreach my $biblio (@$biblios) {
363 my $citation = $biblio->{'title'};
364 $citation .= " $biblio->{'author'}" if $biblio->{'author'};
365 $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
366 $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
367 $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
368 $citation .= $biblio->{'issn'} if $biblio->{'issn'};
369 $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
370 my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
371 my %cellrecord = (
372 import_record_id => $biblio->{'import_record_id'},
373 citation => $citation,
374 import => 1,
375 status => $biblio->{'status'},
376 record_sequence => $biblio->{'record_sequence'},
377 overlay_status => $biblio->{'overlay_status'},
378 match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
379 match_citation => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
380 match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
382 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
383 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
384 my $infos = get_infos_syspref($marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2']);
385 my $price = $infos->{price};
386 my $quantity = $infos->{quantity};
387 my $budget_code = $infos->{budget_code};
388 my $discount = $infos->{discount};
389 my $sort1 = $infos->{sort1};
390 my $sort2 = $infos->{sort2};
391 my $budget_id;
392 if($budget_code) {
393 my $biblio_budget = GetBudgetByCode($budget_code);
394 if($biblio_budget) {
395 $budget_id = $biblio_budget->{budget_id};
398 $cellrecord{price} = $price || '';
399 $cellrecord{quantity} = $quantity || '';
400 $cellrecord{budget_id} = $budget_id || '';
401 $cellrecord{discount} = $discount || '';
402 $cellrecord{sort1} = $sort1 || '';
403 $cellrecord{sort2} = $sort2 || '';
405 push @list, \%cellrecord;
407 my $num_records = $batch->{'num_records'};
408 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
409 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
410 my $item_action = GetImportBatchItemAction($import_batch_id);
411 $template->param(biblio_list => \@list,
412 num_results => $num_records,
413 import_batch_id => $import_batch_id,
414 "overlay_action_${overlay_action}" => 1,
415 overlay_action => $overlay_action,
416 "nomatch_action_${nomatch_action}" => 1,
417 nomatch_action => $nomatch_action,
418 "item_action_${item_action}" => 1,
419 item_action => $item_action
421 batch_info($template, $batch);
424 sub batch_info {
425 my ($template, $batch) = @_;
426 $template->param(batch_info => 1,
427 file_name => $batch->{'file_name'},
428 comments => $batch->{'comments'},
429 import_status => $batch->{'import_status'},
430 upload_timestamp => $batch->{'upload_timestamp'},
431 num_records => $batch->{'num_records'},
432 num_items => $batch->{'num_items'});
433 if ($batch->{'num_records'} > 0) {
434 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
435 $template->param(can_commit => 1);
437 if ($batch->{'import_status'} eq 'imported') {
438 $template->param(can_revert => 1);
441 if (defined $batch->{'matcher_id'}) {
442 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
443 if (defined $matcher) {
444 $template->param('current_matcher_id' => $batch->{'matcher_id'},
445 'current_matcher_code' => $matcher->code(),
446 'current_matcher_description' => $matcher->description());
449 add_matcher_list($batch->{'matcher_id'}, $template);
452 sub add_matcher_list {
453 my ($current_matcher_id, $template) = @_;
454 my @matchers = C4::Matcher::GetMatcherList();
455 if (defined $current_matcher_id) {
456 for (my $i = 0; $i <= $#matchers; $i++) {
457 if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
458 $matchers[$i]->{'selected'} = 1;
462 $template->param(available_matchers => \@matchers);
465 sub get_infos_syspref {
466 my ($record, $field_list) = @_;
467 my $syspref = C4::Context->preference('MarcFieldsToOrder');
468 $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
469 my $yaml = eval {
470 YAML::Load($syspref);
472 if ( $@ ) {
473 warn "Unable to parse MarcFieldsToOrder syspref : $@";
474 return ();
476 my $r;
477 for my $field_name ( @$field_list ) {
478 next unless exists $yaml->{$field_name};
479 my @fields = split /\|/, $yaml->{$field_name};
480 for my $field ( @fields ) {
481 my ( $f, $sf ) = split /\$/, $field;
482 next unless $f and $sf;
483 if ( my $v = $record->subfield( $f, $sf ) ) {
484 $r->{$field_name} = $v;
486 last if $yaml->{$field};
489 return $r;