Revert "Bug 18307 - Branchname is no longer displayed in subscription tab view"
[koha.git] / acqui / addorderiso2709.pl
blob6363d6eb46d9a23f8234ee73c7682d147c5c5e3d
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::Branch; # GetBranches
43 use C4::Members;
45 use Koha::Number::Price;
46 use Koha::Acquisition::Currencies;
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 $allmatch = $input->param('allmatch');
64 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
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 chosen 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 @currencies = Koha::Acquisition::Currencies->search;
95 $template->param("batch_details" => 1,
96 "basketno" => $cgiparams->{'basketno'},
97 currencies => \@currencies,
98 bookseller => $bookseller,
99 "allmatch" => $allmatch,
101 import_biblios_list($template, $cgiparams->{'import_batch_id'});
102 my $basket = GetBasket($cgiparams->{basketno});
103 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$basket->{is_standing} ) {
104 # prepare empty item form
105 my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
107 # warn "==> ".Data::Dumper::Dumper($cell);
108 unless ($cell) {
109 $cell = PrepareItemrecordDisplay( '', '', '', '' );
110 $template->param( 'NoACQframework' => 1 );
112 my @itemloop;
113 push @itemloop, $cell;
115 $template->param( items => \@itemloop );
118 # 3rd step = import the records
120 } elsif ( $op eq 'import_records' ) {
121 #import selected lines
122 $template->param('basketno' => $cgiparams->{'basketno'});
123 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
124 my $budgets = GetBudgets();
125 if (scalar @$budgets == 0){
126 die "No budgets defined, can't continue";
128 my $budget_id = @$budgets[0]->{'budget_id'};
129 #get all records from a batch, and check their import status to see if they are checked.
130 #(default values: quantity 1, uncertainprice yes, first budget)
132 # retrieve the file you want to import
133 my $import_batch_id = $cgiparams->{'import_batch_id'};
134 my $biblios = GetImportRecordsRange($import_batch_id);
135 my $duplinbatch;
136 my $imported = 0;
137 my @import_record_id_selected = $input->multi_param("import_record_id");
138 my @quantities = $input->multi_param('quantity');
139 my @prices = $input->multi_param('price');
140 my @budgets_id = $input->multi_param('budget_id');
141 my @discount = $input->multi_param('discount');
142 my @sort1 = $input->multi_param('sort1');
143 my @sort2 = $input->multi_param('sort2');
144 my $matcher_id = $input->param('matcher_id');
145 my $active_currency = Koha::Acquisition::Currencies->get_active;
146 for my $biblio (@$biblios){
147 # Check if this import_record_id was selected
148 next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
149 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
150 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
151 my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
152 my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
153 my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
154 my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
155 my $c_discount = shift ( @discount);
156 $c_discount = $c_discount / 100 if $c_discount > 1;
157 my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
158 my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
160 # 1st insert the biblio, or find it through matcher
161 unless ( $biblionumber ) {
162 if ($matcher_id) {
163 if ( $matcher_id eq '_TITLE_AUTHOR_' ) {
164 $duplinbatch = $import_batch_id if FindDuplicate($marcrecord);
166 else {
167 my $matcher = C4::Matcher->fetch($matcher_id);
168 my @matches = $matcher->get_matches( $marcrecord, my $max_matches = 1 );
169 $duplinbatch = $import_batch_id if @matches;
172 next if $duplinbatch;
175 # add the biblio
176 my $bibitemnum;
178 # remove ISBN -
179 my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
180 if ( $marcrecord->field($isbnfield) ) {
181 foreach my $field ( $marcrecord->field($isbnfield) ) {
182 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
183 my $newisbn = $field->subfield($isbnsubfield);
184 $newisbn =~ s/-//g;
185 $field->update( $isbnsubfield => $newisbn );
189 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
190 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
191 # 2nd add authorities if applicable
192 if (C4::Context->preference("BiblioAddsAuthorities")){
193 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
195 } else {
196 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
198 # 3rd add order
199 my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
200 # get quantity in the MARC record (1 if none)
201 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
202 my %orderinfo = (
203 biblionumber => $biblionumber,
204 basketno => $cgiparams->{'basketno'},
205 quantity => $c_quantity,
206 branchcode => $patron->{branchcode},
207 budget_id => $c_budget_id,
208 uncertainprice => 1,
209 sort1 => $c_sort1,
210 sort2 => $c_sort2,
211 order_internalnote => $cgiparams->{'all_order_internalnote'},
212 order_vendornote => $cgiparams->{'all_order_vendornote'},
213 currency => $cgiparams->{'all_currency'},
215 # get the price if there is one.
216 my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
217 if ($price){
218 # in France, the cents separator is the , but sometimes, ppl use a .
219 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
220 $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
221 $price = Koha::Number::Price->new($price)->unformat;
222 $orderinfo{gstrate} = $bookseller->{gstrate};
223 my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
224 if ( $bookseller->{listincgst} ) {
225 if ( $c_discount ) {
226 $orderinfo{ecost} = $price;
227 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
228 } else {
229 $orderinfo{ecost} = $price * ( 1 - $c );
230 $orderinfo{rrp} = $price;
232 } else {
233 if ( $c_discount ) {
234 $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
235 $orderinfo{rrp} = $orderinfo{ecost} / ( 1 - $c );
236 } else {
237 $orderinfo{rrp} = $price / ( 1 + $orderinfo{gstrate} );
238 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
241 $orderinfo{listprice} = $orderinfo{rrp} / $active_currency->rate;
242 $orderinfo{unitprice} = $orderinfo{ecost};
243 $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
244 } else {
245 $orderinfo{listprice} = 0;
248 # remove uncertainprice flag if we have found a price in the MARC record
249 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
250 my $order = Koha::Acquisition::Order->new( \%orderinfo )->insert;
252 # 4th, add items if applicable
253 # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
254 # this is not optimised, but it's working !
255 my $basket = GetBasket($cgiparams->{basketno});
256 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$basket->{is_standing} ) {
257 my @tags = $input->multi_param('tag');
258 my @subfields = $input->multi_param('subfield');
259 my @field_values = $input->multi_param('field_value');
260 my @serials = $input->multi_param('serial');
261 my @ind_tag = $input->multi_param('ind_tag');
262 my @indicator = $input->multi_param('indicator');
263 my $item;
264 push @{ $item->{tags} }, $tags[0];
265 push @{ $item->{subfields} }, $subfields[0];
266 push @{ $item->{field_values} }, $field_values[0];
267 push @{ $item->{ind_tag} }, $ind_tag[0];
268 push @{ $item->{indicator} }, $indicator[0];
269 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@indicator, \@ind_tag );
270 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
271 for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
272 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
273 $order->add_item( $itemnumber );
275 } else {
276 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
278 $imported++;
280 # go to basket page
281 if ( $imported ) {
282 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
283 } else {
284 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");
286 exit;
289 my $budgets = GetBudgets();
290 my $budget_id = @$budgets[0]->{'budget_id'};
291 # build bookfund list
292 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
293 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
294 my $budget = GetBudget($budget_id);
296 # build budget list
297 my $budget_loop = [];
298 my $budgets_hierarchy = GetBudgetHierarchy;
299 foreach my $r ( @{$budgets_hierarchy} ) {
300 next unless (CanUserUseBudget($borrower, $r, $userflags));
301 if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
302 next;
304 push @{$budget_loop},
305 { b_id => $r->{budget_id},
306 b_txt => $r->{budget_name},
307 b_sort1_authcat => $r->{'sort1_authcat'},
308 b_sort2_authcat => $r->{'sort2_authcat'},
309 b_active => $r->{budget_period_active},
310 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
314 @{$budget_loop} =
315 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
317 $template->param( budget_loop => $budget_loop,);
319 output_html_with_http_headers $input, $cookie, $template->output;
322 sub import_batches_list {
323 my ($template) = @_;
324 my $batches = GetImportBatchRangeDesc();
326 my @list = ();
327 foreach my $batch (@$batches) {
328 if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
329 # check if there is at least 1 line still staged
330 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
331 if (scalar @$stagedList) {
332 push @list, {
333 import_batch_id => $batch->{'import_batch_id'},
334 num_records => $batch->{'num_records'},
335 num_items => $batch->{'num_items'},
336 staged_date => $batch->{'upload_timestamp'},
337 import_status => $batch->{'import_status'},
338 file_name => $batch->{'file_name'},
339 comments => $batch->{'comments'},
341 } else {
342 # if there are no more line to includes, set the status to imported
343 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
347 $template->param(batch_list => \@list);
348 my $num_batches = GetNumberOfNonZ3950ImportBatches();
349 $template->param(num_results => $num_batches);
352 sub import_biblios_list {
353 my ($template, $import_batch_id) = @_;
354 my $batch = GetImportBatch($import_batch_id,'staged');
355 return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
356 my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
357 my @list = ();
359 foreach my $biblio (@$biblios) {
360 my $citation = $biblio->{'title'};
361 $citation .= " $biblio->{'author'}" if $biblio->{'author'};
362 $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
363 $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
364 $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
365 $citation .= $biblio->{'issn'} if $biblio->{'issn'};
366 $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
367 my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
368 my %cellrecord = (
369 import_record_id => $biblio->{'import_record_id'},
370 citation => $citation,
371 import => 1,
372 status => $biblio->{'status'},
373 record_sequence => $biblio->{'record_sequence'},
374 overlay_status => $biblio->{'overlay_status'},
375 match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
376 match_citation => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
377 match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
379 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
380 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
381 my $infos = get_infos_syspref($marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2']);
382 my $price = $infos->{price};
383 my $quantity = $infos->{quantity};
384 my $budget_code = $infos->{budget_code};
385 my $discount = $infos->{discount};
386 my $sort1 = $infos->{sort1};
387 my $sort2 = $infos->{sort2};
388 my $budget_id;
389 if($budget_code) {
390 my $biblio_budget = GetBudgetByCode($budget_code);
391 if($biblio_budget) {
392 $budget_id = $biblio_budget->{budget_id};
395 $cellrecord{price} = $price || '';
396 $cellrecord{quantity} = $quantity || '';
397 $cellrecord{budget_id} = $budget_id || '';
398 $cellrecord{discount} = $discount || '';
399 $cellrecord{sort1} = $sort1 || '';
400 $cellrecord{sort2} = $sort2 || '';
402 push @list, \%cellrecord;
404 my $num_records = $batch->{'num_records'};
405 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
406 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
407 my $item_action = GetImportBatchItemAction($import_batch_id);
408 $template->param(biblio_list => \@list,
409 num_results => $num_records,
410 import_batch_id => $import_batch_id,
411 "overlay_action_${overlay_action}" => 1,
412 overlay_action => $overlay_action,
413 "nomatch_action_${nomatch_action}" => 1,
414 nomatch_action => $nomatch_action,
415 "item_action_${item_action}" => 1,
416 item_action => $item_action
418 batch_info($template, $batch);
421 sub batch_info {
422 my ($template, $batch) = @_;
423 $template->param(batch_info => 1,
424 file_name => $batch->{'file_name'},
425 comments => $batch->{'comments'},
426 import_status => $batch->{'import_status'},
427 upload_timestamp => $batch->{'upload_timestamp'},
428 num_records => $batch->{'num_records'},
429 num_items => $batch->{'num_items'});
430 if ($batch->{'num_records'} > 0) {
431 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
432 $template->param(can_commit => 1);
434 if ($batch->{'import_status'} eq 'imported') {
435 $template->param(can_revert => 1);
438 if (defined $batch->{'matcher_id'}) {
439 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
440 if (defined $matcher) {
441 $template->param('current_matcher_id' => $batch->{'matcher_id'},
442 'current_matcher_code' => $matcher->code(),
443 'current_matcher_description' => $matcher->description());
446 add_matcher_list($batch->{'matcher_id'}, $template);
449 sub add_matcher_list {
450 my ($current_matcher_id, $template) = @_;
451 my @matchers = C4::Matcher::GetMatcherList();
452 if (defined $current_matcher_id) {
453 for (my $i = 0; $i <= $#matchers; $i++) {
454 if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
455 $matchers[$i]->{'selected'} = 1;
459 $template->param(available_matchers => \@matchers);
462 sub get_infos_syspref {
463 my ($record, $field_list) = @_;
464 my $syspref = C4::Context->preference('MarcFieldsToOrder');
465 $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
466 my $yaml = eval {
467 YAML::Load($syspref);
469 if ( $@ ) {
470 warn "Unable to parse MarcFieldsToOrder syspref : $@";
471 return ();
473 my $r;
474 for my $field_name ( @$field_list ) {
475 next unless exists $yaml->{$field_name};
476 my @fields = split /\|/, $yaml->{$field_name};
477 for my $field ( @fields ) {
478 my ( $f, $sf ) = split /\$/, $field;
479 next unless $f and $sf;
480 if ( my $v = $record->subfield( $f, $sf ) ) {
481 $r->{$field_name} = $v;
483 last if $yaml->{$field};
486 return $r;