Bug 26145: (QA follow-up) Add missing filters
[koha.git] / circ / circulation.pl
blobdcb206119cfd0021746be139f7b3b1dfae6d6156
1 #!/usr/bin/perl
3 # script to execute issuing of books
5 # Copyright 2000-2002 Katipo Communications
6 # copyright 2010 BibLibre
7 # Copyright 2011 PTFS-Europe Ltd.
8 # Copyright 2012 software.coop and MJ Ray
10 # This file is part of Koha.
12 # Koha is free software; you can redistribute it and/or modify it
13 # under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 3 of the License, or
15 # (at your option) any later version.
17 # Koha is distributed in the hope that it will be useful, but
18 # WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
22 # You should have received a copy of the GNU General Public License
23 # along with Koha; if not, see <http://www.gnu.org/licenses>.
25 # FIXME There are too many calls to Koha::Patrons->find in this script
27 use Modern::Perl;
28 use CGI qw ( -utf8 );
29 use DateTime;
30 use DateTime::Duration;
31 use Scalar::Util qw( looks_like_number );
32 use C4::Output;
33 use C4::Auth qw/:DEFAULT get_session haspermission/;
34 use C4::Koha;
35 use C4::Circulation;
36 use C4::Utils::DataTables::Members;
37 use C4::Members;
38 use C4::Biblio;
39 use C4::Search;
40 use MARC::Record;
41 use C4::Reserves;
42 use Koha::Holds;
43 use C4::Context;
44 use CGI::Session;
45 use Koha::AuthorisedValues;
46 use Koha::CsvProfiles;
47 use Koha::Patrons;
48 use Koha::Patron::Debarments qw(GetDebarments);
49 use Koha::DateUtils;
50 use Koha::Database;
51 use Koha::BiblioFrameworks;
52 use Koha::Items;
53 use Koha::Patron::Messages;
54 use Koha::SearchEngine;
55 use Koha::SearchEngine::Search;
56 use Koha::Patron::Modifications;
58 use Date::Calc qw(
59 Today
60 Add_Delta_Days
61 Date_to_Days
63 use List::MoreUtils qw/uniq/;
66 # PARAMETERS READING
68 my $query = new CGI;
70 my $override_high_holds = $query->param('override_high_holds');
71 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
73 my $sessionID = $query->cookie("CGISESSID") ;
74 my $session = get_session($sessionID);
76 my $barcodes = [];
77 my $barcode = $query->param('barcode');
78 my $findborrower;
79 my $autoswitched;
80 my $borrowernumber = $query->param('borrowernumber');
82 if (C4::Context->preference("AutoSwitchPatron") && $barcode) {
83 if (Koha::Patrons->search( { cardnumber => $barcode} )->count() > 0) {
84 $findborrower = $barcode;
85 undef $barcode;
86 undef $borrowernumber;
87 $autoswitched = 1;
90 $findborrower ||= $query->param('findborrower') || q{};
91 $findborrower =~ s|,| |g;
93 # Barcode given by user could be '0'
94 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
95 $barcodes = [ $barcode ];
96 } else {
97 my $filefh = $query->upload('uploadfile');
98 if ( $filefh ) {
99 while ( my $content = <$filefh> ) {
100 $content =~ s/[\r\n]*$//g;
101 push @$barcodes, $content if $content;
103 } elsif ( my $list = $query->param('barcodelist') ) {
104 push @$barcodes, split( /\s\n/, $list );
105 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
106 } else {
107 @$barcodes = $query->multi_param('barcodes');
111 $barcodes = [ uniq @$barcodes ];
113 my $template_name = q|circ/circulation.tt|;
114 my $patron = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : undef;
115 my $batch = $query->param('batch');
116 my $batch_allowed = 0;
117 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
118 $template_name = q|circ/circulation_batch_checkouts.tt|;
119 my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
120 my $categorycode = $patron->categorycode;
121 if ( $categorycode && grep { $_ eq $categorycode } @batch_category_codes ) {
122 $batch_allowed = 1;
123 } else {
124 $barcodes = [];
128 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
130 template_name => $template_name,
131 query => $query,
132 type => "intranet",
133 flagsrequired => { circulate => 'circulate_remaining_permissions' },
136 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
138 my $force_allow_issue = $query->param('forceallow') || 0;
139 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
140 $force_allow_issue = 0;
142 my $onsite_checkout = $query->param('onsite_checkout');
144 if (C4::Context->preference("OnSiteCheckoutAutoCheck") && $onsite_checkout eq "on") {
145 $template->param(onsite_checkout => $onsite_checkout);
148 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
149 our %renew_failed = ();
150 for (@failedrenews) { $renew_failed{$_} = 1; }
152 my @failedreturns = $query->multi_param('failedreturn');
153 our %return_failed = ();
154 for (@failedreturns) { $return_failed{$_} = 1; }
156 my $searchtype = $query->param('searchtype') || q{contain};
158 my $branch = C4::Context->userenv->{'branch'};
160 if (C4::Context->preference("DisplayClearScreenButton")) {
161 $template->param(DisplayClearScreenButton => 1);
164 for my $barcode ( @$barcodes ) {
165 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
166 $barcode = barcodedecode($barcode)
167 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
170 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
171 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
172 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso' }); }
173 if ( $duedatespec );
174 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
175 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
176 undef $restoreduedatespec;
178 my $issueconfirmed = $query->param('issueconfirmed');
179 my $cancelreserve = $query->param('cancelreserve');
180 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
181 my $charges = $query->param('charges') || q{};
183 # Check if stickyduedate is turned off
184 if ( @$barcodes ) {
185 # was stickyduedate loaded from session?
186 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
187 $session->clear( 'stickyduedate' );
188 $stickyduedate = $query->param('stickyduedate');
189 $duedatespec = $query->param('duedatespec');
191 $session->param('auto_renew', scalar $query->param('auto_renew'));
193 else {
194 $session->clear('auto_renew');
197 $template->param( auto_renew => $session->param('auto_renew') );
199 my ($datedue,$invalidduedate);
201 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
202 if( $onsite_checkout && !$duedatespec_allow ) {
203 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
204 $datedue .= ' 23:59:00';
205 } elsif( $duedatespec_allow ) {
206 if ( $duedatespec ) {
207 $datedue = eval { dt_from_string( $duedatespec ) };
208 if (! $datedue ) {
209 $invalidduedate = 1;
210 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
215 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
216 if ( @$barcodes == 0 && $charges eq 'yes' ) {
217 $template->param(
218 PAYCHARGES => 'yes',
219 borrowernumber => $borrowernumber
224 # STEP 2 : FIND BORROWER
225 # if there is a list of find borrowers....
227 my $message;
228 if ($findborrower) {
229 my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
230 if ( $patron ) {
231 $borrowernumber = $patron->borrowernumber;
232 } else {
233 my $dt_params = { iDisplayLength => -1 };
234 my $results = C4::Utils::DataTables::Members::search(
236 searchmember => $findborrower,
237 searchtype => $searchtype,
238 dt_params => $dt_params,
241 my $borrowers = $results->{patrons};
242 if ( scalar @$borrowers == 1 ) {
243 $borrowernumber = $borrowers->[0]->{borrowernumber};
244 $query->param( 'borrowernumber', $borrowernumber );
245 $query->param( 'barcode', '' );
246 } elsif ( @$borrowers ) {
247 $template->param( borrowers => $borrowers );
248 } else {
249 $query->param( 'findborrower', '' );
250 $message = "'$findborrower'";
255 # get the borrower information.....
256 my $balance = 0;
257 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
258 if ($patron) {
260 $template->param( borrowernumber => $patron->borrowernumber );
261 output_and_exit_if_error( $query, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
263 my $overdues = $patron->get_overdues;
264 my $issues = $patron->checkouts;
265 $balance = $patron->account->balance;
268 # if the expiry date is before today ie they have expired
269 if ( $patron->is_expired ) {
270 #borrowercard expired, no issues
271 $template->param(
272 noissues => ($force_allow_issue) ? 0 : "1",
273 forceallow => $force_allow_issue,
274 expired => "1",
277 # check for NotifyBorrowerDeparture
278 elsif ( $patron->is_going_to_expire ) {
279 # borrower card soon to expire warn librarian
280 $template->param( "warndeparture" => $patron->dateexpiry ,
282 if (C4::Context->preference('ReturnBeforeExpiry')){
283 $template->param("returnbeforeexpiry" => 1);
286 $template->param(
287 overduecount => $overdues->count,
288 issuecount => $issues->count,
289 finetotal => $balance,
292 if ( $patron and $patron->is_debarred ) {
293 $template->param(
294 'userdebarred' => $patron->debarred,
295 'debarredcomment' => $patron->debarredcomment,
298 if ( $patron->debarred ne "9999-12-31" ) {
299 $template->param( 'userdebarreddate' => $patron->debarred );
303 # Calculate and display patron's age
304 if ( !$patron->is_valid_age ) {
305 $template->param( age_limitations => 1 );
306 $template->param( age_low => $patron->category->dateofbirthrequired );
307 $template->param( age_high => $patron->category->upperagelimit );
313 # STEP 3 : ISSUING
316 if (@$barcodes) {
317 my $checkout_infos;
318 for my $barcode ( @$barcodes ) {
320 my $template_params = {
321 barcode => $barcode,
322 onsite_checkout => $onsite_checkout,
325 # always check for blockers on issuing
326 my ( $error, $question, $alerts, $messages ) = CanBookBeIssued(
327 $patron,
328 $barcode, $datedue,
329 $inprocess,
330 undef,
332 onsite_checkout => $onsite_checkout,
333 override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
337 my $blocker = $invalidduedate ? 1 : 0;
339 $template_params->{alert} = $alerts;
340 $template_params->{messages} = $messages;
342 my $item = Koha::Items->find({ barcode => $barcode });
344 my $biblio;
345 if ( $item ) {
346 $biblio = $item->biblio;
349 # Fix for bug 7494: optional checkout-time fallback search for a book
351 if ( $error->{'UNKNOWN_BARCODE'}
352 && C4::Context->preference("itemBarcodeFallbackSearch")
353 && not $batch
356 $template_params->{FALLBACK} = 1;
358 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
359 my $query = "kw=" . $barcode;
360 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
362 # if multiple hits, offer options to librarian
363 if ( $total_hits > 0 ) {
364 my @options = ();
365 foreach my $hit ( @{$results} ) {
366 my $chosen =
367 TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
369 # offer all barcodes individually
370 if ( $chosen->{barcode} ) {
371 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
372 my %chosen_single = %{$chosen};
373 $chosen_single{barcode} = $barcode;
374 push( @options, \%chosen_single );
378 $template_params->{options} = \@options;
382 if ( $error->{UNKNOWN_BARCODE} or not $onsite_checkout or not C4::Context->preference("OnSiteCheckoutsForce") ) {
383 delete $question->{'DEBT'} if ($debt_confirmed);
384 foreach my $impossible ( keys %$error ) {
385 $template_params->{$impossible} = $$error{$impossible};
386 $template_params->{IMPOSSIBLE} = 1;
387 $blocker = 1;
391 if( $item and ( !$blocker or $force_allow_issue ) ){
392 my $confirm_required = 0;
393 unless($issueconfirmed){
394 # Get the item title for more information
395 my $materials = $item->materials;
396 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
397 $materials = $descriptions->{lib} // $materials;
398 $template_params->{ADDITIONAL_MATERIALS} = $materials;
399 $template_params->{itemhomebranch} = $item->homebranch;
401 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
402 foreach my $needsconfirmation ( keys %$question ) {
403 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
404 $template_params->{getTitleMessageIteminfo} = $biblio->title;
405 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
406 $template_params->{NEEDSCONFIRMATION} = 1;
407 $confirm_required = 1;
410 unless($confirm_required) {
411 my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED};
412 my $issue = AddIssue( $patron->unblessed, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew'), switch_onsite_checkout => $switch_onsite_checkout, } );
413 $template_params->{issue} = $issue;
414 $session->clear('auto_renew');
415 $inprocess = 1;
419 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
420 $template->param(
421 reserveborrowernumber => $question->{'resborrowernumber'},
422 reserve_id => $question->{reserve_id},
427 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
428 $patron = Koha::Patrons->find( $borrowernumber );
429 $template_params->{issuecount} = $patron->checkouts->count;
431 if ( $item ) {
432 $template_params->{item} = $item;
433 $template_params->{biblio} = $biblio;
434 $template_params->{itembiblionumber} = $biblio->biblionumber;
436 push @$checkout_infos, $template_params;
438 unless ( $batch ) {
439 $template->param( %{$checkout_infos->[0]} );
440 $template->param( barcode => $barcodes->[0] );
441 } else {
442 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
443 $template->param(
444 checkout_infos => $checkout_infos,
445 confirmation_needed => $confirmation_needed,
450 ##################################################################################
451 # BUILD HTML
452 # show all reserves of this borrower, and the position of the reservation ....
453 if ($patron) {
454 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
455 my $waiting_holds = $holds->waiting;
456 $template->param(
457 holds_count => $holds->count(),
458 WaitingHolds => $waiting_holds,
462 if ( $patron ) {
463 my $noissues;
464 if ( $patron->gonenoaddress ) {
465 $template->param( gna => 1 );
466 $noissues = 1;
468 if ( $patron->lost ) {
469 $template->param( lost=> 1 );
470 $noissues = 1;
472 if ( $patron->is_debarred ) {
473 $template->param( dbarred=> 1 );
474 $noissues = 1;
476 my $account = $patron->account;
477 if( ( my $owing = $account->non_issues_charges ) > 0 ) {
478 my $noissuescharge = C4::Context->preference("noissuescharge") || 5; # FIXME If noissuescharge == 0 then 5, why??
479 $noissues ||= ( not C4::Context->preference("AllowFineOverride") and ( $owing > $noissuescharge ) );
480 $template->param(
481 charges => 1,
482 chargesamount => $owing,
484 } elsif ( $balance < 0 ) {
485 $template->param(
486 credits => 1,
487 creditsamount => -$balance,
491 my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
492 $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
493 if ( defined $no_issues_charge_guarantees ) {
494 my $guarantees_non_issues_charges = 0;
495 my $guarantees = $patron->guarantee_relationships->guarantees;
496 while ( my $g = $guarantees->next ) {
497 $guarantees_non_issues_charges += $g->account->non_issues_charges;
499 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
500 $template->param(
501 charges_guarantees => 1,
502 chargesamount_guarantees => $guarantees_non_issues_charges,
504 $noissues = 1 unless C4::Context->preference("allowfineoverride");
508 if ( $patron->has_overdues ) {
509 $template->param( odues => 1 );
512 if ( $patron->borrowernotes ) {
513 my $borrowernotes = $patron->borrowernotes;
514 $borrowernotes =~ s#\n#<br />#g;
515 $template->param(
516 notes =>1,
517 notesmsg => $borrowernotes,
521 if ( $noissues ) {
522 $template->param(
523 noissues => ($force_allow_issue) ? 0 : 'true',
524 forceallow => $force_allow_issue,
529 my $messages = Koha::Patron::Messages->search(
531 'me.borrowernumber' => $borrowernumber,
534 join => 'manager',
535 '+select' => ['manager.surname', 'manager.firstname' ],
536 '+as' => ['manager_surname', 'manager_firstname'],
540 my $fast_cataloging = 0;
541 if ( Koha::BiblioFrameworks->find('FA') ) {
542 $fast_cataloging = 1
545 my $view = $batch
546 ?'batch_checkout_view'
547 : 'circview';
549 my @relatives;
550 if ( $patron ) {
551 if ( my @guarantors = $patron->guarantor_relationships()->guarantors() ) {
552 push( @relatives, $_->id ) for @guarantors;
553 push( @relatives, $_->id ) for $patron->siblings();
554 } else {
555 push( @relatives, $_->id ) for $patron->guarantee_relationships()->guarantees();
558 my $relatives_issues_count =
559 Koha::Database->new()->schema()->resultset('Issue')
560 ->count( { borrowernumber => \@relatives } );
562 if ( $patron ) {
563 my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
564 my $roadtype = $av->count ? $av->next->lib : '';
565 $template->param(
566 roadtype => $roadtype,
567 patron => $patron,
568 categoryname => $patron->category->description,
569 expiry => $patron->dateexpiry,
573 # Restore date if changed by holds and/or save stickyduedate to session
574 if ($restoreduedatespec || $stickyduedate) {
575 $duedatespec = $restoreduedatespec || $duedatespec;
577 if ($stickyduedate) {
578 $session->param( 'stickyduedate', $duedatespec );
580 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
581 undef $duedatespec;
584 $template->param(
585 messages => $messages,
586 borrowernumber => $borrowernumber,
587 branch => $branch,
588 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
589 barcodes => $barcodes,
590 stickyduedate => $stickyduedate,
591 duedatespec => $duedatespec,
592 restoreduedatespec => $restoreduedatespec,
593 message => $message,
594 totaldue => sprintf('%.2f', $balance), # FIXME not used in template?
595 inprocess => $inprocess,
596 $view => 1,
597 batch_allowed => $batch_allowed,
598 batch => $batch,
599 AudioAlerts => C4::Context->preference("AudioAlerts"),
600 fast_cataloging => $fast_cataloging,
601 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
602 RoutingSerials => C4::Context->preference('RoutingSerials'),
603 relatives_issues_count => $relatives_issues_count,
604 relatives_borrowernumbers => \@relatives,
608 if ( C4::Context->preference("ExportCircHistory") ) {
609 $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
612 my $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
613 $template->param(
614 debt_confirmed => $debt_confirmed,
615 SpecifyDueDate => $duedatespec_allow,
616 PatronAutoComplete => C4::Context->preference("PatronAutoComplete"),
617 debarments => scalar GetDebarments({ borrowernumber => $borrowernumber }),
618 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
619 has_modifications => $has_modifications,
620 override_high_holds => $override_high_holds,
621 nopermission => scalar $query->param('nopermission'),
622 autoswitched => $autoswitched,
623 logged_in_user => $logged_in_user,
626 output_html_with_http_headers $query, $cookie, $template->output;