Bug 9002 - Remove Problematic Logic from Patron Messaging Preferences Form
[koha.git] / acqui / addorderiso2709.pl
blobabfb870fef7de51f021a9f8681a24239a7113313
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 strict;
25 use warnings;
26 use CGI;
27 use Carp;
28 use Number::Format qw(:all);
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.tmpl",
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},
68 my $ordernumber;
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 choosen 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 $active_currency = GetCurrency();
93 my $default_currency;
94 if (! $data->{currency} ) { # New order no currency set
95 if ( $bookseller->{listprice} ) {
96 $default_currency = $bookseller->{listprice};
98 else {
99 $default_currency = $active_currency->{currency};
102 my @rates = GetCurrencies();
104 # ## @rates
106 my @loop_currency = ();
107 for my $curr ( @rates ) {
108 my $selected;
109 if ($data->{currency} ) {
110 $selected = $curr->{currency} eq $data->{currency};
112 else {
113 $selected = $curr->{currency} eq $default_currency;
115 push @loop_currency, {
116 currcode => $curr->{currency},
117 rate => $curr->{rate},
118 selected => $selected,
122 $template->param("batch_details" => 1,
123 "basketno" => $cgiparams->{'basketno'},
124 loop_currencies => \@loop_currency,
126 import_biblios_list($template, $cgiparams->{'import_batch_id'});
127 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber ) {
128 # prepare empty item form
129 my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
131 # warn "==> ".Data::Dumper::Dumper($cell);
132 unless ($cell) {
133 $cell = PrepareItemrecordDisplay( '', '', '', '' );
134 $template->param( 'NoACQframework' => 1 );
136 my @itemloop;
137 push @itemloop, $cell;
139 $template->param( items => \@itemloop );
142 # 3rd step = import the records
144 } elsif ( $op eq 'import_records' ) {
145 my $num=FormatNumber();
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 for my $biblio (@$biblios){
161 # 1st insert the biblio, or find it through matcher
162 my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
163 my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
164 my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
165 my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
167 unless ( $biblionumber ) {
168 # add the biblio
169 my $bibitemnum;
171 # remove ISBN -
172 my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
173 if ( $marcrecord->field($isbnfield) ) {
174 foreach my $field ( $marcrecord->field($isbnfield) ) {
175 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
176 my $newisbn = $field->subfield($isbnsubfield);
177 $newisbn =~ s/-//g;
178 $field->update( $isbnsubfield => $newisbn );
182 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
183 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
184 # 2nd add authorities if applicable
185 if (C4::Context->preference("BiblioAddsAuthorities")){
186 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
188 } else {
189 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
191 # 3rd add order
192 my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
193 my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
194 # get quantity in the MARC record (1 if none)
195 my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
196 my %orderinfo = (
197 "biblionumber", $biblionumber, "basketno", $cgiparams->{'basketno'},
198 "quantity", $quantity, "branchcode", $branch,
199 "budget_id", $budget_id, "uncertainprice", 1,
200 "sort1", $cgiparams->{'sort1'},"sort2", $cgiparams->{'sort2'},
201 "notes", $cgiparams->{'notes'}, "budget_id", $cgiparams->{'budget_id'},
202 "currency",$cgiparams->{'currency'},
205 my $price = GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
207 if ($price){
208 eval {
209 require C4::Acquisition;
210 import C4::Acquisition qw/GetBasket/;
212 if ($@){
213 croak $@;
215 eval {
216 require C4::Bookseller;
217 import C4::Bookseller qw/GetBookSellerFromId/;
219 if ($@){
220 croak $@;
222 my $basket = GetBasket( $orderinfo{basketno} );
223 my $bookseller = GetBookSellerFromId( $basket->{booksellerid} );
224 $orderinfo{gstrate} = $bookseller->{gstrate};
225 $orderinfo{rrp} = $price;
226 $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $bookseller->{discount} / 100 );
227 $orderinfo{listprice} = $orderinfo{rrp};
228 $orderinfo{unitprice} = $orderinfo{ecost};
229 $orderinfo{total} = $orderinfo{ecost};
230 } else {
231 $orderinfo{'listprice'} = 0;
234 # remove uncertainprice flag if we have found a price in the MARC record
235 $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
236 my $basketno;
237 ( $basketno, $ordernumber ) = NewOrder( \%orderinfo );
239 # 4th, add items if applicable
240 # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
241 # this is not optimised, but it's working !
242 if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
243 my @tags = $input->param('tag');
244 my @subfields = $input->param('subfield');
245 my @field_values = $input->param('field_value');
246 my @serials = $input->param('serial');
247 my @ind_tag = $input->param('ind_tag');
248 my @indicator = $input->param('indicator');
249 my $item;
250 push @{ $item->{tags} }, $tags[0];
251 push @{ $item->{subfields} }, $subfields[0];
252 push @{ $item->{field_values} }, $field_values[0];
253 push @{ $item->{ind_tag} }, $ind_tag[0];
254 push @{ $item->{indicator} }, $indicator[0];
255 my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@ind_tag, \@indicator );
256 my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
257 for (my $qtyloop=1;$qtyloop <=$quantity;$qtyloop++) {
258 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
259 NewOrderItem( $itemnumber, $ordernumber );
261 } else {
262 SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
265 # go to basket page
266 print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'});
267 exit;
270 my $budgets = GetBudgets();
271 my $budget_id = @$budgets[0]->{'budget_id'};
272 # build bookfund list
273 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
274 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
275 my $budget = GetBudget($budget_id);
277 # build budget list
278 my $budget_loop = [];
279 $budgets = GetBudgetHierarchy;
280 foreach my $r ( @{$budgets} ) {
281 next unless (CanUserUseBudget($borrower, $r, $userflags));
282 if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
283 next;
285 push @{$budget_loop},
286 { b_id => $r->{budget_id},
287 b_txt => $r->{budget_name},
288 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
291 $template->param( budget_loop => $budget_loop,);
293 my $CGIsort1;
294 if ($budget) { # its a mod ..
295 if ( defined $budget->{'sort1_authcat'} ) { # with custom Asort* planning values
296 $CGIsort1 = GetAuthvalueDropbox( $budget->{'sort1_authcat'}, $data->{'sort1'} );
298 } elsif ( scalar(@$budgets) ) {
299 $CGIsort1 = GetAuthvalueDropbox( @$budgets[0]->{'sort1_authcat'}, '' );
301 # if CGIsort is successfully fetched, the use it
302 # else - failback to plain input-field
303 if ($CGIsort1) {
304 $template->param( CGIsort1 => $CGIsort1 );
305 } else {
306 $template->param( sort1 => $data->{'sort1'} );
309 my $CGIsort2;
310 if ($budget) {
311 if ( defined $budget->{'sort2_authcat'} ) {
312 $CGIsort2 = GetAuthvalueDropbox( $budget->{'sort2_authcat'}, $data->{'sort2'} );
314 } elsif ( scalar(@$budgets) ) {
315 $CGIsort2 = GetAuthvalueDropbox( @$budgets[0]->{sort2_authcat}, '' );
317 if ($CGIsort2) {
318 $template->param( CGIsort2 => $CGIsort2 );
319 } else {
320 $template->param( sort2 => $data->{'sort2'} );
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'} eq "staged") {
333 # check if there is at least 1 line still staged
334 my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, undef, 'staged');
335 if (scalar @$stagedList) {
336 my ($staged_date, $staged_hour) = split (/ /, $batch->{'upload_timestamp'});
337 push @list, {
338 import_batch_id => $batch->{'import_batch_id'},
339 num_biblios => $batch->{'num_biblios'},
340 num_items => $batch->{'num_items'},
341 staged_date => $staged_date,
342 staged_hour => $staged_hour,
343 import_status => $batch->{'import_status'},
344 file_name => $batch->{'file_name'},
345 comments => $batch->{'comments'},
347 } else {
348 # if there are no more line to includes, set the status to imported
349 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
353 $template->param(batch_list => \@list);
354 my $num_batches = GetNumberOfNonZ3950ImportBatches();
355 $template->param(num_results => $num_batches);
358 sub import_biblios_list {
359 my ($template, $import_batch_id) = @_;
360 my $batch = GetImportBatch($import_batch_id,'staged');
361 my $biblios = GetImportRecordsRange($import_batch_id,'','','staged');
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 push @list, \%cellrecord;
386 my $num_biblios = $batch->{'num_biblios'};
387 my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
388 my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
389 my $item_action = GetImportBatchItemAction($import_batch_id);
390 $template->param(biblio_list => \@list,
391 num_results => $num_biblios,
392 import_batch_id => $import_batch_id,
393 "overlay_action_${overlay_action}" => 1,
394 overlay_action => $overlay_action,
395 "nomatch_action_${nomatch_action}" => 1,
396 nomatch_action => $nomatch_action,
397 "item_action_${item_action}" => 1,
398 item_action => $item_action
400 batch_info($template, $batch);
403 sub batch_info {
404 my ($template, $batch) = @_;
405 $template->param(batch_info => 1,
406 file_name => $batch->{'file_name'},
407 comments => $batch->{'comments'},
408 import_status => $batch->{'import_status'},
409 upload_timestamp => $batch->{'upload_timestamp'},
410 num_biblios => $batch->{'num_biblios'},
411 num_items => $batch->{'num_biblios'});
412 if ($batch->{'num_biblios'} > 0) {
413 if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
414 $template->param(can_commit => 1);
416 if ($batch->{'import_status'} eq 'imported') {
417 $template->param(can_revert => 1);
420 if (defined $batch->{'matcher_id'}) {
421 my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
422 if (defined $matcher) {
423 $template->param('current_matcher_id' => $batch->{'matcher_id'},
424 'current_matcher_code' => $matcher->code(),
425 'current_matcher_description' => $matcher->description());
428 add_matcher_list($batch->{'matcher_id'}, $template);
431 sub add_matcher_list {
432 my ($current_matcher_id, $template) = @_;
433 my @matchers = C4::Matcher::GetMatcherList();
434 if (defined $current_matcher_id) {
435 for (my $i = 0; $i <= $#matchers; $i++) {
436 if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
437 $matchers[$i]->{'selected'} = 1;
441 $template->param(available_matchers => \@matchers);