Bug 3186 - invalid or uninstalled SMSSendDriver (or bad number format) causes process...
[koha.git] / acqui / addorderiso2709.pl
blob15c83eaec48010602e9ce28fd390ff83f197e526
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 use Koha::Number::Price;
49 use Koha::Acquisition::Order;
51 my $input = new CGI;
52 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
53 template_name => "acqui/addorderiso2709.tt",
54 query => $input,
55 type => "intranet",
56 authnotrequired => 0,
57 flagsrequired => { acquisition => 'order_manage' },
58 debug => 1,
59 });
61 my $cgiparams = $input->Vars;
62 my $op = $cgiparams->{'op'} || '';
63 my $booksellerid = $input->param('booksellerid');
64 my $bookseller = GetBookSellerFromId($booksellerid);
65 my $data;
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";
76 #Needed parameters:
77 if (! $cgiparams->{'basketno'}){
78 die "Basketnumber required to order from iso2709 file import";
82 # 1st step = choose the file to import into acquisition
84 if ($op eq ""){
85 $template->param("basketno" => $cgiparams->{'basketno'});
86 #display batches
87 import_batches_list($template);
89 # 2nd step = display the content of the choosen 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();
95 my $default_currency;
96 if (! $data->{currency} ) { # New order no currency set
97 if ( $bookseller->{listprice} ) {
98 $default_currency = $bookseller->{listprice};
100 else {
101 $default_currency = $active_currency->{currency};
104 my @rates = GetCurrencies();
106 # ## @rates
108 my @loop_currency = ();
109 for my $curr ( @rates ) {
110 my $selected;
111 if ($data->{currency} ) {
112 $selected = $curr->{currency} eq $data->{currency};
114 else {
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,
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);
134 unless ($cell) {
135 $cell = PrepareItemrecordDisplay( '', '', '', '' );
136 $template->param( 'NoACQframework' => 1 );
138 my @itemloop;
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);
161 my @import_record_id_selected = $input->param("import_record_id");
162 my @quantities = $input->param('quantity');
163 my @prices = $input->param('price');
164 my @budgets_id = $input->param('budget_id');
165 my @discount = $input->param('discount');
166 my @sort1 = $input->param('sort1');
167 my @sort2 = $input->param('sort2');
168 my $cur = GetCurrency();
169 for my $biblio (@$biblios){
170 # Check if this import_record_id was selected
171 next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
172 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
173 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
174 my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
175 my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
176 my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
177 my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
178 my $c_discount = shift ( @discount);
179 $c_discount = $c_discount / 100 if $c_discount > 1;
180 my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
181 my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
183 # 1st insert the biblio, or find it through matcher
184 unless ( $biblionumber ) {
185 # add the biblio
186 my $bibitemnum;
188 # remove ISBN -
189 my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
190 if ( $marcrecord->field($isbnfield) ) {
191 foreach my $field ( $marcrecord->field($isbnfield) ) {
192 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
193 my $newisbn = $field->subfield($isbnsubfield);
194 $newisbn =~ s/-//g;
195 $field->update( $isbnsubfield => $newisbn );
199 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
200 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
201 # 2nd add authorities if applicable
202 if (C4::Context->preference("BiblioAddsAuthorities")){
203 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
205 } else {
206 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
208 # 3rd add order
209 my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
210 my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
211 # get quantity in the MARC record (1 if none)
212 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
213 my %orderinfo = (
214 biblionumber => $biblionumber,
215 basketno => $cgiparams->{'basketno'},
216 quantity => $c_quantity,
217 branchcode => $patron->{branchcode},
218 budget_id => $c_budget_id,
219 uncertainprice => 1,
220 sort1 => $c_sort1,
221 sort2 => $c_sort2,
222 order_internalnote => $cgiparams->{'all_order_internalnote'},
223 order_vendornote => $cgiparams->{'all_order_vendornote'},
224 currency => $cgiparams->{'all_currency'},
226 # get the price if there is one.
227 my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
228 if ($price){
229 # in France, the cents separator is the , but sometimes, ppl use a .
230 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
231 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
232 $price = Koha::Number::Price->new($price)->unformat;
233 $orderinfo{gstrate} = $bookseller->{gstrate};
234 my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
235 if ( $bookseller->{listincgst} ) {
236 if ( $c_discount ) {
237 $orderinfo{ecost} = $price;
238 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
239 } else {
240 $orderinfo{ecost} = $price * ( 1 - $c );
241 $orderinfo{rrp} = $price;
243 } else {
244 if ( $c_discount ) {
245 $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
246 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
247 } else {
248 $orderinfo{rrp} = $price / ( 1 + $orderinfo{gstrate} );
249 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
252 $orderinfo{listprice} = $orderinfo{rrp} / $cur->{rate};
253 $orderinfo{unitprice} = $orderinfo{ecost};
254 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
255 } else {
256 $orderinfo{listprice} = 0;
259 # remove uncertainprice flag if we have found a price in the MARC record
260 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
261 my $order = Koha::Acquisition::Order->new( \%orderinfo )->insert;
263 # 4th, add items if applicable
264 # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
265 # this is not optimised, but it's working !
266 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
267 my @tags = $input->param('tag');
268 my @subfields = $input->param('subfield');
269 my @field_values = $input->param('field_value');
270 my @serials = $input->param('serial');
271 my @ind_tag = $input->param('ind_tag');
272 my @indicator = $input->param('indicator');
273 my $item;
274 push @{ $item->{tags} }, $tags[0];
275 push @{ $item->{subfields} }, $subfields[0];
276 push @{ $item->{field_values} }, $field_values[0];
277 push @{ $item->{ind_tag} }, $ind_tag[0];
278 push @{ $item->{indicator} }, $indicator[0];
279 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@ind_tag, \@indicator );
280 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
281 for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
282 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
283 $order->add_item( $itemnumber );
285 } else {
286 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
289 # go to basket page
290 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'});
291 exit;
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);
301 # build budget list
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 ) {
307 next;
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,
319 @{$budget_loop} =
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 {
328 my ($template) = @_;
329 my $batches = GetImportBatchRangeDesc();
331 my @list = ();
332 foreach my $batch (@$batches) {
333 if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ ) {
334 # check if there is at least 1 line still staged
335 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, undef, $batch->{import_status}, { order_by_direction => 'ASC' });
336 if (scalar @$stagedList) {
337 push @list, {
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'},
346 } else {
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});
362 my @list = ();
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);
373 my %cellrecord = (
374 import_record_id => $biblio->{'import_record_id'},
375 citation => $citation,
376 import => 1,
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};
393 my $budget_id;
394 if($budget_code) {
395 my $biblio_budget = GetBudgetByCode($budget_code);
396 if($biblio_budget) {
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);
426 sub batch_info {
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
471 my $yaml = eval {
472 YAML::Load($syspref);
474 if ( $@ ) {
475 warn "Unable to parse MarcFieldsToOrder syspref : $@";
476 return ();
478 my $r;
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};
491 return $r;