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);
78 my $barcode = $query->param('barcode');
81 my $borrowernumber = $query->param('borrowernumber');
83 if (C4
::Context
->preference("AutoSwitchPatron") && $barcode) {
84 if (Koha
::Patrons
->search( { cardnumber
=> $barcode} )->count() > 0) {
85 $findborrower = $barcode;
87 undef $borrowernumber;
91 $findborrower ||= $query->param('findborrower') || q{};
92 $findborrower =~ s
|,| |g
;
94 # Barcode given by user could be '0'
95 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
96 $barcodes = [ $barcode ];
98 my $filefh = $query->upload('uploadfile');
100 while ( my $content = <$filefh> ) {
101 $content =~ s/[\r\n]*$//g;
102 push @
$barcodes, $content if $content;
104 } elsif ( my $list = $query->param('barcodelist') ) {
105 push @
$barcodes, split( /\s\n/, $list );
106 $barcodes = [ map { $_ =~ /^\s*$/ ?
() : $_ } @
$barcodes ];
108 @
$barcodes = $query->multi_param('barcodes');
112 $barcodes = [ uniq @
$barcodes ];
114 my $template_name = q
|circ
/circulation
.tt
|;
115 my $patron = $borrowernumber ? Koha
::Patrons
->find( $borrowernumber ) : undef;
116 my $batch = $query->param('batch');
117 my $batch_allowed = 0;
118 if ( $batch && C4
::Context
->preference('BatchCheckouts') ) {
119 $template_name = q
|circ
/circulation_batch_checkouts
.tt
|;
120 my @batch_category_codes = split '\|', C4
::Context
->preference('BatchCheckoutsValidCategories');
121 my $categorycode = $patron->categorycode;
122 if ( $categorycode && grep { $_ eq $categorycode } @batch_category_codes ) {
129 my ( $template, $loggedinuser, $cookie ) = get_template_and_user
(
131 template_name
=> $template_name,
134 authnotrequired
=> 0,
135 flagsrequired
=> { circulate
=> 'circulate_remaining_permissions' },
138 my $logged_in_user = Koha
::Patrons
->find( $loggedinuser );
140 my $force_allow_issue = $query->param('forceallow') || 0;
141 if (!C4
::Auth
::haspermission
( C4
::Context
->userenv->{id
} , { circulate
=> 'force_checkout' } )) {
142 $force_allow_issue = 0;
144 my $onsite_checkout = $query->param('onsite_checkout');
146 if (C4
::Context
->preference("OnSiteCheckoutAutoCheck") && $onsite_checkout eq "on") {
147 $template->param(onsite_checkout
=> $onsite_checkout);
150 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
151 our %renew_failed = ();
152 for (@failedrenews) { $renew_failed{$_} = 1; }
154 my @failedreturns = $query->multi_param('failedreturn');
155 our %return_failed = ();
156 for (@failedreturns) { $return_failed{$_} = 1; }
158 my $searchtype = $query->param('searchtype') || q{contain};
160 my $branch = C4
::Context
->userenv->{'branch'};
162 if (C4
::Context
->preference("DisplayClearScreenButton")) {
163 $template->param(DisplayClearScreenButton
=> 1);
166 for my $barcode ( @
$barcodes ) {
167 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
168 $barcode = barcodedecode
($barcode)
169 if( $barcode && C4
::Context
->preference('itemBarcodeInputFilter'));
172 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
173 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
174 $duedatespec = eval { output_pref
( { dt
=> dt_from_string
( $duedatespec ), dateformat
=> 'iso', timeformat
=> '24hr' }); }
176 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
177 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
178 undef $restoreduedatespec;
180 my $issueconfirmed = $query->param('issueconfirmed');
181 my $cancelreserve = $query->param('cancelreserve');
182 my $print = $query->param('print') || q{};
183 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
184 my $charges = $query->param('charges') || q{};
186 # Check if stickyduedate is turned off
188 # was stickyduedate loaded from session?
189 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
190 $session->clear( 'stickyduedate' );
191 $stickyduedate = $query->param('stickyduedate');
192 $duedatespec = $query->param('duedatespec');
194 $session->param('auto_renew', scalar $query->param('auto_renew'));
197 $session->clear('auto_renew');
200 $template->param( auto_renew
=> $session->param('auto_renew') );
202 my ($datedue,$invalidduedate);
204 my $duedatespec_allow = C4
::Context
->preference('SpecifyDueDate');
205 if( $onsite_checkout && !$duedatespec_allow ) {
206 $datedue = output_pref
({ dt
=> dt_from_string
, dateonly
=> 1, dateformat
=> 'iso' });
207 $datedue .= ' 23:59:00';
208 } elsif( $duedatespec_allow ) {
209 if ( $duedatespec ) {
210 $datedue = eval { dt_from_string
( $duedatespec ) };
213 $template->param( IMPOSSIBLE
=>1, INVALID_DATE
=>$duedatespec );
218 # check and see if we should print
219 if ( @
$barcodes == 0 && $print eq 'maybe' ) {
223 my $inprocess = (@
$barcodes == 0) ?
'' : $query->param('inprocess');
224 if ( @
$barcodes == 0 && $charges eq 'yes' ) {
227 borrowernumber
=> $borrowernumber
231 if ( $print eq 'yes' && $borrowernumber ne '' ) {
232 if ( C4
::Context
->boolean_preference('printcirculationslips') ) {
233 my $letter = IssueSlip
($branch, $borrowernumber, "QUICK");
234 NetworkPrint
($letter->{content
});
236 $query->param( 'borrowernumber', '' );
237 $borrowernumber = '';
242 # STEP 2 : FIND BORROWER
243 # if there is a list of find borrowers....
247 my $patron = Koha
::Patrons
->find( { cardnumber
=> $findborrower } );
249 $borrowernumber = $patron->borrowernumber;
251 my $dt_params = { iDisplayLength
=> -1 };
252 my $results = C4
::Utils
::DataTables
::Members
::search
(
254 searchmember
=> $findborrower,
255 searchtype
=> $searchtype,
256 dt_params
=> $dt_params,
259 my $borrowers = $results->{patrons
};
260 if ( scalar @
$borrowers == 1 ) {
261 $borrowernumber = $borrowers->[0]->{borrowernumber
};
262 $query->param( 'borrowernumber', $borrowernumber );
263 $query->param( 'barcode', '' );
264 } elsif ( @
$borrowers ) {
265 $template->param( borrowers
=> $borrowers );
267 $query->param( 'findborrower', '' );
268 $message = "'$findborrower'";
273 # get the borrower information.....
275 $patron ||= Koha
::Patrons
->find( $borrowernumber ) if $borrowernumber;
278 $template->param( borrowernumber
=> $patron->borrowernumber );
279 output_and_exit_if_error
( $query, $cookie, $template, { module
=> 'members', logged_in_user
=> $logged_in_user, current_patron
=> $patron } );
281 my $overdues = $patron->get_overdues;
282 my $issues = $patron->checkouts;
283 $balance = $patron->account->balance;
286 # if the expiry date is before today ie they have expired
287 if ( $patron->is_expired ) {
288 #borrowercard expired, no issues
290 noissues
=> ($force_allow_issue) ?
0 : "1",
291 forceallow
=> $force_allow_issue,
295 # check for NotifyBorrowerDeparture
296 elsif ( $patron->is_going_to_expire ) {
297 # borrower card soon to expire warn librarian
298 $template->param( "warndeparture" => $patron->dateexpiry ,
300 if (C4
::Context
->preference('ReturnBeforeExpiry')){
301 $template->param("returnbeforeexpiry" => 1);
305 overduecount
=> $overdues->count,
306 issuecount
=> $issues->count,
307 finetotal
=> $balance,
310 if ( $patron and $patron->is_debarred ) {
312 'userdebarred' => $patron->debarred,
313 'debarredcomment' => $patron->debarredcomment,
316 if ( $patron->debarred ne "9999-12-31" ) {
317 $template->param( 'userdebarreddate' => $patron->debarred );
321 # Calculate and display patron's age
322 if ( !$patron->is_valid_age ) {
323 $template->param( age_limitations
=> 1 );
324 $template->param( age_low
=> $patron->category->dateofbirthrequired );
325 $template->param( age_high
=> $patron->category->upperagelimit );
336 for my $barcode ( @
$barcodes ) {
338 my $template_params = {
340 onsite_checkout
=> $onsite_checkout,
343 # always check for blockers on issuing
344 my ( $error, $question, $alerts, $messages ) = CanBookBeIssued
(
350 onsite_checkout
=> $onsite_checkout,
351 override_high_holds
=> $override_high_holds || $override_high_holds_tmp || 0,
355 my $blocker = $invalidduedate ?
1 : 0;
357 $template_params->{alert
} = $alerts;
358 $template_params->{messages
} = $messages;
360 my $item = Koha
::Items
->find({ barcode
=> $barcode });
364 $biblio = $item->biblio;
367 # Fix for bug 7494: optional checkout-time fallback search for a book
369 if ( $error->{'UNKNOWN_BARCODE'}
370 && C4
::Context
->preference("itemBarcodeFallbackSearch")
374 $template_params->{FALLBACK
} = 1;
376 my $searcher = Koha
::SearchEngine
::Search
->new({index => $Koha::SearchEngine
::BIBLIOS_INDEX
});
377 my $query = "kw=" . $barcode;
378 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
380 # if multiple hits, offer options to librarian
381 if ( $total_hits > 0 ) {
383 foreach my $hit ( @
{$results} ) {
385 TransformMarcToKoha
( C4
::Search
::new_record_from_zebra
('biblioserver',$hit) );
387 # offer all barcodes individually
388 if ( $chosen->{barcode
} ) {
389 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode
}) ) {
390 my %chosen_single = %{$chosen};
391 $chosen_single{barcode
} = $barcode;
392 push( @options, \
%chosen_single );
396 $template_params->{options
} = \
@options;
400 if ( $error->{UNKNOWN_BARCODE
} or not $onsite_checkout or not C4
::Context
->preference("OnSiteCheckoutsForce") ) {
401 delete $question->{'DEBT'} if ($debt_confirmed);
402 foreach my $impossible ( keys %$error ) {
403 $template_params->{$impossible} = $$error{$impossible};
404 $template_params->{IMPOSSIBLE
} = 1;
409 if( $item and ( !$blocker or $force_allow_issue ) ){
410 my $confirm_required = 0;
411 unless($issueconfirmed){
412 # Get the item title for more information
413 my $materials = $item->materials;
414 my $descriptions = Koha
::AuthorisedValues
->get_description_by_koha_field({ frameworkcode
=> $biblio->frameworkcode, kohafield
=> 'items.materials', authorised_value
=> $materials });
415 $materials = $descriptions->{lib
} // $materials;
416 $template_params->{additional_materials
} = $materials;
417 $template_params->{itemhomebranch
} = $item->homebranch;
419 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
420 foreach my $needsconfirmation ( keys %$question ) {
421 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
422 $template_params->{getTitleMessageIteminfo
} = $biblio->title;
423 $template_params->{getBarcodeMessageIteminfo
} = $item->barcode;
424 $template_params->{NEEDSCONFIRMATION
} = 1;
425 $confirm_required = 1;
428 unless($confirm_required) {
429 my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED
};
430 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, } );
431 $template_params->{issue
} = $issue;
432 $session->clear('auto_renew');
437 if ($question->{RESERVE_WAITING
} or $question->{RESERVED
}){
439 reserveborrowernumber
=> $question->{'resborrowernumber'}
444 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
445 $patron = Koha
::Patrons
->find( $borrowernumber );
446 $template_params->{issuecount
} = $patron->checkouts->count;
449 $template_params->{item
} = $item;
450 $template_params->{biblio
} = $biblio;
451 $template_params->{itembiblionumber
} = $biblio->biblionumber;
453 push @
$checkout_infos, $template_params;
456 $template->param( %{$checkout_infos->[0]} );
457 $template->param( barcode
=> $barcodes->[0] );
459 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION
} } @
$checkout_infos;
461 checkout_infos
=> $checkout_infos,
462 confirmation_needed
=> $confirmation_needed,
467 ##################################################################################
469 # show all reserves of this borrower, and the position of the reservation ....
471 my $holds = Koha
::Holds
->search( { borrowernumber
=> $borrowernumber } ); # FIXME must be Koha::Patron->holds
472 my $waiting_holds = $holds->waiting;
474 holds_count
=> $holds->count(),
475 WaitingHolds
=> $waiting_holds,
481 if ( $patron->gonenoaddress ) {
482 $template->param( gna
=> 1 );
485 if ( $patron->lost ) {
486 $template->param( lost
=> 1 );
489 if ( $patron->is_debarred ) {
490 $template->param( dbarred
=> 1 );
493 my $account = $patron->account;
494 if( ( my $owing = $account->non_issues_charges ) > 0 ) {
495 my $noissuescharge = C4
::Context
->preference("noissuescharge") || 5; # FIXME If noissuescharge == 0 then 5, why??
496 $noissues ||= ( not C4
::Context
->preference("AllowFineOverride") and ( $owing > $noissuescharge ) );
499 chargesamount
=> $owing,
501 } elsif ( $balance < 0 ) {
504 creditsamount
=> -$balance,
508 my $no_issues_charge_guarantees = C4
::Context
->preference("NoIssuesChargeGuarantees");
509 $no_issues_charge_guarantees = undef unless looks_like_number
( $no_issues_charge_guarantees );
510 if ( defined $no_issues_charge_guarantees ) {
511 my $guarantees_non_issues_charges = 0;
512 my $guarantees = $patron->guarantee_relationships->guarantees;
513 while ( my $g = $guarantees->next ) {
514 $guarantees_non_issues_charges += $g->account->non_issues_charges;
516 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
518 charges_guarantees
=> 1,
519 chargesamount_guarantees
=> $guarantees_non_issues_charges,
521 $noissues = 1 unless C4
::Context
->preference("allowfineoverride");
525 if ( $patron->has_overdues ) {
526 $template->param( odues
=> 1 );
529 if ( $patron->borrowernotes ) {
530 my $borrowernotes = $patron->borrowernotes;
531 $borrowernotes =~ s
#\n#<br />#g;
534 notesmsg
=> $borrowernotes,
540 noissues
=> ($force_allow_issue) ?
0 : 'true',
541 forceallow
=> $force_allow_issue,
546 my $messages = Koha
::Patron
::Messages
->search(
548 'me.borrowernumber' => $borrowernumber,
552 '+select' => ['manager.surname', 'manager.firstname' ],
553 '+as' => ['manager_surname', 'manager_firstname'],
557 my $fast_cataloging = 0;
558 if ( Koha
::BiblioFrameworks
->find('FA') ) {
563 ?
'batch_checkout_view'
568 if ( my @guarantors = $patron->guarantor_relationships()->guarantors() ) {
569 push( @relatives, $_->id ) for @guarantors;
570 push( @relatives, $_->id ) for $patron->siblings();
572 push( @relatives, $_->id ) for $patron->guarantee_relationships()->guarantees();
575 my $relatives_issues_count =
576 Koha
::Database
->new()->schema()->resultset('Issue')
577 ->count( { borrowernumber
=> \
@relatives } );
580 my $av = Koha
::AuthorisedValues
->search({ category
=> 'ROADTYPE', authorised_value
=> $patron->streettype });
581 my $roadtype = $av->count ?
$av->next->lib : '';
583 roadtype
=> $roadtype,
585 categoryname
=> $patron->category->description,
586 expiry
=> $patron->dateexpiry,
590 # Restore date if changed by holds and/or save stickyduedate to session
591 if ($restoreduedatespec || $stickyduedate) {
592 $duedatespec = $restoreduedatespec || $duedatespec;
594 if ($stickyduedate) {
595 $session->param( 'stickyduedate', $duedatespec );
597 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
602 messages
=> $messages,
603 borrowernumber
=> $borrowernumber,
605 was_renewed
=> scalar $query->param('was_renewed') ?
1 : 0,
606 barcodes
=> $barcodes,
607 stickyduedate
=> $stickyduedate,
608 duedatespec
=> $duedatespec,
609 restoreduedatespec
=> $restoreduedatespec,
611 totaldue
=> sprintf('%.2f', $balance), # FIXME not used in template?
612 inprocess
=> $inprocess,
614 batch_allowed
=> $batch_allowed,
616 AudioAlerts
=> C4
::Context
->preference("AudioAlerts"),
617 fast_cataloging
=> $fast_cataloging,
618 CircAutoPrintQuickSlip
=> C4
::Context
->preference("CircAutoPrintQuickSlip"),
619 RoutingSerials
=> C4
::Context
->preference('RoutingSerials'),
620 relatives_issues_count
=> $relatives_issues_count,
621 relatives_borrowernumbers
=> \
@relatives,
625 if ( C4
::Context
->preference("ExportCircHistory") ) {
626 $template->param(csv_profiles
=> [ Koha
::CsvProfiles
->search({ type
=> 'marc' }) ]);
629 my $has_modifications = Koha
::Patron
::Modifications
->search( { borrowernumber
=> $borrowernumber } )->count;
631 debt_confirmed
=> $debt_confirmed,
632 SpecifyDueDate
=> $duedatespec_allow,
633 PatronAutoComplete
=> C4
::Context
->preference("PatronAutoComplete"),
634 debarments
=> scalar GetDebarments
({ borrowernumber
=> $borrowernumber }),
635 todaysdate
=> output_pref
( { dt
=> dt_from_string
()->set(hour
=> 23)->set(minute
=> 59), dateformat
=> 'sql' } ),
636 has_modifications
=> $has_modifications,
637 override_high_holds
=> $override_high_holds,
638 nopermission
=> scalar $query->param('nopermission'),
639 autoswitched
=> $autoswitched,
640 logged_in_user
=> $logged_in_user,
643 output_html_with_http_headers
$query, $cookie, $template->output;