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 );
33 use C4
::Auth qw
/:DEFAULT get_session haspermission/;
36 use C4
::Utils
::DataTables
::Members
;
45 use Koha
::AuthorisedValues
;
46 use Koha
::CsvProfiles
;
48 use Koha
::Patron
::Debarments
qw(GetDebarments);
51 use Koha
::BiblioFrameworks
;
53 use Koha
::Patron
::Messages
;
54 use Koha
::SearchEngine
;
55 use Koha
::SearchEngine
::Search
;
56 use Koha
::Patron
::Modifications
;
63 use List
::MoreUtils qw
/uniq/;
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);
77 my $barcode = $query->param('barcode');
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;
86 undef $borrowernumber;
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 ];
97 my $filefh = $query->upload('uploadfile');
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 ];
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 ) {
128 my ( $template, $loggedinuser, $cookie ) = get_template_and_user
(
130 template_name
=> $template_name,
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' }); }
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
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'));
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 ) };
210 $template->param( IMPOSSIBLE
=>1, INVALID_DATE
=>$duedatespec );
215 my $inprocess = (@
$barcodes == 0) ?
'' : $query->param('inprocess');
216 if ( @
$barcodes == 0 && $charges eq 'yes' ) {
219 borrowernumber
=> $borrowernumber
224 # STEP 2 : FIND BORROWER
225 # if there is a list of find borrowers....
229 my $patron = Koha
::Patrons
->find( { cardnumber
=> $findborrower } );
231 $borrowernumber = $patron->borrowernumber;
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 );
249 $query->param( 'findborrower', '' );
250 $message = "'$findborrower'";
255 # get the borrower information.....
257 $patron ||= Koha
::Patrons
->find( $borrowernumber ) if $borrowernumber;
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
272 noissues
=> ($force_allow_issue) ?
0 : "1",
273 forceallow
=> $force_allow_issue,
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);
287 overduecount
=> $overdues->count,
288 issuecount
=> $issues->count,
289 finetotal
=> $balance,
292 if ( $patron and $patron->is_debarred ) {
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 );
318 for my $barcode ( @
$barcodes ) {
320 my $template_params = {
322 onsite_checkout
=> $onsite_checkout,
325 # always check for blockers on issuing
326 my ( $error, $question, $alerts, $messages ) = CanBookBeIssued
(
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 });
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")
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 ) {
365 foreach my $hit ( @
{$results} ) {
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->{DEBT_GUARANTORS
} ) {
383 $template_params->{DEBT_GUARANTORS
} = $error->{DEBT_GUARANTORS
};
384 $template_params->{IMPOSSIBLE
} = 1;
388 if ( $error->{UNKNOWN_BARCODE
} or not $onsite_checkout or not C4
::Context
->preference("OnSiteCheckoutsForce") ) {
389 delete $question->{'DEBT'} if ($debt_confirmed);
390 foreach my $impossible ( keys %$error ) {
391 $template_params->{$impossible} = $$error{$impossible};
392 $template_params->{IMPOSSIBLE
} = 1;
397 if( $item and ( !$blocker or $force_allow_issue ) ){
398 my $confirm_required = 0;
399 unless($issueconfirmed){
400 # Get the item title for more information
401 my $materials = $item->materials;
402 my $descriptions = Koha
::AuthorisedValues
->get_description_by_koha_field({ frameworkcode
=> $biblio->frameworkcode, kohafield
=> 'items.materials', authorised_value
=> $materials });
403 $materials = $descriptions->{lib
} // $materials;
404 $template_params->{ADDITIONAL_MATERIALS
} = $materials;
405 $template_params->{itemhomebranch
} = $item->homebranch;
407 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
408 foreach my $needsconfirmation ( keys %$question ) {
409 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
410 $template_params->{getTitleMessageIteminfo
} = $biblio->title;
411 $template_params->{getBarcodeMessageIteminfo
} = $item->barcode;
412 $template_params->{NEEDSCONFIRMATION
} = 1;
413 $confirm_required = 1;
416 unless($confirm_required) {
417 my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED
};
418 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, } );
419 $template_params->{issue
} = $issue;
420 $session->clear('auto_renew');
425 if ($question->{RESERVE_WAITING
} or $question->{RESERVED
}){
427 reserveborrowernumber
=> $question->{'resborrowernumber'},
428 reserve_id
=> $question->{reserve_id
},
433 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
434 $patron = Koha
::Patrons
->find( $borrowernumber );
435 $template_params->{issuecount
} = $patron->checkouts->count;
438 $template_params->{item
} = $item;
439 $template_params->{biblio
} = $biblio;
440 $template_params->{itembiblionumber
} = $biblio->biblionumber;
442 push @
$checkout_infos, $template_params;
445 $template->param( %{$checkout_infos->[0]} );
446 $template->param( barcode
=> $barcodes->[0] );
448 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION
} } @
$checkout_infos;
450 checkout_infos
=> $checkout_infos,
451 confirmation_needed
=> $confirmation_needed,
456 ##################################################################################
458 # show all reserves of this borrower, and the position of the reservation ....
460 my $holds = Koha
::Holds
->search( { borrowernumber
=> $borrowernumber } ); # FIXME must be Koha::Patron->holds
461 my $waiting_holds = $holds->waiting;
463 holds_count
=> $holds->count(),
464 WaitingHolds
=> $waiting_holds,
470 if ( $patron->gonenoaddress ) {
471 $template->param( gna
=> 1 );
474 if ( $patron->lost ) {
475 $template->param( lost
=> 1 );
478 if ( $patron->is_debarred ) {
479 $template->param( dbarred
=> 1 );
482 my $account = $patron->account;
483 if( ( my $owing = $account->non_issues_charges ) > 0 ) {
484 my $noissuescharge = C4
::Context
->preference("noissuescharge") || 5; # FIXME If noissuescharge == 0 then 5, why??
485 $noissues ||= ( not C4
::Context
->preference("AllowFineOverride") and ( $owing > $noissuescharge ) );
488 chargesamount
=> $owing,
490 } elsif ( $balance < 0 ) {
493 creditsamount
=> -$balance,
497 # Check the debt of this patrons guarantors *and* the guarantees of those guarantors
498 my $no_issues_charge_guarantors = C4
::Context
->preference("NoIssuesChargeGuarantorsWithGuarantees");
499 if ( $no_issues_charge_guarantors ) {
500 my $guarantors_non_issues_charges += $patron->relationships_debt({ include_guarantors
=> 1, only_this_guarantor
=> 0, include_this_patron
=> 1 });
502 if ( $guarantors_non_issues_charges > $no_issues_charge_guarantors ) {
504 charges_guarantors_guarantees
=> $guarantors_non_issues_charges
506 $noissues = 1 unless C4
::Context
->preference("allowfineoverride");
510 my $no_issues_charge_guarantees = C4
::Context
->preference("NoIssuesChargeGuarantees");
511 $no_issues_charge_guarantees = undef unless looks_like_number
( $no_issues_charge_guarantees );
512 if ( defined $no_issues_charge_guarantees ) {
513 my $guarantees_non_issues_charges = 0;
514 my $guarantees = $patron->guarantee_relationships->guarantees;
515 while ( my $g = $guarantees->next ) {
516 $guarantees_non_issues_charges += $g->account->non_issues_charges;
518 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
520 charges_guarantees
=> 1,
521 chargesamount_guarantees
=> $guarantees_non_issues_charges,
523 $noissues = 1 unless C4
::Context
->preference("allowfineoverride");
527 if ( $patron->has_overdues ) {
528 $template->param( odues
=> 1 );
531 if ( $patron->borrowernotes ) {
532 my $borrowernotes = $patron->borrowernotes;
533 $borrowernotes =~ s
#\n#<br />#g;
536 notesmsg
=> $borrowernotes,
542 noissues
=> ($force_allow_issue) ?
0 : 'true',
543 forceallow
=> $force_allow_issue,
548 my $messages = Koha
::Patron
::Messages
->search(
550 'me.borrowernumber' => $borrowernumber,
554 '+select' => ['manager.surname', 'manager.firstname' ],
555 '+as' => ['manager_surname', 'manager_firstname'],
559 my $fast_cataloging = 0;
560 if ( Koha
::BiblioFrameworks
->find('FA') ) {
565 ?
'batch_checkout_view'
570 if ( my @guarantors = $patron->guarantor_relationships()->guarantors() ) {
571 push( @relatives, $_->id ) for @guarantors;
572 push( @relatives, $_->id ) for $patron->siblings();
574 push( @relatives, $_->id ) for $patron->guarantee_relationships()->guarantees();
577 my $relatives_issues_count =
578 Koha
::Database
->new()->schema()->resultset('Issue')
579 ->count( { borrowernumber
=> \
@relatives } );
582 my $av = Koha
::AuthorisedValues
->search({ category
=> 'ROADTYPE', authorised_value
=> $patron->streettype });
583 my $roadtype = $av->count ?
$av->next->lib : '';
585 roadtype
=> $roadtype,
587 categoryname
=> $patron->category->description,
588 expiry
=> $patron->dateexpiry,
592 # Restore date if changed by holds and/or save stickyduedate to session
593 if ($restoreduedatespec || $stickyduedate) {
594 $duedatespec = $restoreduedatespec || $duedatespec;
596 if ($stickyduedate) {
597 $session->param( 'stickyduedate', $duedatespec );
599 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
604 messages
=> $messages,
605 borrowernumber
=> $borrowernumber,
607 was_renewed
=> scalar $query->param('was_renewed') ?
1 : 0,
608 barcodes
=> $barcodes,
609 stickyduedate
=> $stickyduedate,
610 duedatespec
=> $duedatespec,
611 restoreduedatespec
=> $restoreduedatespec,
613 totaldue
=> sprintf('%.2f', $balance), # FIXME not used in template?
614 inprocess
=> $inprocess,
616 batch_allowed
=> $batch_allowed,
618 AudioAlerts
=> C4
::Context
->preference("AudioAlerts"),
619 fast_cataloging
=> $fast_cataloging,
620 CircAutoPrintQuickSlip
=> C4
::Context
->preference("CircAutoPrintQuickSlip"),
621 RoutingSerials
=> C4
::Context
->preference('RoutingSerials'),
622 relatives_issues_count
=> $relatives_issues_count,
623 relatives_borrowernumbers
=> \
@relatives,
627 if ( C4
::Context
->preference("ExportCircHistory") ) {
628 $template->param(csv_profiles
=> [ Koha
::CsvProfiles
->search({ type
=> 'marc' }) ]);
631 my $has_modifications = Koha
::Patron
::Modifications
->search( { borrowernumber
=> $borrowernumber } )->count;
633 debt_confirmed
=> $debt_confirmed,
634 SpecifyDueDate
=> $duedatespec_allow,
635 PatronAutoComplete
=> C4
::Context
->preference("PatronAutoComplete"),
636 debarments
=> scalar GetDebarments
({ borrowernumber
=> $borrowernumber }),
637 todaysdate
=> output_pref
( { dt
=> dt_from_string
()->set(hour
=> 23)->set(minute
=> 59), dateformat
=> 'sql' } ),
638 has_modifications
=> $has_modifications,
639 override_high_holds
=> $override_high_holds,
640 nopermission
=> scalar $query->param('nopermission'),
641 autoswitched
=> $autoswitched,
642 logged_in_user
=> $logged_in_user,
645 output_html_with_http_headers
$query, $cookie, $template->output;