Bug 13381 - RDA: 245 field changes in XSLT
[koha.git] / acqui / addorderiso2709.pl
bloba71e15a4a98610670fa987d823c9381d2a4c45d3
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::Input;
32 use C4::Output;
33 use C4::ImportBatch;
34 use C4::Matcher;
35 use C4::Search qw/FindDuplicate/;
36 use C4::Acquisition;
37 use C4::Biblio;
38 use C4::Items;
39 use C4::Koha;
40 use C4::Budgets;
41 use C4::Acquisition;
42 use C4::Suggestions; # GetSuggestion
43 use C4::Branch; # GetBranches
44 use C4::Members;
46 use Koha::Number::Price;
47 use Koha::Acquisition::Order;
48 use Koha::Acquisition::Bookseller;
50 my $input = new CGI;
51 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
52 template_name => "acqui/addorderiso2709.tt",
53 query => $input,
54 type => "intranet",
55 authnotrequired => 0,
56 flagsrequired => { acquisition => 'order_manage' },
57 debug => 1,
58 });
60 my $cgiparams = $input->Vars;
61 my $op = $cgiparams->{'op'} || '';
62 my $booksellerid = $input->param('booksellerid');
63 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
64 my $data;
66 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
67 booksellerid => $booksellerid,
68 booksellername => $bookseller->{name},
71 if ($cgiparams->{'import_batch_id'} && $op eq ""){
72 $op = "batch_details";
75 #Needed parameters:
76 if (! $cgiparams->{'basketno'}){
77 die "Basketnumber required to order from iso2709 file import";
81 # 1st step = choose the file to import into acquisition
83 if ($op eq ""){
84 $template->param("basketno" => $cgiparams->{'basketno'});
85 #display batches
86 import_batches_list($template);
88 # 2nd step = display the content of the choosen file
90 } elsif ($op eq "batch_details"){
91 #display lines inside the selected batch
92 # get currencies (for change rates calcs if needed)
93 my $active_currency = GetCurrency();
94 my $default_currency;
95 if (! $data->{currency} ) { # New order no currency set
96 if ( $bookseller->{listprice} ) {
97 $default_currency = $bookseller->{listprice};
99 else {
100 $default_currency = $active_currency->{currency};
103 my @rates = GetCurrencies();
105 # ## @rates
107 my @loop_currency = ();
108 for my $curr ( @rates ) {
109 my $selected;
110 if ($data->{currency} ) {
111 $selected = $curr->{currency} eq $data->{currency};
113 else {
114 $selected = $curr->{currency} eq $default_currency;
116 push @loop_currency, {
117 currcode => $curr->{currency},
118 rate => $curr->{rate},
119 selected => $selected,
123 $template->param("batch_details" => 1,
124 "basketno" => $cgiparams->{'basketno'},
125 loop_currencies => \@loop_currency,
127 import_biblios_list($template, $cgiparams->{'import_batch_id'});
128 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
129 # prepare empty item form
130 my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
132 # warn "==> ".Data::Dumper::Dumper($cell);
133 unless ($cell) {
134 $cell = PrepareItemrecordDisplay( '', '', '', '' );
135 $template->param( 'NoACQframework' => 1 );
137 my @itemloop;
138 push @itemloop, $cell;
140 $template->param( items => \@itemloop );
143 # 3rd step = import the records
145 } elsif ( $op eq 'import_records' ) {
146 #import selected lines
147 $template->param('basketno' => $cgiparams->{'basketno'});
148 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
149 my $budgets = GetBudgets();
150 if (scalar @$budgets == 0){
151 die "No budgets defined, can't continue";
153 my $budget_id = @$budgets[0]->{'budget_id'};
154 #get all records from a batch, and check their import status to see if they are checked.
155 #(default values: quantity 1, uncertainprice yes, first budget)
157 # retrieve the file you want to import
158 my $import_batch_id = $cgiparams->{'import_batch_id'};
159 my $biblios = GetImportRecordsRange($import_batch_id);
160 my @import_record_id_selected = $input->param("import_record_id");
161 my @quantities = $input->param('quantity');
162 my @prices = $input->param('price');
163 my @budgets_id = $input->param('budget_id');
164 my @discount = $input->param('discount');
165 my @sort1 = $input->param('sort1');
166 my @sort2 = $input->param('sort2');
167 my $cur = GetCurrency();
168 for my $biblio (@$biblios){
169 # Check if this import_record_id was selected
170 next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
171 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
172 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
173 my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
174 my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
175 my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
176 my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
177 my $c_discount = shift ( @discount);
178 $c_discount = $c_discount / 100 if $c_discount > 1;
179 my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
180 my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
182 # 1st insert the biblio, or find it through matcher
183 unless ( $biblionumber ) {
184 # add the biblio
185 my $bibitemnum;
187 # remove ISBN -
188 my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
189 if ( $marcrecord->field($isbnfield) ) {
190 foreach my $field ( $marcrecord->field($isbnfield) ) {
191 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
192 my $newisbn = $field->subfield($isbnsubfield);
193 $newisbn =~ s/-//g;
194 $field->update( $isbnsubfield => $newisbn );
198 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
199 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
200 # 2nd add authorities if applicable
201 if (C4::Context->preference("BiblioAddsAuthorities")){
202 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
204 } else {
205 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
207 # 3rd add order
208 my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
209 my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
210 # get quantity in the MARC record (1 if none)
211 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
212 my %orderinfo = (
213 biblionumber => $biblionumber,
214 basketno => $cgiparams->{'basketno'},
215 quantity => $c_quantity,
216 branchcode => $patron->{branchcode},
217 budget_id => $c_budget_id,
218 uncertainprice => 1,
219 sort1 => $c_sort1,
220 sort2 => $c_sort2,
221 order_internalnote => $cgiparams->{'all_order_internalnote'},
222 order_vendornote => $cgiparams->{'all_order_vendornote'},
223 currency => $cgiparams->{'all_currency'},
225 # get the price if there is one.
226 my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
227 if ($price){
228 # in France, the cents separator is the , but sometimes, ppl use a .
229 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
230 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
231 $price = Koha::Number::Price->new($price)->unformat;
232 $orderinfo{gstrate} = $bookseller->{gstrate};
233 my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
234 if ( $bookseller->{listincgst} ) {
235 if ( $c_discount ) {
236 $orderinfo{ecost} = $price;
237 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
238 } else {
239 $orderinfo{ecost} = $price * ( 1 - $c );
240 $orderinfo{rrp} = $price;
242 } else {
243 if ( $c_discount ) {
244 $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
245 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
246 } else {
247 $orderinfo{rrp} = $price / ( 1 + $orderinfo{gstrate} );
248 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
251 $orderinfo{listprice} = $orderinfo{rrp} / $cur->{rate};
252 $orderinfo{unitprice} = $orderinfo{ecost};
253 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
254 } else {
255 $orderinfo{listprice} = 0;
258 # remove uncertainprice flag if we have found a price in the MARC record
259 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
260 my $order = Koha::Acquisition::Order->new( \%orderinfo )->insert;
262 # 4th, add items if applicable
263 # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
264 # this is not optimised, but it's working !
265 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
266 my @tags = $input->param('tag');
267 my @subfields = $input->param('subfield');
268 my @field_values = $input->param('field_value');
269 my @serials = $input->param('serial');
270 my @ind_tag = $input->param('ind_tag');
271 my @indicator = $input->param('indicator');
272 my $item;
273 push @{ $item->{tags} }, $tags[0];
274 push @{ $item->{subfields} }, $subfields[0];
275 push @{ $item->{field_values} }, $field_values[0];
276 push @{ $item->{ind_tag} }, $ind_tag[0];
277 push @{ $item->{indicator} }, $indicator[0];
278 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@ind_tag, \@indicator );
279 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
280 for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
281 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
282 $order->add_item( $itemnumber );
284 } else {
285 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
288 # go to basket page
289 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'});
290 exit;
293 my $budgets = GetBudgets();
294 my $budget_id = @$budgets[0]->{'budget_id'};
295 # build bookfund list
296 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
297 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
298 my $budget = GetBudget($budget_id);
300 # build budget list
301 my $budget_loop = [];
302 my $budgets_hierarchy = GetBudgetHierarchy;
303 foreach my $r ( @{$budgets_hierarchy} ) {
304 next unless (CanUserUseBudget($borrower, $r, $userflags));
305 if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
306 next;
308 push @{$budget_loop},
309 { b_id => $r->{budget_id},
310 b_txt => $r->{budget_name},
311 b_sort1_authcat => $r->{'sort1_authcat'},
312 b_sort2_authcat => $r->{'sort2_authcat'},
313 b_active => $r->{budget_period_active},
314 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
318 @{$budget_loop} =
319 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
321 $template->param( budget_loop => $budget_loop,);
323 output_html_with_http_headers $input, $cookie, $template->output;
326 sub import_batches_list {
327 my ($template) = @_;
328 my $batches = GetImportBatchRangeDesc();
330 my @list = ();
331 foreach my $batch (@$batches) {
332 if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ ) {
333 # check if there is at least 1 line still staged
334 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
335 if (scalar @$stagedList) {
336 push @list, {
337 import_batch_id => $batch->{'import_batch_id'},
338 num_records => $batch->{'num_records'},
339 num_items => $batch->{'num_items'},
340 staged_date => $batch->{'upload_timestamp'},
341 import_status => $batch->{'import_status'},
342 file_name => $batch->{'file_name'},
343 comments => $batch->{'comments'},
345 } else {
346 # if there are no more line to includes, set the status to imported
347 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
351 $template->param(batch_list => \@list);
352 my $num_batches = GetNumberOfNonZ3950ImportBatches();
353 $template->param(num_results => $num_batches);
356 sub import_biblios_list {
357 my ($template, $import_batch_id) = @_;
358 my $batch = GetImportBatch($import_batch_id,'staged');
359 return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
360 my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
361 my @list = ();
363 foreach my $biblio (@$biblios) {
364 my $citation = $biblio->{'title'};
365 $citation .= " $biblio->{'author'}" if $biblio->{'author'};
366 $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
367 $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
368 $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
369 $citation .= $biblio->{'issn'} if $biblio->{'issn'};
370 $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
371 my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
372 my %cellrecord = (
373 import_record_id => $biblio->{'import_record_id'},
374 citation => $citation,
375 import => 1,
376 status => $biblio->{'status'},
377 record_sequence => $biblio->{'record_sequence'},
378 overlay_status => $biblio->{'overlay_status'},
379 match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
380 match_citation => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
381 match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
383 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
384 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
385 my $infos = get_infos_syspref($marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2']);
386 my $price = $infos->{price};
387 my $quantity = $infos->{quantity};
388 my $budget_code = $infos->{budget_code};
389 my $discount = $infos->{discount};
390 my $sort1 = $infos->{sort1};
391 my $sort2 = $infos->{sort2};
392 my $budget_id;
393 if($budget_code) {
394 my $biblio_budget = GetBudgetByCode($budget_code);
395 if($biblio_budget) {
396 $budget_id = $biblio_budget->{budget_id};
399 $cellrecord{price} = $price || '';
400 $cellrecord{quantity} = $quantity || '';
401 $cellrecord{budget_id} = $budget_id || '';
402 $cellrecord{discount} = $discount || '';
403 $cellrecord{sort1} = $sort1 || '';
404 $cellrecord{sort2} = $sort2 || '';
406 push @list, \%cellrecord;
408 my $num_records = $batch->{'num_records'};
409 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
410 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
411 my $item_action = GetImportBatchItemAction($import_batch_id);
412 $template->param(biblio_list => \@list,
413 num_results => $num_records,
414 import_batch_id => $import_batch_id,
415 "overlay_action_${overlay_action}" => 1,
416 overlay_action => $overlay_action,
417 "nomatch_action_${nomatch_action}" => 1,
418 nomatch_action => $nomatch_action,
419 "item_action_${item_action}" => 1,
420 item_action => $item_action
422 batch_info($template, $batch);
425 sub batch_info {
426 my ($template, $batch) = @_;
427 $template->param(batch_info => 1,
428 file_name => $batch->{'file_name'},
429 comments => $batch->{'comments'},
430 import_status => $batch->{'import_status'},
431 upload_timestamp => $batch->{'upload_timestamp'},
432 num_records => $batch->{'num_records'},
433 num_items => $batch->{'num_items'});
434 if ($batch->{'num_records'} > 0) {
435 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
436 $template->param(can_commit => 1);
438 if ($batch->{'import_status'} eq 'imported') {
439 $template->param(can_revert => 1);
442 if (defined $batch->{'matcher_id'}) {
443 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
444 if (defined $matcher) {
445 $template->param('current_matcher_id' => $batch->{'matcher_id'},
446 'current_matcher_code' => $matcher->code(),
447 'current_matcher_description' => $matcher->description());
450 add_matcher_list($batch->{'matcher_id'}, $template);
453 sub add_matcher_list {
454 my ($current_matcher_id, $template) = @_;
455 my @matchers = C4::Matcher::GetMatcherList();
456 if (defined $current_matcher_id) {
457 for (my $i = 0; $i <= $#matchers; $i++) {
458 if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
459 $matchers[$i]->{'selected'} = 1;
463 $template->param(available_matchers => \@matchers);
466 sub get_infos_syspref {
467 my ($record, $field_list) = @_;
468 my $syspref = C4::Context->preference('MarcFieldsToOrder');
469 $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
470 my $yaml = eval {
471 YAML::Load($syspref);
473 if ( $@ ) {
474 warn "Unable to parse MarcFieldsToOrder syspref : $@";
475 return ();
477 my $r;
478 for my $field_name ( @$field_list ) {
479 next unless exists $yaml->{$field_name};
480 my @fields = split /\|/, $yaml->{$field_name};
481 for my $field ( @fields ) {
482 my ( $f, $sf ) = split /\$/, $field;
483 next unless $f and $sf;
484 if ( my $v = $record->subfield( $f, $sf ) ) {
485 $r->{$field_name} = $v;
487 last if $yaml->{$field};
490 return $r;