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;
33 use C4::Auth qw/:DEFAULT get_session haspermission/;
34 use C4::Koha; # GetPrinter
36 use C4::Utils::DataTables::Members;
45 use C4::Members::Attributes qw(GetBorrowerAttributes);
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');
87 if (C4::Context->preference("AutoSwitchPatron") && $barcode) {
88 if (Koha::Patrons->search( { cardnumber => $barcode} )->count() > 0) {
89 print $query->redirect("/cgi-bin/koha/circ/circulation.pl?findborrower=".$barcode);
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 $borrowernumber = $query->param('borrowernumber');
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 {/^$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 ) or die "Not logged in";
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;
145 my $onsite_checkout = $query->param('onsite_checkout');
147 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
148 our %renew_failed = ();
149 for (@failedrenews) { $renew_failed{$_} = 1; }
151 my @failedreturns = $query->multi_param('failedreturn');
152 our %return_failed = ();
153 for (@failedreturns) { $return_failed{$_} = 1; }
155 my $searchtype = $query->param('searchtype') || q{contain};
157 my $findborrower = $query->param('findborrower') || q{};
158 $findborrower =~ s|,| |g;
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 my ($datedue,$invalidduedate);
202 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
203 if( $onsite_checkout && !$duedatespec_allow ) {
204 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
205 $datedue .= ' 23:59:00';
206 } elsif( $duedatespec_allow ) {
207 if ( $duedatespec ) {
208 $datedue = eval { dt_from_string( $duedatespec ) };
211 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
216 # check and see if we should print
217 if ( @$barcodes == 0 && $print eq 'maybe' ) {
221 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
222 if ( @$barcodes == 0 && $charges eq 'yes' ) {
225 borrowernumber => $borrowernumber
229 if ( $print eq 'yes' && $borrowernumber ne '' ) {
230 if ( C4::Context->boolean_preference('printcirculationslips') ) {
231 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
232 NetworkPrint($letter->{content});
234 $query->param( 'borrowernumber', '' );
235 $borrowernumber = '';
239 # STEP 2 : FIND BORROWER
240 # if there is a list of find borrowers....
244 my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
246 $borrowernumber = $patron->borrowernumber;
248 my $dt_params = { iDisplayLength => -1 };
249 my $results = C4::Utils::DataTables::Members::search(
251 searchmember => $findborrower,
252 searchtype => $searchtype,
253 dt_params => $dt_params,
256 my $borrowers = $results->{patrons};
257 if ( scalar @$borrowers == 1 ) {
258 $borrowernumber = $borrowers->[0]->{borrowernumber};
259 $query->param( 'borrowernumber', $borrowernumber );
260 $query->param( 'barcode', '' );
261 } elsif ( @$borrowers ) {
262 $template->param( borrowers => $borrowers );
264 $query->param( 'findborrower', '' );
265 $message = "'$findborrower'";
270 # get the borrower information.....
271 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
274 $template->param( borrowernumber => $patron->borrowernumber );
275 output_and_exit_if_error( $query, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
277 my $overdues = $patron->get_overdues;
278 my $issues = $patron->checkouts;
279 my $balance = $patron->account->balance;
282 # if the expiry date is before today ie they have expired
283 if ( $patron->is_expired ) {
284 #borrowercard expired, no issues
286 noissues => ($force_allow_issue) ? 0 : "1",
287 forceallow => $force_allow_issue,
291 # check for NotifyBorrowerDeparture
292 elsif ( $patron->is_going_to_expire ) {
293 # borrower card soon to expire warn librarian
294 $template->param( "warndeparture" => $patron->dateexpiry ,
296 if (C4::Context->preference('ReturnBeforeExpiry')){
297 $template->param("returnbeforeexpiry" => 1);
301 overduecount => $overdues->count,
302 issuecount => $issues->count,
303 finetotal => $balance,
306 if ( $patron and $patron->is_debarred ) {
308 'userdebarred' => $patron->debarred,
309 'debarredcomment' => $patron->debarredcomment,
312 if ( $patron->debarred ne "9999-12-31" ) {
313 $template->param( 'userdebarreddate' => $patron->debarred );
325 for my $barcode ( @$barcodes ) {
326 my $template_params = { barcode => $barcode };
327 # always check for blockers on issuing
328 my ( $error, $question, $alerts, $messages ) = CanBookBeIssued(
334 onsite_checkout => $onsite_checkout,
335 override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
339 my $blocker = $invalidduedate ? 1 : 0;
341 $template_params->{alert} = $alerts;
342 $template_params->{messages} = $messages;
344 my $item = Koha::Items->find({ barcode => $barcode });
345 my ( $biblio, $mss );
348 $biblio = $item->biblio;
349 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.notforloan', authorised_value => { not => undef } });
350 $template_params->{authvalcode_notforloan} = $mss->count ? $mss->next->authorised_value : undef;
353 # Fix for bug 7494: optional checkout-time fallback search for a book
355 if ( $error->{'UNKNOWN_BARCODE'}
356 && C4::Context->preference("itemBarcodeFallbackSearch")
360 $template_params->{FALLBACK} = 1;
362 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
363 my $query = "kw=" . $barcode;
364 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
366 # if multiple hits, offer options to librarian
367 if ( $total_hits > 0 ) {
369 foreach my $hit ( @{$results} ) {
371 TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
373 # offer all barcodes individually
374 if ( $chosen->{barcode} ) {
375 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
376 my %chosen_single = %{$chosen};
377 $chosen_single{barcode} = $barcode;
378 push( @options, \%chosen_single );
382 $template_params->{options} = \@options;
386 if ( $error->{UNKNOWN_BARCODE} or not $onsite_checkout or not C4::Context->preference("OnSiteCheckoutsForce") ) {
387 delete $question->{'DEBT'} if ($debt_confirmed);
388 foreach my $impossible ( keys %$error ) {
389 $template_params->{$impossible} = $$error{$impossible};
390 $template_params->{IMPOSSIBLE} = 1;
395 if( $item and ( !$blocker or $force_allow_issue ) ){
396 my $confirm_required = 0;
397 unless($issueconfirmed){
398 # Get the item title for more information
399 my $materials = $item->materials;
400 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
401 $materials = $descriptions->{lib} // $materials;
402 $template_params->{additional_materials} = $materials;
403 $template_params->{itemhomebranch} = $item->homebranch;
405 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
406 foreach my $needsconfirmation ( keys %$question ) {
407 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
408 $template_params->{getTitleMessageIteminfo} = $biblio->title;
409 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
410 $template_params->{NEEDSCONFIRMATION} = 1;
411 $template_params->{onsite_checkout} = $onsite_checkout;
412 $template_params->{auto_renew} = $session->param('auto_renew');
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'}
432 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
433 $patron = Koha::Patrons->find( $borrowernumber );
434 $template_params->{issuecount} = $patron->checkouts->count;
437 $template_params->{item} = $item;
438 $template_params->{biblio} = $biblio;
439 $template_params->{itembiblionumber} = $biblio->biblionumber;
441 push @$checkout_infos, $template_params;
444 $template->param( %{$checkout_infos->[0]} );
445 $template->param( barcode => $barcodes->[0] );
447 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
449 checkout_infos => $checkout_infos,
450 confirmation_needed => $confirmation_needed,
455 ##################################################################################
457 # show all reserves of this borrower, and the position of the reservation ....
459 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
460 my $waiting_holds = $holds->waiting;
462 holds_count => $holds->count(),
463 WaitingHolds => $waiting_holds,
466 my $category_type = $patron->category->category_type;
467 $template->param( adultborrower => 1 ) if ( $category_type eq 'A' || $category_type eq 'I' );
471 my $flags = $patron ? C4::Members::patronflags( $patron->unblessed ) : {};
472 foreach my $flag ( sort keys %$flags ) {
473 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
474 if ( $flags->{$flag}->{'noissues'} ) {
476 noissues => ($force_allow_issue) ? 0 : 'true',
477 forceallow => $force_allow_issue,
479 if ( $flag eq 'GNA' ) {
480 $template->param( gna => 'true' );
482 elsif ( $flag eq 'LOST' ) {
483 $template->param( lost => 'true' );
485 elsif ( $flag eq 'DBARRED' ) {
486 $template->param( dbarred => 'true' );
488 elsif ( $flag eq 'CHARGES' ) {
491 chargesmsg => $flags->{'CHARGES'}->{'message'},
492 chargesamount => $flags->{'CHARGES'}->{'amount'},
493 charges_is_blocker => 1
496 elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
498 charges_guarantees => 'true',
499 chargesmsg_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'message'},
500 chargesamount_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'amount'},
501 charges_guarantees_is_blocker => 1
504 elsif ( $flag eq 'CREDITS' ) {
507 creditsmsg => $flags->{'CREDITS'}->{'message'},
508 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
513 if ( $flag eq 'CHARGES' ) {
516 chargesmsg => $flags->{'CHARGES'}->{'message'},
517 chargesamount => $flags->{'CHARGES'}->{'amount'},
520 elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
522 charges_guarantees => 'true',
523 chargesmsg_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'message'},
524 chargesamount_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'amount'},
527 elsif ( $flag eq 'CREDITS' ) {
530 creditsmsg => $flags->{'CREDITS'}->{'message'},
531 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
534 elsif ( $flag eq 'ODUES' ) {
537 oduesmsg => $flags->{'ODUES'}->{'message'}
540 my $items = $flags->{$flag}->{'itemlist'};
541 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
542 $template->param( nonreturns => 'true' );
545 elsif ( $flag eq 'NOTES' ) {
548 notesmsg => $flags->{'NOTES'}->{'message'}
554 my $amountold = $flags ? $flags->{'CHARGES'}->{'message'} || 0 : 0;
555 $amountold =~ s/^.*\$//; # remove upto the $, if any
557 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
559 if ( $patron && $patron->category->category_type eq 'C') {
560 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => 'A' }, {order_by => ['categorycode']});
561 $template->param( 'CATCODE_MULTI' => 1) if $patron_categories->count > 1;
562 $template->param( 'catcode' => $patron_categories->next->categorycode ) if $patron_categories->count == 1;
565 my $messages = Koha::Patron::Messages->search(
567 'me.borrowernumber' => $borrowernumber,
571 '+select' => ['manager.surname', 'manager.firstname' ],
572 '+as' => ['manager_surname', 'manager_firstname'],
576 my $fast_cataloging = 0;
577 if ( Koha::BiblioFrameworks->find('FA') ) {
581 if (C4::Context->preference('ExtendedPatronAttributes')) {
582 my $attributes = GetBorrowerAttributes($borrowernumber);
584 ExtendedPatronAttributes => 1,
585 extendedattributes => $attributes
589 ?'batch_checkout_view'
593 if ( $borrowernumber ) {
595 if ( my $guarantor = $patron->guarantor ) {
596 push @relatives, $guarantor->borrowernumber;
597 push @relatives, $_->borrowernumber for $patron->siblings;
599 push @relatives, $_->borrowernumber for $patron->guarantees;
603 my $relatives_issues_count =
604 Koha::Database->new()->schema()->resultset('Issue')
605 ->count( { borrowernumber => \@relatives } );
608 my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
609 my $roadtype = $av->count ? $av->next->lib : '';
611 %{ $patron->unblessed },
612 borrower => $patron->unblessed,
613 roadtype => $roadtype,
615 categoryname => $patron->category->description,
616 expiry => $patron->dateexpiry,
617 is_child => ( $patron->category->category_type eq 'C' ),
618 picture => ( $patron->image ? 1 : 0 ),
622 # Restore date if changed by holds and/or save stickyduedate to session
623 if ($restoreduedatespec || $stickyduedate) {
624 $duedatespec = $restoreduedatespec || $duedatespec;
626 if ($stickyduedate) {
627 $session->param( 'stickyduedate', $duedatespec );
629 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
634 messages => $messages,
635 borrowernumber => $borrowernumber,
637 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
638 amountold => $amountold,
639 barcodes => $barcodes,
640 stickyduedate => $stickyduedate,
641 duedatespec => $duedatespec,
642 restoreduedatespec => $restoreduedatespec,
644 totaldue => sprintf('%.2f', $total),
645 inprocess => $inprocess,
647 batch_allowed => $batch_allowed,
649 AudioAlerts => C4::Context->preference("AudioAlerts"),
650 fast_cataloging => $fast_cataloging,
651 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
652 RoutingSerials => C4::Context->preference('RoutingSerials'),
653 relatives_issues_count => $relatives_issues_count,
654 relatives_borrowernumbers => \@relatives,
658 if ( C4::Context->preference("ExportCircHistory") ) {
659 $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
662 my $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
664 debt_confirmed => $debt_confirmed,
665 SpecifyDueDate => $duedatespec_allow,
666 CircAutocompl => C4::Context->preference("CircAutocompl"),
667 debarments => scalar GetDebarments({ borrowernumber => $borrowernumber }),
668 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
669 has_modifications => $has_modifications,
670 override_high_holds => $override_high_holds,
671 nopermission => scalar $query->param('nopermission'),
674 output_html_with_http_headers $query, $cookie, $template->output;