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
29 use URI::Escape qw( uri_escape_utf8 );
31 use DateTime::Duration;
32 use Scalar::Util qw( blessed looks_like_number );
34 use C4::Output qw( output_and_exit_if_error output_and_exit output_html_with_http_headers );
35 use C4::Auth qw( get_session get_template_and_user );
37 use C4::Circulation qw( barcodedecode CanBookBeIssued AddIssue AddReturn );
39 use C4::Biblio qw( TransformMarcToKoha );
40 use C4::Search qw( new_record_from_zebra );
41 use C4::Reserves qw( ModReserveAffect );
45 use Koha::AuthorisedValues;
46 use Koha::CsvProfiles;
48 use Koha::DateUtils qw( dt_from_string );
49 use Koha::Patron::Restriction::Types;
52 use Koha::BiblioFrameworks;
54 use Koha::SearchEngine;
55 use Koha::SearchEngine::Search;
56 use Koha::Patron::Modifications;
59 use List::MoreUtils qw( uniq );
66 my $borrowernumber = $query->param('borrowernumber');
68 my $barcode = $query->param('barcode');
71 # Barcode given by user could be '0'
72 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
73 $barcodes = [ $barcode ];
75 my $filefh = $query->upload('uploadfile');
77 while ( my $content = <$filefh> ) {
78 $content =~ s/[\r\n]*$//g;
79 push @$barcodes, $content if $content;
81 } elsif ( my $list = $query->param('barcodelist') ) {
82 push @$barcodes, split( /\s\n/, $list );
83 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
85 @$barcodes = $query->multi_param('barcodes');
88 $barcodes = [ uniq @$barcodes ];
90 my $template_name = q|circ/circulation.tt|;
91 my $patron = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : undef;
92 my $batch = $query->param('batch');
93 my $batch_allowed = 0;
94 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
95 $template_name = q|circ/circulation_batch_checkouts.tt|;
96 my @batch_category_codes = split ',', C4::Context->preference('BatchCheckoutsValidCategories');
97 my $categorycode = $patron->categorycode;
98 if ( $categorycode && grep { $_ eq $categorycode } @batch_category_codes ) {
105 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
107 template_name => $template_name,
110 flagsrequired => { circulate => 'circulate_remaining_permissions' },
114 my $override_high_holds = $query->param('override_high_holds');
115 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
117 my $sessionID = $query->cookie("CGISESSID");
118 my $session = get_session($sessionID);
120 my $userenv = C4::Context->userenv;
121 my $branch = $userenv->{'branch'} // '';
122 my $desk_id = $userenv->{"desk_id"} || '';
127 if ( C4::Context->preference("AutoSwitchPatron") && $barcode ) {
128 my $new_barcode = $barcode;
129 Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
130 if ( Koha::Patrons->search( { cardnumber => $new_barcode } )->count() > 0 ) {
131 $findborrower = $barcode;
133 undef $borrowernumber;
137 $findborrower ||= $query->param('findborrower') || q{};
138 $findborrower =~ s|,| |g;
140 if ( $query->param('confirm_hold') ) {
141 my $reserve_id = $query->param('confirm_hold');
142 my $hold_branch = $query->param('hold_branch');
143 my $hold_itemnumber = $query->param('hold_itemnumber');
144 my $hold_borrowernumber = $query->param('hold_borrowernumber');
145 my $diffBranchSend = ( $branch ne $hold_branch );
147 # diffBranchSend tells ModReserveAffect whether document is expected in this library or not,
148 # i.e., whether to apply waiting status
149 ModReserveAffect( $hold_itemnumber, $hold_borrowernumber, $diffBranchSend, $reserve_id, $desk_id );
153 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
155 my $force_allow_issue = $query->param('forceallow') || 0;
156 if (!C4::Auth::haspermission( $userenv->{id} , { circulate => 'force_checkout' } )) {
157 $force_allow_issue = 0;
159 my $onsite_checkout = $query->param('onsite_checkout');
161 if (C4::Context->preference("OnSiteCheckoutAutoCheck") && $onsite_checkout eq "on") {
162 $template->param(onsite_checkout => $onsite_checkout);
165 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
166 our %renew_failed = ();
167 for (@failedrenews) { $renew_failed{$_} = 1; }
169 my @failedreturns = $query->multi_param('failedreturn');
170 our %return_failed = ();
171 for (@failedreturns) { $return_failed{$_} = 1; }
173 for my $barcode ( @$barcodes ) {
174 $barcode = barcodedecode( $barcode ) if $barcode;
177 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
178 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
179 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
180 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
181 undef $restoreduedatespec;
183 my $issueconfirmed = $query->param('issueconfirmed');
184 my $cancelreserve = $query->param('cancelreserve');
185 my $cancel_recall = $query->param('cancel_recall');
186 my $recall_id = $query->param('recall_id');
187 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
188 my $charges = $query->param('charges') || q{};
190 # Check if stickyduedate is turned off
192 # was stickyduedate loaded from session?
193 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
194 $session->clear( 'stickyduedate' );
195 $stickyduedate = $query->param('stickyduedate');
196 $duedatespec = $query->param('duedatespec');
198 $session->param('auto_renew', scalar $query->param('auto_renew'));
201 $session->clear('auto_renew');
204 $template->param( auto_renew => $session->param('auto_renew') );
206 my ($datedue,$invalidduedate);
208 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
209 if( $onsite_checkout && !$duedatespec_allow ) {
210 $datedue = dt_from_string()->truncate(to => 'day');
211 $datedue->set_hour(23);
212 $datedue->set_minute(59);
213 } elsif( $duedatespec_allow ) {
214 if ( $duedatespec ) {
215 $datedue = eval { dt_from_string( $duedatespec ) };
218 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
222 my $reduced_datedue = $query->param('reduceddue');
223 if ( $reduced_datedue ) {
224 $datedue = dt_from_string( $reduced_datedue );
227 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
228 if ( @$barcodes == 0 && $charges eq 'yes' ) {
231 borrowernumber => $borrowernumber
236 # STEP 2 : FIND BORROWER
237 # if there is a list of find borrowers....
241 Koha::Plugins->call( 'patron_barcode_transform', \$findborrower );
242 my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
244 $borrowernumber = $patron->borrowernumber;
246 print $query->redirect( "/cgi-bin/koha/members/member.pl?quicksearch=1&circsearch=1&searchmember=" . uri_escape_utf8($findborrower) );
251 # get the borrower information.....
253 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
256 $template->param( borrowernumber => $patron->borrowernumber );
257 output_and_exit_if_error( $query, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
259 my $overdues = $patron->overdues;
260 my $issues = $patron->checkouts;
261 $balance = $patron->account->balance;
264 # if the expiry date is before today ie they have expired
265 if ( $patron->is_expired ) {
266 #borrowercard expired, no issues
268 noissues => ($force_allow_issue) ? 0 : "1",
269 forceallow => $force_allow_issue,
273 # check for NotifyBorrowerDeparture
274 elsif ( $patron->is_going_to_expire ) {
275 # borrower card soon to expire warn librarian
276 $template->param( "warndeparture" => $patron->dateexpiry ,
278 if (C4::Context->preference('ReturnBeforeExpiry')){
279 $template->param("returnbeforeexpiry" => 1);
283 overduecount => $overdues->count,
284 issuecount => $issues->count,
285 finetotal => $balance,
288 if ( $patron and $patron->is_debarred ) {
290 'userdebarred' => $patron->debarred,
291 'debarredcomment' => $patron->debarredcomment,
292 'debarredsince' => $patron->restrictions->search()->single->created,
295 if ( $patron->debarred ne "9999-12-31" ) {
296 $template->param( 'userdebarreddate' => $patron->debarred );
300 # Calculate and display patron's age
301 if ( !$patron->is_valid_age ) {
302 $template->param( age_limitations => 1 );
303 $template->param( age_low => $patron->category->dateofbirthrequired );
304 $template->param( age_high => $patron->category->upperagelimit );
315 for my $barcode ( @$barcodes ) {
317 my $template_params = {
319 onsite_checkout => $onsite_checkout,
322 # always check for blockers on issuing
323 my ( $issuingimpossible, $needsconfirmation, $alerts, $messages );
325 ( $issuingimpossible, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued(
331 onsite_checkout => $onsite_checkout,
332 override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
336 die $_ unless blessed $_ && $_->can('rethrow');
338 if ( $_->isa('Koha::Exceptions::Calendar::NoOpenDays') ) {
339 $issuingimpossible = { NO_OPEN_DAYS => 1 };
345 my $blocker = $invalidduedate ? 1 : 0;
347 $template_params->{alert} = $alerts;
348 $template_params->{messages} = $messages;
350 my $item = Koha::Items->find({ barcode => $barcode });
354 $biblio = $item->biblio;
357 if ( $issuingimpossible->{'STATS'} ) {
358 $template->param( STATS => 1 );
360 if ( $item->onloan ) {
361 my ( $stats_return, $stats_messages, $stats_iteminformation, $stats_borrower ) =
362 AddReturn( $item->barcode, C4::Context->userenv->{'branch'}, undef, undef, 1 );
365 CHECKEDIN => $stats_return,
366 MESSAGES => $stats_messages,
367 ITEM => $stats_iteminformation,
368 BORROWER => $stats_borrower,
372 # Fix for bug 7494: optional checkout-time fallback search for a book
374 if ( $issuingimpossible->{'UNKNOWN_BARCODE'}
375 && C4::Context->preference("itemBarcodeFallbackSearch")
379 $template_params->{FALLBACK} = 1;
381 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
382 my $query = "kw=" . $barcode;
383 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
385 # if multiple hits, offer options to librarian
386 if ( $total_hits > 0 ) {
388 foreach my $hit ( @{$results} ) {
389 my $chosen = # Maybe easier to retrieve the itemnumber from $hit?
390 TransformMarcToKoha({ record => C4::Search::new_record_from_zebra('biblioserver',$hit) });
392 # offer all barcodes individually
393 if ( $chosen->{barcode} ) {
394 push @barcodes, sort split(/\s*\|\s*/, $chosen->{barcode});
397 my $items = Koha::Items->search({ barcode => {-in => \@barcodes}});
398 $template_params->{options} = $items;
402 # Only some errors will block when performing forced onsite checkout,
403 # for other cases all errors will block
404 my @blocking_error_codes =
405 ( $onsite_checkout and C4::Context->preference("OnSiteCheckoutsForce") )
406 ? qw( UNKNOWN_BARCODE NO_OPEN_DAYS )
407 : ( keys %$issuingimpossible );
409 if ( $issuingimpossible->{BOOKED_TO_ANOTHER} ) {
410 $template_params->{BOOKED_TO_ANOTHER} = $issuingimpossible->{BOOKED_TO_ANOTHER};
411 $template_params->{IMPOSSIBLE} = 1;
415 foreach my $code ( @blocking_error_codes ) {
416 if ($issuingimpossible->{$code}) {
417 $template_params->{$code} = $issuingimpossible->{$code};
419 $template_params->{IMPOSSIBLE} = 1;
424 delete $needsconfirmation->{'DEBT'} if ($debt_confirmed);
426 if( $item and ( !$blocker or $force_allow_issue ) ){
427 my $confirm_required = 0;
428 unless($issueconfirmed){
429 # Get the item title for more information
430 my $materials = $item->materials;
431 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
432 $materials = $descriptions->{lib} // $materials;
433 $template_params->{ADDITIONAL_MATERIALS} = $materials;
434 $template_params->{itemhomebranch} = $item->homebranch;
436 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
437 foreach my $needsconfirmation_key ( keys %$needsconfirmation ) {
438 $template_params->{$needsconfirmation_key} = $needsconfirmation->{$needsconfirmation_key};
439 $template_params->{getTitleMessageIteminfo} = $biblio->title;
440 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
441 $template_params->{NEEDSCONFIRMATION} = 1;
442 $confirm_required = 1;
443 if ( $needsconfirmation_key eq 'BOOKED_TO_ANOTHER' ) {
445 dt_from_string( $$needsconfirmation{$needsconfirmation_key}->start_date )->subtract( days => 1 );
446 $template_params->{reduceddue} = $reduceddue;
450 unless ($confirm_required) {
451 my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED};
452 if ( C4::Context->preference('UseRecalls') && !$recall_id ) {
453 my $recall = Koha::Recalls->find(
455 biblio_id => $item->biblionumber,
456 item_id => [ undef, $item->itemnumber ],
457 status => [ 'requested', 'waiting' ],
459 patron_id => $patron->borrowernumber,
462 $recall_id = ( $recall and $recall->id ) ? $recall->id : undef;
465 # If booked (alerts or confirmation) update datedue to end of booking
466 if ( my $booked = $needsconfirmation->{BOOKED_EARLY} // $alerts->{BOOKED} ) {
467 $datedue = $booked->end_date;
469 my $issue = AddIssue(
470 $patron, $barcode, $datedue,
474 onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew'),
475 switch_onsite_checkout => $switch_onsite_checkout, cancel_recall => $cancel_recall,
476 recall_id => $recall_id,
479 $template_params->{issue} = $issue;
480 $session->clear('auto_renew');
485 if ($needsconfirmation->{RESERVE_WAITING} or $needsconfirmation->{RESERVED} or $needsconfirmation->{TRANSFERRED} or $needsconfirmation->{PROCESSING}){
487 reserveborrowernumber => $needsconfirmation->{'resborrowernumber'},
488 reserve_id => $needsconfirmation->{reserve_id},
493 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
494 $patron = Koha::Patrons->find( $borrowernumber );
495 $template_params->{issuecount} = $patron->checkouts->count;
498 $template_params->{item} = $item;
499 $template_params->{biblio} = $biblio;
500 $template_params->{itembiblionumber} = $biblio->biblionumber;
502 push @$checkout_infos, $template_params;
505 $template->param( %{$checkout_infos->[0]} );
506 $template->param( barcode => $barcodes->[0] );
508 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
510 checkout_infos => $checkout_infos,
511 onsite_checkout => $onsite_checkout,
512 confirmation_needed => $confirmation_needed,
517 ##################################################################################
519 # show all reserves of this borrower, and the position of the reservation ....
521 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
522 my $waiting_holds = $holds->waiting;
524 holds_count => $holds->count(),
525 WaitingHolds => $waiting_holds,
528 if ( C4::Context->preference('UseRecalls') ) {
529 my $waiting_recalls = $patron->recalls->search({ status => 'waiting' });
531 recalls => $patron->recalls->filter_by_current->search({},{ order_by => { -asc => 'created_date' } }),
532 specific_patron => 1,
533 waiting_recalls => $waiting_recalls,
540 if ( $patron->gonenoaddress ) {
541 $template->param( gonenoaddress => 1 );
544 if ( $patron->lost ) {
545 $template->param( lost=> 1 );
548 if ( $patron->is_debarred ) {
549 $template->param( is_debarred=> 1 );
552 if ( $patron->borrowernumber eq C4::Context->preference("AnonymousPatron") ) {
553 $template->param( is_anonymous => 1 );
556 my $account = $patron->account;
557 if( ( my $owing = $account->non_issues_charges ) > 0 ) {
558 my $noissuescharge = C4::Context->preference("noissuescharge") || 5; # FIXME If noissuescharge == 0 then 5, why??
559 $noissues ||= ( not C4::Context->preference("AllowFineOverride") and ( $owing > $noissuescharge ) );
562 chargesamount => $owing,
564 } elsif ( $balance < 0 ) {
567 creditsamount => -$balance,
571 # Check the debt of this patrons guarantors *and* the guarantees of those guarantors
572 my $no_issues_charge_guarantors = C4::Context->preference("NoIssuesChargeGuarantorsWithGuarantees");
573 if ( $no_issues_charge_guarantors ) {
574 my $guarantors_non_issues_charges = $patron->relationships_debt({ include_guarantors => 1, only_this_guarantor => 0, include_this_patron => 1 });
576 if ( $guarantors_non_issues_charges > $no_issues_charge_guarantors ) {
578 charges_guarantors_guarantees => $guarantors_non_issues_charges
580 $noissues = 1 unless C4::Context->preference("allowfineoverride");
584 my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
585 $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
586 if ( defined $no_issues_charge_guarantees ) {
587 my $guarantees_non_issues_charges = 0;
588 my $guarantees = $patron->guarantee_relationships->guarantees;
589 while ( my $g = $guarantees->next ) {
590 $guarantees_non_issues_charges += $g->account->non_issues_charges;
592 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
594 charges_guarantees => 1,
595 chargesamount_guarantees => $guarantees_non_issues_charges,
597 $noissues = 1 unless C4::Context->preference("allowfineoverride");
601 if ( $patron->has_overdues ) {
602 $template->param( odues => 1 );
605 if ( $patron->borrowernotes ) {
606 my $borrowernotes = $patron->borrowernotes;
607 $borrowernotes =~ s#\n#<br />#g;
610 notesmsg => $borrowernotes,
616 noissues => ($force_allow_issue) ? 0 : 'true',
617 forceallow => $force_allow_issue,
621 my $patron_messages = $patron->messages->search(
625 '+select' => ['manager.surname', 'manager.firstname' ],
626 '+as' => ['manager_surname', 'manager_firstname'],
629 $template->param( patron_messages => $patron_messages );
633 my $fast_cataloging = 0;
634 if ( Koha::BiblioFrameworks->find('FA') ) {
639 ?'batch_checkout_view'
644 if ( my @guarantors = $patron->guarantor_relationships()->guarantors->as_list ) {
645 push( @relatives, $_->id ) for @guarantors;
646 push( @relatives, $_->id ) for $patron->siblings->as_list;
648 push( @relatives, $_->id ) for $patron->guarantee_relationships()->guarantees->as_list;
651 my $relatives_issues_count =
652 Koha::Database->new()->schema()->resultset('Issue')
653 ->count( { borrowernumber => \@relatives } );
656 my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
657 my $roadtype = $av->count ? $av->next->lib : '';
659 roadtype => $roadtype,
661 categoryname => $patron->category->description,
662 expiry => $patron->dateexpiry,
666 # Restore date if changed by holds and/or save stickyduedate to session
667 if ($restoreduedatespec || $stickyduedate) {
668 $duedatespec = $restoreduedatespec || $duedatespec;
670 if ($stickyduedate) {
671 $session->param( 'stickyduedate', $duedatespec );
673 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
678 borrowernumber => $borrowernumber,
680 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
681 barcodes => $barcodes,
682 stickyduedate => $stickyduedate,
683 duedatespec => $duedatespec,
684 restoreduedatespec => $restoreduedatespec,
686 totaldue => sprintf('%.2f', $balance), # FIXME not used in template?
687 inprocess => $inprocess,
689 batch_allowed => $batch_allowed,
691 AudioAlerts => C4::Context->preference("AudioAlerts"),
692 fast_cataloging => $fast_cataloging,
693 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
694 RoutingSerials => C4::Context->preference('RoutingSerials'),
695 relatives_issues_count => $relatives_issues_count,
696 relatives_borrowernumbers => \@relatives,
700 if ( C4::Context->preference("ExportCircHistory") ) {
701 $template->param(csv_profiles => Koha::CsvProfiles->search({ type => 'marc' }));
704 my ( $has_modifications, $patron_lists_count);
706 $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
707 $patron_lists_count = $patron->get_lists_with_patron->count();
710 debt_confirmed => $debt_confirmed,
711 SpecifyDueDate => $duedatespec_allow,
712 PatronAutoComplete => C4::Context->preference("PatronAutoComplete"),
713 today_due_date_and_time => dt_from_string()->set(hour => 23)->set(minute => 59),
714 restriction_types => scalar Koha::Patron::Restriction::Types->search(),
715 has_modifications => $has_modifications,
716 patron_lists_count => $patron_lists_count,
717 override_high_holds => $override_high_holds,
718 nopermission => scalar $query->param('nopermission'),
719 autoswitched => $autoswitched,
720 logged_in_user => $logged_in_user,
723 # Generate CSRF token for upload and delete image buttons
725 csrf_token => Koha::Token->new->generate_csrf({ session_id => $query->cookie('CGISESSID'),}),
728 output_html_with_http_headers $query, $cookie, $template->output;