Bug 17744: Remove the oai_dc:dcCollection wrapper in OAI responses
[koha.git] / acqui / addorderiso2709.pl
blob74ea8e2a1a7c4828737f8260db5ce4704e7e57bd
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
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>.
24 use Modern::Perl;
25 use CGI qw ( -utf8 );
26 use Carp;
27 use YAML qw/Load/;
29 use C4::Context;
30 use C4::Auth;
31 use C4::Output;
32 use C4::ImportBatch;
33 use C4::Matcher;
34 use C4::Search qw/FindDuplicate/;
35 use C4::Acquisition;
36 use C4::Biblio;
37 use C4::Items;
38 use C4::Koha;
39 use C4::Budgets;
40 use C4::Acquisition;
41 use C4::Suggestions; # GetSuggestion
42 use C4::Members;
44 use Koha::Number::Price;
45 use Koha::Acquisition::Currencies;
46 use Koha::Acquisition::Order;
47 use Koha::Acquisition::Bookseller;
49 my $input = new CGI;
50 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
51 template_name => "acqui/addorderiso2709.tt",
52 query => $input,
53 type => "intranet",
54 authnotrequired => 0,
55 flagsrequired => { acquisition => 'order_manage' },
56 debug => 1,
57 });
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 });
65 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
66 booksellerid => $booksellerid,
67 booksellername => $bookseller->{name},
70 if ($cgiparams->{'import_batch_id'} && $op eq ""){
71 $op = "batch_details";
74 #Needed parameters:
75 if (! $cgiparams->{'basketno'}){
76 die "Basketnumber required to order from iso2709 file import";
80 # 1st step = choose the file to import into acquisition
82 if ($op eq ""){
83 $template->param("basketno" => $cgiparams->{'basketno'});
84 #display batches
85 import_batches_list($template);
87 # 2nd step = display the content of the chosen file
89 } elsif ($op eq "batch_details"){
90 #display lines inside the selected batch
91 # get currencies (for change rates calcs if needed)
92 my @currencies = Koha::Acquisition::Currencies->search;
94 $template->param("batch_details" => 1,
95 "basketno" => $cgiparams->{'basketno'},
96 currencies => \@currencies,
97 bookseller => $bookseller,
98 "allmatch" => $allmatch,
100 import_biblios_list($template, $cgiparams->{'import_batch_id'});
101 my $basket = GetBasket($cgiparams->{basketno});
102 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$basket->{is_standing} ) {
103 # prepare empty item form
104 my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
106 # warn "==> ".Data::Dumper::Dumper($cell);
107 unless ($cell) {
108 $cell = PrepareItemrecordDisplay( '', '', '', '' );
109 $template->param( 'NoACQframework' => 1 );
111 my @itemloop;
112 push @itemloop, $cell;
114 $template->param( items => \@itemloop );
117 # 3rd step = import the records
119 } elsif ( $op eq 'import_records' ) {
120 #import selected lines
121 $template->param('basketno' => $cgiparams->{'basketno'});
122 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
123 my $budgets = GetBudgets();
124 if (scalar @$budgets == 0){
125 die "No budgets defined, can't continue";
127 my $budget_id = @$budgets[0]->{'budget_id'};
128 #get all records from a batch, and check their import status to see if they are checked.
129 #(default values: quantity 1, uncertainprice yes, first budget)
131 # retrieve the file you want to import
132 my $import_batch_id = $cgiparams->{'import_batch_id'};
133 my $biblios = GetImportRecordsRange($import_batch_id);
134 my $duplinbatch;
135 my $imported = 0;
136 my @import_record_id_selected = $input->multi_param("import_record_id");
137 my @quantities = $input->multi_param('quantity');
138 my @prices = $input->multi_param('price');
139 my @budgets_id = $input->multi_param('budget_id');
140 my @discount = $input->multi_param('discount');
141 my @sort1 = $input->multi_param('sort1');
142 my @sort2 = $input->multi_param('sort2');
143 my $matcher_id = $input->param('matcher_id');
144 my $active_currency = Koha::Acquisition::Currencies->get_active;
145 for my $biblio (@$biblios){
146 # Check if this import_record_id was selected
147 next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
148 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
149 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
150 my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
151 my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
152 my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
153 my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
154 my $c_discount = shift ( @discount);
155 $c_discount = $c_discount / 100 if $c_discount > 1;
156 my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
157 my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
159 # 1st insert the biblio, or find it through matcher
160 unless ( $biblionumber ) {
161 if ($matcher_id) {
162 if ( $matcher_id eq '_TITLE_AUTHOR_' ) {
163 $duplinbatch = $import_batch_id if FindDuplicate($marcrecord);
165 else {
166 my $matcher = C4::Matcher->fetch($matcher_id);
167 my @matches = $matcher->get_matches( $marcrecord, my $max_matches = 1 );
168 $duplinbatch = $import_batch_id if @matches;
171 next if $duplinbatch;
174 # add the biblio
175 my $bibitemnum;
177 # remove ISBN -
178 my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
179 if ( $marcrecord->field($isbnfield) ) {
180 foreach my $field ( $marcrecord->field($isbnfield) ) {
181 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
182 my $newisbn = $field->subfield($isbnsubfield);
183 $newisbn =~ s/-//g;
184 $field->update( $isbnsubfield => $newisbn );
188 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
189 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
190 # 2nd add authorities if applicable
191 if (C4::Context->preference("BiblioAddsAuthorities")){
192 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
194 } else {
195 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
197 # 3rd add order
198 my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
199 # get quantity in the MARC record (1 if none)
200 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
201 my %orderinfo = (
202 biblionumber => $biblionumber,
203 basketno => $cgiparams->{'basketno'},
204 quantity => $c_quantity,
205 branchcode => $patron->{branchcode},
206 budget_id => $c_budget_id,
207 uncertainprice => 1,
208 sort1 => $c_sort1,
209 sort2 => $c_sort2,
210 order_internalnote => $cgiparams->{'all_order_internalnote'},
211 order_vendornote => $cgiparams->{'all_order_vendornote'},
212 currency => $cgiparams->{'all_currency'},
214 # get the price if there is one.
215 my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
216 if ($price){
217 # in France, the cents separator is the , but sometimes, ppl use a .
218 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
219 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
220 $price = Koha::Number::Price->new($price)->unformat;
221 $orderinfo{tax_rate} = $bookseller->{tax_rate};
222 my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
223 if ( $bookseller->{listincgst} ) {
224 if ( $c_discount ) {
225 $orderinfo{ecost} = $price;
226 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
227 } else {
228 $orderinfo{ecost} = $price * ( 1 - $c );
229 $orderinfo{rrp} = $price;
231 } else {
232 if ( $c_discount ) {
233 $orderinfo{ecost} = $price / ( 1 + $orderinfo{tax_rate} );
234 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
235 } else {
236 $orderinfo{rrp} = $price / ( 1 + $orderinfo{tax_rate} );
237 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
240 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
241 $orderinfo{unitprice} = $orderinfo{ecost};
242 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
243 } else {
244 $orderinfo{listprice} = 0;
247 # remove uncertainprice flag if we have found a price in the MARC record
248 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
250 %orderinfo = %{
251 C4::Acquisition::populate_order_with_prices(
253 order => \%orderinfo,
254 booksellerid => $booksellerid,
255 ordering => 1,
256 receiving => 1,
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 my $basket = GetBasket($cgiparams->{basketno});
267 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$basket->{is_standing} ) {
268 my @tags = $input->multi_param('tag');
269 my @subfields = $input->multi_param('subfield');
270 my @field_values = $input->multi_param('field_value');
271 my @serials = $input->multi_param('serial');
272 my @ind_tag = $input->multi_param('ind_tag');
273 my @indicator = $input->multi_param('indicator');
274 my $item;
275 push @{ $item->{tags} }, $tags[0];
276 push @{ $item->{subfields} }, $subfields[0];
277 push @{ $item->{field_values} }, $field_values[0];
278 push @{ $item->{ind_tag} }, $ind_tag[0];
279 push @{ $item->{indicator} }, $indicator[0];
280 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@indicator, \@ind_tag );
281 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
282 for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
283 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
284 $order->add_item( $itemnumber );
286 } else {
287 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
289 $imported++;
291 # go to basket page
292 if ( $imported ) {
293 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
294 } else {
295 print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&amp;basketno=".$cgiparams->{'basketno'}."&amp;booksellerid=$booksellerid&amp;allmatch=1");
297 exit;
300 my $budgets = GetBudgets();
301 my $budget_id = @$budgets[0]->{'budget_id'};
302 # build bookfund list
303 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
304 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
305 my $budget = GetBudget($budget_id);
307 # build budget list
308 my $budget_loop = [];
309 my $budgets_hierarchy = GetBudgetHierarchy;
310 foreach my $r ( @{$budgets_hierarchy} ) {
311 next unless (CanUserUseBudget($borrower, $r, $userflags));
312 if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
313 next;
315 push @{$budget_loop},
316 { b_id => $r->{budget_id},
317 b_txt => $r->{budget_name},
318 b_sort1_authcat => $r->{'sort1_authcat'},
319 b_sort2_authcat => $r->{'sort2_authcat'},
320 b_active => $r->{budget_period_active},
321 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
325 @{$budget_loop} =
326 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
328 $template->param( budget_loop => $budget_loop,);
330 output_html_with_http_headers $input, $cookie, $template->output;
333 sub import_batches_list {
334 my ($template) = @_;
335 my $batches = GetImportBatchRangeDesc();
337 my @list = ();
338 foreach my $batch (@$batches) {
339 if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
340 # check if there is at least 1 line still staged
341 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
342 if (scalar @$stagedList) {
343 push @list, {
344 import_batch_id => $batch->{'import_batch_id'},
345 num_records => $batch->{'num_records'},
346 num_items => $batch->{'num_items'},
347 staged_date => $batch->{'upload_timestamp'},
348 import_status => $batch->{'import_status'},
349 file_name => $batch->{'file_name'},
350 comments => $batch->{'comments'},
352 } else {
353 # if there are no more line to includes, set the status to imported
354 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
358 $template->param(batch_list => \@list);
359 my $num_batches = GetNumberOfNonZ3950ImportBatches();
360 $template->param(num_results => $num_batches);
363 sub import_biblios_list {
364 my ($template, $import_batch_id) = @_;
365 my $batch = GetImportBatch($import_batch_id,'staged');
366 return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
367 my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
368 my @list = ();
370 foreach my $biblio (@$biblios) {
371 my $citation = $biblio->{'title'};
372 $citation .= " $biblio->{'author'}" if $biblio->{'author'};
373 $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
374 $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
375 $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
376 $citation .= $biblio->{'issn'} if $biblio->{'issn'};
377 $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
378 my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
379 my %cellrecord = (
380 import_record_id => $biblio->{'import_record_id'},
381 citation => $citation,
382 import => 1,
383 status => $biblio->{'status'},
384 record_sequence => $biblio->{'record_sequence'},
385 overlay_status => $biblio->{'overlay_status'},
386 match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
387 match_citation => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
388 match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
390 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
391 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
392 my $infos = get_infos_syspref($marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2']);
393 my $price = $infos->{price};
394 my $quantity = $infos->{quantity};
395 my $budget_code = $infos->{budget_code};
396 my $discount = $infos->{discount};
397 my $sort1 = $infos->{sort1};
398 my $sort2 = $infos->{sort2};
399 my $budget_id;
400 if($budget_code) {
401 my $biblio_budget = GetBudgetByCode($budget_code);
402 if($biblio_budget) {
403 $budget_id = $biblio_budget->{budget_id};
406 $cellrecord{price} = $price || '';
407 $cellrecord{quantity} = $quantity || '';
408 $cellrecord{budget_id} = $budget_id || '';
409 $cellrecord{discount} = $discount || '';
410 $cellrecord{sort1} = $sort1 || '';
411 $cellrecord{sort2} = $sort2 || '';
413 push @list, \%cellrecord;
415 my $num_records = $batch->{'num_records'};
416 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
417 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
418 my $item_action = GetImportBatchItemAction($import_batch_id);
419 $template->param(biblio_list => \@list,
420 num_results => $num_records,
421 import_batch_id => $import_batch_id,
422 "overlay_action_${overlay_action}" => 1,
423 overlay_action => $overlay_action,
424 "nomatch_action_${nomatch_action}" => 1,
425 nomatch_action => $nomatch_action,
426 "item_action_${item_action}" => 1,
427 item_action => $item_action
429 batch_info($template, $batch);
432 sub batch_info {
433 my ($template, $batch) = @_;
434 $template->param(batch_info => 1,
435 file_name => $batch->{'file_name'},
436 comments => $batch->{'comments'},
437 import_status => $batch->{'import_status'},
438 upload_timestamp => $batch->{'upload_timestamp'},
439 num_records => $batch->{'num_records'},
440 num_items => $batch->{'num_items'});
441 if ($batch->{'num_records'} > 0) {
442 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
443 $template->param(can_commit => 1);
445 if ($batch->{'import_status'} eq 'imported') {
446 $template->param(can_revert => 1);
449 if (defined $batch->{'matcher_id'}) {
450 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
451 if (defined $matcher) {
452 $template->param('current_matcher_id' => $batch->{'matcher_id'},
453 'current_matcher_code' => $matcher->code(),
454 'current_matcher_description' => $matcher->description());
457 add_matcher_list($batch->{'matcher_id'}, $template);
460 sub add_matcher_list {
461 my ($current_matcher_id, $template) = @_;
462 my @matchers = C4::Matcher::GetMatcherList();
463 if (defined $current_matcher_id) {
464 for (my $i = 0; $i <= $#matchers; $i++) {
465 if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
466 $matchers[$i]->{'selected'} = 1;
470 $template->param(available_matchers => \@matchers);
473 sub get_infos_syspref {
474 my ($record, $field_list) = @_;
475 my $syspref = C4::Context->preference('MarcFieldsToOrder');
476 $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
477 my $yaml = eval {
478 YAML::Load($syspref);
480 if ( $@ ) {
481 warn "Unable to parse MarcFieldsToOrder syspref : $@";
482 return ();
484 my $r;
485 for my $field_name ( @$field_list ) {
486 next unless exists $yaml->{$field_name};
487 my @fields = split /\|/, $yaml->{$field_name};
488 for my $field ( @fields ) {
489 my ( $f, $sf ) = split /\$/, $field;
490 next unless $f and $sf;
491 if ( my $v = $record->subfield( $f, $sf ) ) {
492 $r->{$field_name} = $v;
494 last if $yaml->{$field};
497 return $r;