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');
89 if (C4::Context->preference("AutoSwitchPatron") && $barcode) {
90 if (Koha::Patrons->search( { cardnumber => $barcode} )->count() > 0) {
91 $findborrower = $barcode;
96 $findborrower ||= $query->param('findborrower') || q{};
97 $findborrower =~ s|,| |g;
99 # Barcode given by user could be '0'
100 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
101 $barcodes = [ $barcode ];
103 my $filefh = $query->upload('uploadfile');
105 while ( my $content = <$filefh> ) {
106 $content =~ s/[\r\n]*$//g;
107 push @$barcodes, $content if $content;
109 } elsif ( my $list = $query->param('barcodelist') ) {
110 push @$barcodes, split( /\s\n/, $list );
111 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
113 @$barcodes = $query->multi_param('barcodes');
117 $barcodes = [ uniq @$barcodes ];
119 my $template_name = q|circ/circulation.tt|;
120 my $borrowernumber = $query->param('borrowernumber');
121 my $patron = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : undef;
122 my $batch = $query->param('batch');
123 my $batch_allowed = 0;
124 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
125 $template_name = q|circ/circulation_batch_checkouts.tt|;
126 my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
127 my $categorycode = $patron->categorycode;
128 if ( $categorycode && grep {/^$categorycode$/} @batch_category_codes ) {
135 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
137 template_name => $template_name,
140 authnotrequired => 0,
141 flagsrequired => { circulate => 'circulate_remaining_permissions' },
144 my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
146 my $force_allow_issue = $query->param('forceallow') || 0;
147 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
148 $force_allow_issue = 0;
151 my $onsite_checkout = $query->param('onsite_checkout');
153 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
154 our %renew_failed = ();
155 for (@failedrenews) { $renew_failed{$_} = 1; }
157 my @failedreturns = $query->multi_param('failedreturn');
158 our %return_failed = ();
159 for (@failedreturns) { $return_failed{$_} = 1; }
161 my $searchtype = $query->param('searchtype') || q{contain};
163 my $branch = C4::Context->userenv->{'branch'};
165 if (C4::Context->preference("DisplayClearScreenButton")) {
166 $template->param(DisplayClearScreenButton => 1);
169 for my $barcode ( @$barcodes ) {
170 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
171 $barcode = barcodedecode($barcode)
172 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
175 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
176 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
177 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso', timeformat => '24hr' }); }
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 $print = $query->param('print') || q{};
186 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
187 my $charges = $query->param('charges') || q{};
189 # Check if stickyduedate is turned off
191 # was stickyduedate loaded from session?
192 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
193 $session->clear( 'stickyduedate' );
194 $stickyduedate = $query->param('stickyduedate');
195 $duedatespec = $query->param('duedatespec');
197 $session->param('auto_renew', scalar $query->param('auto_renew'));
200 $session->clear('auto_renew');
203 my ($datedue,$invalidduedate);
205 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
206 if( $onsite_checkout && !$duedatespec_allow ) {
207 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
208 $datedue .= ' 23:59:00';
209 } elsif( $duedatespec_allow ) {
210 if ( $duedatespec ) {
211 $datedue = eval { dt_from_string( $duedatespec ) };
214 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
219 # check and see if we should print
220 if ( @$barcodes == 0 && $print eq 'maybe' ) {
224 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
225 if ( @$barcodes == 0 && $charges eq 'yes' ) {
228 borrowernumber => $borrowernumber
232 if ( $print eq 'yes' && $borrowernumber ne '' ) {
233 if ( C4::Context->boolean_preference('printcirculationslips') ) {
234 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
235 NetworkPrint($letter->{content});
237 $query->param( 'borrowernumber', '' );
238 $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.....
274 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
277 $template->param( borrowernumber => $patron->borrowernumber );
278 output_and_exit_if_error( $query, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
280 my $overdues = $patron->get_overdues;
281 my $issues = $patron->checkouts;
282 my $balance = $patron->account->balance;
285 # if the expiry date is before today ie they have expired
286 if ( $patron->is_expired ) {
287 #borrowercard expired, no issues
289 noissues => ($force_allow_issue) ? 0 : "1",
290 forceallow => $force_allow_issue,
294 # check for NotifyBorrowerDeparture
295 elsif ( $patron->is_going_to_expire ) {
296 # borrower card soon to expire warn librarian
297 $template->param( "warndeparture" => $patron->dateexpiry ,
299 if (C4::Context->preference('ReturnBeforeExpiry')){
300 $template->param("returnbeforeexpiry" => 1);
304 overduecount => $overdues->count,
305 issuecount => $issues->count,
306 finetotal => $balance,
309 if ( $patron and $patron->is_debarred ) {
311 'userdebarred' => $patron->debarred,
312 'debarredcomment' => $patron->debarredcomment,
315 if ( $patron->debarred ne "9999-12-31" ) {
316 $template->param( 'userdebarreddate' => $patron->debarred );
328 for my $barcode ( @$barcodes ) {
329 my $template_params = { barcode => $barcode };
330 # always check for blockers on issuing
331 my ( $error, $question, $alerts, $messages ) = CanBookBeIssued(
337 onsite_checkout => $onsite_checkout,
338 override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
342 my $blocker = $invalidduedate ? 1 : 0;
344 $template_params->{alert} = $alerts;
345 $template_params->{messages} = $messages;
347 my $item = Koha::Items->find({ barcode => $barcode });
348 my ( $biblio, $mss );
351 $biblio = $item->biblio;
352 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.notforloan', authorised_value => { not => undef } });
353 $template_params->{authvalcode_notforloan} = $mss->count ? $mss->next->authorised_value : undef;
356 # Fix for bug 7494: optional checkout-time fallback search for a book
358 if ( $error->{'UNKNOWN_BARCODE'}
359 && C4::Context->preference("itemBarcodeFallbackSearch")
363 $template_params->{FALLBACK} = 1;
365 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
366 my $query = "kw=" . $barcode;
367 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
369 # if multiple hits, offer options to librarian
370 if ( $total_hits > 0 ) {
372 foreach my $hit ( @{$results} ) {
374 TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
376 # offer all barcodes individually
377 if ( $chosen->{barcode} ) {
378 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
379 my %chosen_single = %{$chosen};
380 $chosen_single{barcode} = $barcode;
381 push( @options, \%chosen_single );
385 $template_params->{options} = \@options;
389 if ( $error->{UNKNOWN_BARCODE} or not $onsite_checkout or not C4::Context->preference("OnSiteCheckoutsForce") ) {
390 delete $question->{'DEBT'} if ($debt_confirmed);
391 foreach my $impossible ( keys %$error ) {
392 $template_params->{$impossible} = $$error{$impossible};
393 $template_params->{IMPOSSIBLE} = 1;
398 if( $item and ( !$blocker or $force_allow_issue ) ){
399 my $confirm_required = 0;
400 unless($issueconfirmed){
401 # Get the item title for more information
402 my $materials = $item->materials;
403 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
404 $materials = $descriptions->{lib} // $materials;
405 $template_params->{additional_materials} = $materials;
406 $template_params->{itemhomebranch} = $item->homebranch;
408 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
409 foreach my $needsconfirmation ( keys %$question ) {
410 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
411 $template_params->{getTitleMessageIteminfo} = $biblio->title;
412 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
413 $template_params->{NEEDSCONFIRMATION} = 1;
414 $template_params->{onsite_checkout} = $onsite_checkout;
415 $template_params->{auto_renew} = $session->param('auto_renew');
416 $confirm_required = 1;
419 unless($confirm_required) {
420 my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED};
421 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, } );
422 $template_params->{issue} = $issue;
423 $session->clear('auto_renew');
428 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
430 reserveborrowernumber => $question->{'resborrowernumber'}
435 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
436 $patron = Koha::Patrons->find( $borrowernumber );
437 $template_params->{issuecount} = $patron->checkouts->count;
440 $template_params->{item} = $item;
441 $template_params->{biblio} = $biblio;
442 $template_params->{itembiblionumber} = $biblio->biblionumber;
444 push @$checkout_infos, $template_params;
447 $template->param( %{$checkout_infos->[0]} );
448 $template->param( barcode => $barcodes->[0] );
450 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
452 checkout_infos => $checkout_infos,
453 confirmation_needed => $confirmation_needed,
458 ##################################################################################
460 # show all reserves of this borrower, and the position of the reservation ....
462 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
463 my $waiting_holds = $holds->waiting;
465 holds_count => $holds->count(),
466 WaitingHolds => $waiting_holds,
469 my $category_type = $patron->category->category_type;
470 $template->param( adultborrower => 1 ) if ( $category_type eq 'A' || $category_type eq 'I' );
474 my $flags = $patron ? C4::Members::patronflags( $patron->unblessed ) : {};
475 foreach my $flag ( sort keys %$flags ) {
476 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
477 if ( $flags->{$flag}->{'noissues'} ) {
479 noissues => ($force_allow_issue) ? 0 : 'true',
480 forceallow => $force_allow_issue,
482 if ( $flag eq 'GNA' ) {
483 $template->param( gna => 'true' );
485 elsif ( $flag eq 'LOST' ) {
486 $template->param( lost => 'true' );
488 elsif ( $flag eq 'DBARRED' ) {
489 $template->param( dbarred => 'true' );
491 elsif ( $flag eq 'CHARGES' ) {
494 chargesmsg => $flags->{'CHARGES'}->{'message'},
495 chargesamount => $flags->{'CHARGES'}->{'amount'},
496 charges_is_blocker => 1
499 elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
501 charges_guarantees => 'true',
502 chargesmsg_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'message'},
503 chargesamount_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'amount'},
504 charges_guarantees_is_blocker => 1
507 elsif ( $flag eq 'CREDITS' ) {
510 creditsmsg => $flags->{'CREDITS'}->{'message'},
511 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
516 if ( $flag eq 'CHARGES' ) {
519 chargesmsg => $flags->{'CHARGES'}->{'message'},
520 chargesamount => $flags->{'CHARGES'}->{'amount'},
523 elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
525 charges_guarantees => 'true',
526 chargesmsg_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'message'},
527 chargesamount_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'amount'},
530 elsif ( $flag eq 'CREDITS' ) {
533 creditsmsg => $flags->{'CREDITS'}->{'message'},
534 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
537 elsif ( $flag eq 'ODUES' ) {
540 oduesmsg => $flags->{'ODUES'}->{'message'}
543 my $items = $flags->{$flag}->{'itemlist'};
544 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
545 $template->param( nonreturns => 'true' );
548 elsif ( $flag eq 'NOTES' ) {
551 notesmsg => $flags->{'NOTES'}->{'message'}
557 my $amountold = $flags ? $flags->{'CHARGES'}->{'message'} || 0 : 0;
558 $amountold =~ s/^.*\$//; # remove upto the $, if any
560 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
562 if ( $patron && $patron->category->category_type eq 'C') {
563 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => 'A' }, {order_by => ['categorycode']});
564 $template->param( 'CATCODE_MULTI' => 1) if $patron_categories->count > 1;
565 $template->param( 'catcode' => $patron_categories->next->categorycode ) if $patron_categories->count == 1;
568 my $messages = Koha::Patron::Messages->search(
570 'me.borrowernumber' => $borrowernumber,
574 '+select' => ['manager.surname', 'manager.firstname' ],
575 '+as' => ['manager_surname', 'manager_firstname'],
579 my $fast_cataloging = 0;
580 if ( Koha::BiblioFrameworks->find('FA') ) {
584 if (C4::Context->preference('ExtendedPatronAttributes')) {
585 my $attributes = GetBorrowerAttributes($borrowernumber);
587 ExtendedPatronAttributes => 1,
588 extendedattributes => $attributes
592 ?'batch_checkout_view'
596 if ( $borrowernumber ) {
598 if ( my $guarantor = $patron->guarantor ) {
599 push @relatives, $guarantor->borrowernumber;
600 push @relatives, $_->borrowernumber for $patron->siblings;
602 push @relatives, $_->borrowernumber for $patron->guarantees;
606 my $relatives_issues_count =
607 Koha::Database->new()->schema()->resultset('Issue')
608 ->count( { borrowernumber => \@relatives } );
611 my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
612 my $roadtype = $av->count ? $av->next->lib : '';
614 %{ $patron->unblessed },
615 borrower => $patron->unblessed,
616 roadtype => $roadtype,
618 categoryname => $patron->category->description,
619 expiry => $patron->dateexpiry,
620 is_child => ( $patron->category->category_type eq 'C' ),
621 picture => ( $patron->image ? 1 : 0 ),
625 # Restore date if changed by holds and/or save stickyduedate to session
626 if ($restoreduedatespec || $stickyduedate) {
627 $duedatespec = $restoreduedatespec || $duedatespec;
629 if ($stickyduedate) {
630 $session->param( 'stickyduedate', $duedatespec );
632 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
637 messages => $messages,
638 borrowernumber => $borrowernumber,
640 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
641 amountold => $amountold,
642 barcodes => $barcodes,
643 stickyduedate => $stickyduedate,
644 duedatespec => $duedatespec,
645 restoreduedatespec => $restoreduedatespec,
647 totaldue => sprintf('%.2f', $total),
648 inprocess => $inprocess,
650 batch_allowed => $batch_allowed,
652 AudioAlerts => C4::Context->preference("AudioAlerts"),
653 fast_cataloging => $fast_cataloging,
654 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
655 RoutingSerials => C4::Context->preference('RoutingSerials'),
656 relatives_issues_count => $relatives_issues_count,
657 relatives_borrowernumbers => \@relatives,
661 if ( C4::Context->preference("ExportCircHistory") ) {
662 $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
665 my $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
667 debt_confirmed => $debt_confirmed,
668 SpecifyDueDate => $duedatespec_allow,
669 CircAutocompl => C4::Context->preference("CircAutocompl"),
670 debarments => scalar GetDebarments({ borrowernumber => $borrowernumber }),
671 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
672 has_modifications => $has_modifications,
673 override_high_holds => $override_high_holds,
674 nopermission => scalar $query->param('nopermission'),
675 autoswitched => $autoswitched,
678 output_html_with_http_headers $query, $cookie, $template->output;