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
30 use DateTime
::Duration
;
31 use Scalar
::Util
qw( looks_like_number );
34 use C4
::Auth qw
/:DEFAULT get_session haspermission/;
35 use C4
::Koha
; # GetPrinter
37 use C4
::Utils
::DataTables
::Members
;
46 use Koha
::AuthorisedValues
;
47 use Koha
::CsvProfiles
;
49 use Koha
::Patron
::Debarments
qw(GetDebarments);
52 use Koha
::BiblioFrameworks
;
54 use Koha
::Patron
::Messages
;
55 use Koha
::SearchEngine
;
56 use Koha
::SearchEngine
::Search
;
57 use Koha
::Patron
::Modifications
;
64 use List
::MoreUtils qw
/uniq/;
71 my $override_high_holds = $query->param('override_high_holds');
72 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
74 my $sessionID = $query->cookie("CGISESSID") ;
75 my $session = get_session
($sessionID);
76 if (!C4
::Context
->userenv){
77 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
78 # no branch set we can't issue
79 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
85 my $barcode = $query->param('barcode');
88 my $borrowernumber = $query->param('borrowernumber');
90 if (C4
::Context
->preference("AutoSwitchPatron") && $barcode) {
91 if (Koha
::Patrons
->search( { cardnumber
=> $barcode} )->count() > 0) {
92 $findborrower = $barcode;
94 undef $borrowernumber;
98 $findborrower ||= $query->param('findborrower') || q{};
99 $findborrower =~ s
|,| |g
;
101 # Barcode given by user could be '0'
102 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
103 $barcodes = [ $barcode ];
105 my $filefh = $query->upload('uploadfile');
107 while ( my $content = <$filefh> ) {
108 $content =~ s/[\r\n]*$//g;
109 push @
$barcodes, $content if $content;
111 } elsif ( my $list = $query->param('barcodelist') ) {
112 push @
$barcodes, split( /\s\n/, $list );
113 $barcodes = [ map { $_ =~ /^\s*$/ ?
() : $_ } @
$barcodes ];
115 @
$barcodes = $query->multi_param('barcodes');
119 $barcodes = [ uniq @
$barcodes ];
121 my $template_name = q
|circ
/circulation
.tt
|;
122 my $patron = $borrowernumber ? Koha
::Patrons
->find( $borrowernumber ) : undef;
123 my $batch = $query->param('batch');
124 my $batch_allowed = 0;
125 if ( $batch && C4
::Context
->preference('BatchCheckouts') ) {
126 $template_name = q
|circ
/circulation_batch_checkouts
.tt
|;
127 my @batch_category_codes = split '\|', C4
::Context
->preference('BatchCheckoutsValidCategories');
128 my $categorycode = $patron->categorycode;
129 if ( $categorycode && grep {/^$categorycode$/} @batch_category_codes ) {
136 my ( $template, $loggedinuser, $cookie ) = get_template_and_user
(
138 template_name
=> $template_name,
141 authnotrequired
=> 0,
142 flagsrequired
=> { circulate
=> 'circulate_remaining_permissions' },
145 my $logged_in_user = Koha
::Patrons
->find( $loggedinuser ) or die "Not logged in";
147 my $force_allow_issue = $query->param('forceallow') || 0;
148 if (!C4
::Auth
::haspermission
( C4
::Context
->userenv->{id
} , { circulate
=> 'force_checkout' } )) {
149 $force_allow_issue = 0;
151 my $onsite_checkout = $query->param('onsite_checkout');
153 if (C4
::Context
->preference("OnSiteCheckoutAutoCheck") && $onsite_checkout eq "on") {
154 $template->param(onsite_checkout
=> $onsite_checkout);
157 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
158 our %renew_failed = ();
159 for (@failedrenews) { $renew_failed{$_} = 1; }
161 my @failedreturns = $query->multi_param('failedreturn');
162 our %return_failed = ();
163 for (@failedreturns) { $return_failed{$_} = 1; }
165 my $searchtype = $query->param('searchtype') || q{contain};
167 my $branch = C4
::Context
->userenv->{'branch'};
169 if (C4
::Context
->preference("DisplayClearScreenButton")) {
170 $template->param(DisplayClearScreenButton
=> 1);
173 for my $barcode ( @
$barcodes ) {
174 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
175 $barcode = barcodedecode
($barcode)
176 if( $barcode && C4
::Context
->preference('itemBarcodeInputFilter'));
179 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
180 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
181 $duedatespec = eval { output_pref
( { dt
=> dt_from_string
( $duedatespec ), dateformat
=> 'iso', timeformat
=> '24hr' }); }
183 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
184 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
185 undef $restoreduedatespec;
187 my $issueconfirmed = $query->param('issueconfirmed');
188 my $cancelreserve = $query->param('cancelreserve');
189 my $print = $query->param('print') || q{};
190 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
191 my $charges = $query->param('charges') || q{};
193 # Check if stickyduedate is turned off
195 # was stickyduedate loaded from session?
196 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
197 $session->clear( 'stickyduedate' );
198 $stickyduedate = $query->param('stickyduedate');
199 $duedatespec = $query->param('duedatespec');
201 $session->param('auto_renew', scalar $query->param('auto_renew'));
204 $session->clear('auto_renew');
207 my ($datedue,$invalidduedate);
209 my $duedatespec_allow = C4
::Context
->preference('SpecifyDueDate');
210 if( $onsite_checkout && !$duedatespec_allow ) {
211 $datedue = output_pref
({ dt
=> dt_from_string
, dateonly
=> 1, dateformat
=> 'iso' });
212 $datedue .= ' 23:59:00';
213 } elsif( $duedatespec_allow ) {
214 if ( $duedatespec ) {
215 $datedue = eval { dt_from_string
( $duedatespec ) };
218 $template->param( IMPOSSIBLE
=>1, INVALID_DATE
=>$duedatespec );
223 # check and see if we should print
224 if ( @
$barcodes == 0 && $print eq 'maybe' ) {
228 my $inprocess = (@
$barcodes == 0) ?
'' : $query->param('inprocess');
229 if ( @
$barcodes == 0 && $charges eq 'yes' ) {
232 borrowernumber
=> $borrowernumber
236 if ( $print eq 'yes' && $borrowernumber ne '' ) {
237 if ( C4
::Context
->boolean_preference('printcirculationslips') ) {
238 my $letter = IssueSlip
($branch, $borrowernumber, "QUICK");
239 NetworkPrint
($letter->{content
});
241 $query->param( 'borrowernumber', '' );
242 $borrowernumber = '';
247 # STEP 2 : FIND BORROWER
248 # if there is a list of find borrowers....
252 my $patron = Koha
::Patrons
->find( { cardnumber
=> $findborrower } );
254 $borrowernumber = $patron->borrowernumber;
256 my $dt_params = { iDisplayLength
=> -1 };
257 my $results = C4
::Utils
::DataTables
::Members
::search
(
259 searchmember
=> $findborrower,
260 searchtype
=> $searchtype,
261 dt_params
=> $dt_params,
264 my $borrowers = $results->{patrons
};
265 if ( scalar @
$borrowers == 1 ) {
266 $borrowernumber = $borrowers->[0]->{borrowernumber
};
267 $query->param( 'borrowernumber', $borrowernumber );
268 $query->param( 'barcode', '' );
269 } elsif ( @
$borrowers ) {
270 $template->param( borrowers
=> $borrowers );
272 $query->param( 'findborrower', '' );
273 $message = "'$findborrower'";
278 # get the borrower information.....
280 $patron ||= Koha
::Patrons
->find( $borrowernumber ) if $borrowernumber;
283 $template->param( borrowernumber
=> $patron->borrowernumber );
284 output_and_exit_if_error
( $query, $cookie, $template, { module
=> 'members', logged_in_user
=> $logged_in_user, current_patron
=> $patron } );
286 my $overdues = $patron->get_overdues;
287 my $issues = $patron->checkouts;
288 $balance = $patron->account->balance;
291 # if the expiry date is before today ie they have expired
292 if ( $patron->is_expired ) {
293 #borrowercard expired, no issues
295 noissues
=> ($force_allow_issue) ?
0 : "1",
296 forceallow
=> $force_allow_issue,
300 # check for NotifyBorrowerDeparture
301 elsif ( $patron->is_going_to_expire ) {
302 # borrower card soon to expire warn librarian
303 $template->param( "warndeparture" => $patron->dateexpiry ,
305 if (C4
::Context
->preference('ReturnBeforeExpiry')){
306 $template->param("returnbeforeexpiry" => 1);
310 overduecount
=> $overdues->count,
311 issuecount
=> $issues->count,
312 finetotal
=> $balance,
315 if ( $patron and $patron->is_debarred ) {
317 'userdebarred' => $patron->debarred,
318 'debarredcomment' => $patron->debarredcomment,
321 if ( $patron->debarred ne "9999-12-31" ) {
322 $template->param( 'userdebarreddate' => $patron->debarred );
326 # Calculate and display patron's age
327 if ( !$patron->is_valid_age ) {
328 $template->param( age_limitations
=> 1 );
329 $template->param( age_low
=> $patron->category->dateofbirthrequired );
330 $template->param( age_high
=> $patron->category->upperagelimit );
341 for my $barcode ( @
$barcodes ) {
343 my $template_params = {
345 onsite_checkout
=> $onsite_checkout,
348 # always check for blockers on issuing
349 my ( $error, $question, $alerts, $messages ) = CanBookBeIssued
(
355 onsite_checkout
=> $onsite_checkout,
356 override_high_holds
=> $override_high_holds || $override_high_holds_tmp || 0,
360 my $blocker = $invalidduedate ?
1 : 0;
362 $template_params->{alert
} = $alerts;
363 $template_params->{messages
} = $messages;
365 my $item = Koha
::Items
->find({ barcode
=> $barcode });
369 $biblio = $item->biblio;
372 # Fix for bug 7494: optional checkout-time fallback search for a book
374 if ( $error->{'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} ) {
390 TransformMarcToKoha
( C4
::Search
::new_record_from_zebra
('biblioserver',$hit) );
392 # offer all barcodes individually
393 if ( $chosen->{barcode
} ) {
394 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode
}) ) {
395 my %chosen_single = %{$chosen};
396 $chosen_single{barcode
} = $barcode;
397 push( @options, \
%chosen_single );
401 $template_params->{options
} = \
@options;
405 if ( $error->{UNKNOWN_BARCODE
} or not $onsite_checkout or not C4
::Context
->preference("OnSiteCheckoutsForce") ) {
406 delete $question->{'DEBT'} if ($debt_confirmed);
407 foreach my $impossible ( keys %$error ) {
408 $template_params->{$impossible} = $$error{$impossible};
409 $template_params->{IMPOSSIBLE
} = 1;
414 if( $item and ( !$blocker or $force_allow_issue ) ){
415 my $confirm_required = 0;
416 unless($issueconfirmed){
417 # Get the item title for more information
418 my $materials = $item->materials;
419 my $descriptions = Koha
::AuthorisedValues
->get_description_by_koha_field({ frameworkcode
=> $biblio->frameworkcode, kohafield
=> 'items.materials', authorised_value
=> $materials });
420 $materials = $descriptions->{lib
} // $materials;
421 $template_params->{additional_materials
} = $materials;
422 $template_params->{itemhomebranch
} = $item->homebranch;
424 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
425 foreach my $needsconfirmation ( keys %$question ) {
426 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
427 $template_params->{getTitleMessageIteminfo
} = $biblio->title;
428 $template_params->{getBarcodeMessageIteminfo
} = $item->barcode;
429 $template_params->{NEEDSCONFIRMATION
} = 1;
430 $template_params->{auto_renew
} = $session->param('auto_renew');
431 $confirm_required = 1;
434 unless($confirm_required) {
435 my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED
};
436 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, } );
437 $template_params->{issue
} = $issue;
438 $session->clear('auto_renew');
443 if ($question->{RESERVE_WAITING
} or $question->{RESERVED
}){
445 reserveborrowernumber
=> $question->{'resborrowernumber'}
450 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
451 $patron = Koha
::Patrons
->find( $borrowernumber );
452 $template_params->{issuecount
} = $patron->checkouts->count;
455 $template_params->{item
} = $item;
456 $template_params->{biblio
} = $biblio;
457 $template_params->{itembiblionumber
} = $biblio->biblionumber;
459 push @
$checkout_infos, $template_params;
462 $template->param( %{$checkout_infos->[0]} );
463 $template->param( barcode
=> $barcodes->[0] );
465 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION
} } @
$checkout_infos;
467 checkout_infos
=> $checkout_infos,
468 confirmation_needed
=> $confirmation_needed,
473 ##################################################################################
475 # show all reserves of this borrower, and the position of the reservation ....
477 my $holds = Koha
::Holds
->search( { borrowernumber
=> $borrowernumber } ); # FIXME must be Koha::Patron->holds
478 my $waiting_holds = $holds->waiting;
480 holds_count
=> $holds->count(),
481 WaitingHolds
=> $waiting_holds,
487 if ( $patron->gonenoaddress ) {
488 $template->param( gna
=> 1 );
491 if ( $patron->lost ) {
492 $template->param( lost
=> 1 );
495 if ( $patron->is_debarred ) {
496 $template->param( dbarred
=> 1 );
499 my $account = $patron->account;
500 if( ( my $owing = $account->non_issues_charges ) > 0 ) {
501 my $noissuescharge = C4
::Context
->preference("noissuescharge") || 5; # FIXME If noissuescharge == 0 then 5, why??
502 $noissues ||= ( not C4
::Context
->preference("AllowFineOverride") and ( $owing > $noissuescharge ) );
505 chargesamount
=> $owing,
507 } elsif ( $balance < 0 ) {
510 creditsamount
=> -$balance,
514 my $no_issues_charge_guarantees = C4
::Context
->preference("NoIssuesChargeGuarantees");
515 $no_issues_charge_guarantees = undef unless looks_like_number
( $no_issues_charge_guarantees );
516 if ( defined $no_issues_charge_guarantees ) {
517 my $guarantees_non_issues_charges = 0;
518 my $guarantees = $patron->guarantee_relationships->guarantees;
519 while ( my $g = $guarantees->next ) {
520 $guarantees_non_issues_charges += $g->account->non_issues_charges;
522 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
524 charges_guarantees
=> 1,
525 chargesamount_guarantees
=> $guarantees_non_issues_charges,
527 $noissues = 1 unless C4
::Context
->preference("allowfineoverride");
531 if ( $patron->has_overdues ) {
532 $template->param( odues
=> 1 );
535 if ( $patron->borrowernotes ) {
536 my $borrowernotes = $patron->borrowernotes;
537 $borrowernotes =~ s
#\n#<br />#g;
540 notesmsg
=> $borrowernotes,
546 noissues
=> ($force_allow_issue) ?
0 : 'true',
547 forceallow
=> $force_allow_issue,
552 my $messages = Koha
::Patron
::Messages
->search(
554 'me.borrowernumber' => $borrowernumber,
558 '+select' => ['manager.surname', 'manager.firstname' ],
559 '+as' => ['manager_surname', 'manager_firstname'],
563 my $fast_cataloging = 0;
564 if ( Koha
::BiblioFrameworks
->find('FA') ) {
569 ?
'batch_checkout_view'
574 if ( my @guarantors = $patron->guarantor_relationships()->guarantors() ) {
575 push( @relatives, $_->id ) for @guarantors;
576 push( @relatives, $_->id ) for $patron->siblings();
578 push( @relatives, $_->id ) for $patron->guarantee_relationships()->guarantees();
581 my $relatives_issues_count =
582 Koha
::Database
->new()->schema()->resultset('Issue')
583 ->count( { borrowernumber
=> \
@relatives } );
586 my $av = Koha
::AuthorisedValues
->search({ category
=> 'ROADTYPE', authorised_value
=> $patron->streettype });
587 my $roadtype = $av->count ?
$av->next->lib : '';
589 roadtype
=> $roadtype,
591 categoryname
=> $patron->category->description,
592 expiry
=> $patron->dateexpiry,
596 # Restore date if changed by holds and/or save stickyduedate to session
597 if ($restoreduedatespec || $stickyduedate) {
598 $duedatespec = $restoreduedatespec || $duedatespec;
600 if ($stickyduedate) {
601 $session->param( 'stickyduedate', $duedatespec );
603 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
608 messages
=> $messages,
609 borrowernumber
=> $borrowernumber,
611 was_renewed
=> scalar $query->param('was_renewed') ?
1 : 0,
612 barcodes
=> $barcodes,
613 stickyduedate
=> $stickyduedate,
614 duedatespec
=> $duedatespec,
615 restoreduedatespec
=> $restoreduedatespec,
617 totaldue
=> sprintf('%.2f', $balance), # FIXME not used in template?
618 inprocess
=> $inprocess,
620 batch_allowed
=> $batch_allowed,
622 AudioAlerts
=> C4
::Context
->preference("AudioAlerts"),
623 fast_cataloging
=> $fast_cataloging,
624 CircAutoPrintQuickSlip
=> C4
::Context
->preference("CircAutoPrintQuickSlip"),
625 RoutingSerials
=> C4
::Context
->preference('RoutingSerials'),
626 relatives_issues_count
=> $relatives_issues_count,
627 relatives_borrowernumbers
=> \
@relatives,
631 if ( C4
::Context
->preference("ExportCircHistory") ) {
632 $template->param(csv_profiles
=> [ Koha
::CsvProfiles
->search({ type
=> 'marc' }) ]);
635 my $has_modifications = Koha
::Patron
::Modifications
->search( { borrowernumber
=> $borrowernumber } )->count;
637 debt_confirmed
=> $debt_confirmed,
638 SpecifyDueDate
=> $duedatespec_allow,
639 CircAutocompl
=> C4
::Context
->preference("CircAutocompl"),
640 debarments
=> scalar GetDebarments
({ borrowernumber
=> $borrowernumber }),
641 todaysdate
=> output_pref
( { dt
=> dt_from_string
()->set(hour
=> 23)->set(minute
=> 59), dateformat
=> 'sql' } ),
642 has_modifications
=> $has_modifications,
643 override_high_holds
=> $override_high_holds,
644 nopermission
=> scalar $query->param('nopermission'),
645 autoswitched
=> $autoswitched,
648 output_html_with_http_headers
$query, $cookie, $template->output;