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>.
29 use DateTime::Duration;
32 use C4::Auth qw/:DEFAULT get_session haspermission/;
33 use C4::Branch; # GetBranches
34 use C4::Koha; # GetPrinter
36 use C4::Utils::DataTables::Members;
45 use C4::Members::Attributes qw(GetBorrowerAttributes);
47 use Koha::Patron::Debarments qw(GetDebarments IsDebarred);
50 use Koha::Patron::Messages;
51 use Koha::Patron::Images;
52 use Koha::SearchEngine;
53 use Koha::SearchEngine::Search;
54 use Koha::Patron::Modifications;
61 use List::MoreUtils qw/uniq/;
68 my $override_high_holds = $query->param('override_high_holds');
69 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
71 my $sessionID = $query->cookie("CGISESSID") ;
72 my $session = get_session($sessionID);
73 if (!C4::Context->userenv){
74 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
75 # no branch set we can't issue
76 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
82 my $barcode = $query->param('barcode');
83 # Barcode given by user could be '0'
84 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
85 $barcodes = [ $barcode ];
87 my $filefh = $query->upload('uploadfile');
89 while ( my $content = <$filefh> ) {
90 $content =~ s/[\r\n]*$//g;
91 push @$barcodes, $content if $content;
93 } elsif ( my $list = $query->param('barcodelist') ) {
94 push @$barcodes, split( /\s\n/, $list );
95 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
97 @$barcodes = $query->multi_param('barcodes');
101 $barcodes = [ uniq @$barcodes ];
103 my $template_name = q|circ/circulation.tt|;
104 my $borrowernumber = $query->param('borrowernumber');
105 my $borrower = $borrowernumber ? GetMember( borrowernumber => $borrowernumber ) : undef;
106 my $batch = $query->param('batch');
107 my $batch_allowed = 0;
108 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
109 $template_name = q|circ/circulation_batch_checkouts.tt|;
110 my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
111 if ( grep {/^$borrower->{categorycode}$/} @batch_category_codes ) {
118 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
120 template_name => $template_name,
123 authnotrequired => 0,
124 flagsrequired => { circulate => 'circulate_remaining_permissions' },
128 my $force_allow_issue = $query->param('forceallow') || 0;
129 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
130 $force_allow_issue = 0;
133 my $onsite_checkout = $query->param('onsite_checkout');
135 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
136 our %renew_failed = ();
137 for (@failedrenews) { $renew_failed{$_} = 1; }
139 my @failedreturns = $query->multi_param('failedreturn');
140 our %return_failed = ();
141 for (@failedreturns) { $return_failed{$_} = 1; }
143 my $searchtype = $query->param('searchtype') || q{contain};
145 my $findborrower = $query->param('findborrower') || q{};
146 $findborrower =~ s|,| |g;
148 my $branch = C4::Context->userenv->{'branch'};
150 if (C4::Context->preference("DisplayClearScreenButton")) {
151 $template->param(DisplayClearScreenButton => 1);
154 for my $barcode ( @$barcodes ) {
155 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
156 $barcode = barcodedecode($barcode)
157 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
160 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
161 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
162 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso', timeformat => '24hr' }); }
164 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
165 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
166 undef $restoreduedatespec;
168 my $issueconfirmed = $query->param('issueconfirmed');
169 my $cancelreserve = $query->param('cancelreserve');
170 my $print = $query->param('print') || q{};
171 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
172 my $charges = $query->param('charges') || q{};
174 # Check if stickyduedate is turned off
176 # was stickyduedate loaded from session?
177 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
178 $session->clear( 'stickyduedate' );
179 $stickyduedate = $query->param('stickyduedate');
180 $duedatespec = $query->param('duedatespec');
182 $session->param('auto_renew', scalar $query->param('auto_renew'));
185 $session->clear('auto_renew');
188 my ($datedue,$invalidduedate);
190 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
191 if( $onsite_checkout && !$duedatespec_allow ) {
192 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
193 $datedue .= ' 23:59:00';
194 } elsif( $duedatespec_allow ) {
195 if ( $duedatespec ) {
196 $datedue = eval { dt_from_string( $duedatespec ) };
199 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
204 # check and see if we should print
205 if ( @$barcodes == 0 && $print eq 'maybe' ) {
209 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
210 if ( @$barcodes == 0 && $charges eq 'yes' ) {
213 borrowernumber => $borrowernumber
217 if ( $print eq 'yes' && $borrowernumber ne '' ) {
218 if ( C4::Context->boolean_preference('printcirculationslips') ) {
219 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
220 NetworkPrint($letter->{content});
222 $query->param( 'borrowernumber', '' );
223 $borrowernumber = '';
227 # STEP 2 : FIND BORROWER
228 # if there is a list of find borrowers....
232 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
234 $borrowernumber = $borrower->{borrowernumber};
236 my $dt_params = { iDisplayLength => -1 };
237 my $results = C4::Utils::DataTables::Members::search(
239 searchmember => $findborrower,
240 searchtype => $searchtype,
241 dt_params => $dt_params,
244 my $borrowers = $results->{patrons};
245 if ( scalar @$borrowers == 1 ) {
246 $borrowernumber = $borrowers->[0]->{borrowernumber};
247 $query->param( 'borrowernumber', $borrowernumber );
248 $query->param( 'barcode', '' );
249 } elsif ( @$borrowers ) {
250 $template->param( borrowers => $borrowers );
252 $query->param( 'findborrower', '' );
253 $message = "'$findborrower'";
258 # get the borrower information.....
259 if ($borrowernumber) {
260 $borrower = GetMemberDetails( $borrowernumber, 0 );
261 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
263 # Warningdate is the date that the warning starts appearing
264 my ( $today_year, $today_month, $today_day) = Today();
265 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
266 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
267 # if the expiry date is before today ie they have expired
268 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
269 || Date_to_Days($today_year, $today_month, $today_day )
270 > Date_to_Days($warning_year, $warning_month, $warning_day) )
272 #borrowercard expired, no issues
274 noissues => ($force_allow_issue) ? 0 : "1",
275 forceallow => $force_allow_issue,
279 # check for NotifyBorrowerDeparture
280 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
281 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
282 Date_to_Days( $today_year, $today_month, $today_day ) )
284 # borrower card soon to expire warn librarian
285 $template->param( "warndeparture" => $borrower->{dateexpiry} ,
287 if (C4::Context->preference('ReturnBeforeExpiry')){
288 $template->param("returnbeforeexpiry" => 1);
293 issuecount => $issue,
297 if ( IsDebarred($borrowernumber) ) {
299 'userdebarred' => $borrower->{debarred},
300 'debarredcomment' => $borrower->{debarredcomment},
303 if ( $borrower->{debarred} ne "9999-12-31" ) {
304 $template->param( 'userdebarreddate' => $borrower->{debarred} );
316 for my $barcode ( @$barcodes ) {
317 my $template_params = { barcode => $barcode };
318 # always check for blockers on issuing
319 my ( $error, $question, $alerts ) = CanBookBeIssued(
325 onsite_checkout => $onsite_checkout,
326 override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
330 my $blocker = $invalidduedate ? 1 : 0;
332 $template_params->{alert} = $alerts;
334 # Get the item title for more information
335 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
336 $template_params->{authvalcode_notforloan} =
337 C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'});
339 # Fix for bug 7494: optional checkout-time fallback search for a book
341 if ( $error->{'UNKNOWN_BARCODE'}
342 && C4::Context->preference("itemBarcodeFallbackSearch")
346 $template_params->{FALLBACK} = 1;
348 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
349 my $query = "kw=" . $barcode;
350 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
352 # if multiple hits, offer options to librarian
353 if ( $total_hits > 0 ) {
355 foreach my $hit ( @{$results} ) {
357 TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
359 # offer all barcodes individually
360 if ( $chosen->{barcode} ) {
361 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
362 my %chosen_single = %{$chosen};
363 $chosen_single{barcode} = $barcode;
364 push( @options, \%chosen_single );
368 $template_params->{options} = \@options;
372 unless( $onsite_checkout and C4::Context->preference("OnSiteCheckoutsForce") ) {
373 delete $question->{'DEBT'} if ($debt_confirmed);
374 foreach my $impossible ( keys %$error ) {
375 $template_params->{$impossible} = $$error{$impossible};
376 $template_params->{IMPOSSIBLE} = 1;
380 my $iteminfo = GetBiblioFromItemNumber(undef, $barcode);
381 if( !$blocker || $force_allow_issue ){
382 my $confirm_required = 0;
383 unless($issueconfirmed){
384 # Get the item title for more information
385 my $materials = $iteminfo->{'materials'};
386 my $avcode = GetAuthValCode('items.materials');
388 $materials = GetKohaAuthorisedValueLib($avcode, $materials);
390 $template_params->{additional_materials} = $materials;
391 $template_params->{itemhomebranch} = $iteminfo->{'homebranch'};
393 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
394 foreach my $needsconfirmation ( keys %$question ) {
395 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
396 $template_params->{getTitleMessageIteminfo} = $iteminfo->{'title'};
397 $template_params->{getBarcodeMessageIteminfo} = $iteminfo->{'barcode'};
398 $template_params->{NEEDSCONFIRMATION} = 1;
399 $template_params->{onsite_checkout} = $onsite_checkout;
400 $confirm_required = 1;
403 unless($confirm_required) {
404 my $issue = AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
405 $template_params->{issue} = $issue;
406 $session->clear('auto_renew');
411 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
412 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
414 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
416 reserveborrowernumber => $question->{'resborrowernumber'}
421 itembiblionumber => $getmessageiteminfo->{'biblionumber'}
426 $template_params->{issuecount} = $issue;
429 $iteminfo->{subtitle} = GetRecordValue('subtitle', GetMarcBiblio($iteminfo->{biblionumber}), GetFrameworkCode($iteminfo->{biblionumber}));
430 $template_params->{item} = $iteminfo;
432 push @$checkout_infos, $template_params;
435 $template->param( %{$checkout_infos->[0]} );
436 $template->param( barcode => $barcodes->[0] );
438 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
440 checkout_infos => $checkout_infos,
441 confirmation_needed => $confirmation_needed,
446 # reload the borrower info for the sake of reseting the flags.....
447 if ($borrowernumber) {
448 $borrower = GetMemberDetails( $borrowernumber, 0 );
451 ##################################################################################
453 # show all reserves of this borrower, and the position of the reservation ....
454 if ($borrowernumber) {
455 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } );
456 my $waiting_holds = $holds->waiting;
458 holds_count => $holds->count(),
459 WaitingHolds => $waiting_holds,
462 $template->param( adultborrower => 1 ) if ( $borrower->{category_type} eq 'A' || $borrower->{category_type} eq 'I' );
466 my $flags = $borrower->{'flags'};
467 foreach my $flag ( sort keys %$flags ) {
468 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
469 if ( $flags->{$flag}->{'noissues'} ) {
471 noissues => ($force_allow_issue) ? 0 : 'true',
472 forceallow => $force_allow_issue,
474 if ( $flag eq 'GNA' ) {
475 $template->param( gna => 'true' );
477 elsif ( $flag eq 'LOST' ) {
478 $template->param( lost => 'true' );
480 elsif ( $flag eq 'DBARRED' ) {
481 $template->param( dbarred => 'true' );
483 elsif ( $flag eq 'CHARGES' ) {
486 chargesmsg => $flags->{'CHARGES'}->{'message'},
487 chargesamount => $flags->{'CHARGES'}->{'amount'},
488 charges_is_blocker => 1
491 elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
493 charges_guarantees => 'true',
494 chargesmsg_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'message'},
495 chargesamount_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'amount'},
496 charges_guarantees_is_blocker => 1
499 elsif ( $flag eq 'CREDITS' ) {
502 creditsmsg => $flags->{'CREDITS'}->{'message'},
503 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
508 if ( $flag eq 'CHARGES' ) {
511 chargesmsg => $flags->{'CHARGES'}->{'message'},
512 chargesamount => $flags->{'CHARGES'}->{'amount'},
515 elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
517 charges_guarantees => 'true',
518 chargesmsg_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'message'},
519 chargesamount_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'amount'},
522 elsif ( $flag eq 'CREDITS' ) {
525 creditsmsg => $flags->{'CREDITS'}->{'message'},
526 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
529 elsif ( $flag eq 'ODUES' ) {
532 oduesmsg => $flags->{'ODUES'}->{'message'}
535 my $items = $flags->{$flag}->{'itemlist'};
536 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
537 $template->param( nonreturns => 'true' );
540 elsif ( $flag eq 'NOTES' ) {
543 notesmsg => $flags->{'NOTES'}->{'message'}
549 my $amountold = $borrower->{flags} ? $borrower->{flags}->{'CHARGES'}->{'message'} || 0 : 0;
550 $amountold =~ s/^.*\$//; # remove upto the $, if any
552 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
554 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
555 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
556 my $cnt = scalar(@$catcodes);
557 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
558 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
561 my $librarian_messages = Koha::Patron::Messages->search(
563 borrowernumber => $borrowernumber,
568 my $patron_messages = Koha::Patron::Messages->search(
570 borrowernumber => $borrowernumber,
575 my $fast_cataloging = 0;
576 if (defined getframeworkinfo('FA')) {
580 if (C4::Context->preference('ExtendedPatronAttributes')) {
581 my $attributes = GetBorrowerAttributes($borrowernumber);
583 ExtendedPatronAttributes => 1,
584 extendedattributes => $attributes
588 ?'batch_checkout_view'
592 if ( $borrowernumber ) {
593 if ( my $patron = Koha::Patrons->find( $borrower->{borrowernumber} ) ) {
594 if ( my $guarantor = $patron->guarantor ) {
595 push @relatives, $guarantor->borrowernumber;
596 push @relatives, $_->borrowernumber for $patron->siblings;
598 push @relatives, $_->borrowernumber for $patron->guarantees;
602 my $relatives_issues_count =
603 Koha::Database->new()->schema()->resultset('Issue')
604 ->count( { borrowernumber => \@relatives } );
606 my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{streettype} );
608 $template->param(%$borrower);
610 # Restore date if changed by holds and/or save stickyduedate to session
611 if ($restoreduedatespec || $stickyduedate) {
612 $duedatespec = $restoreduedatespec || $duedatespec;
614 if ($stickyduedate) {
615 $session->param( 'stickyduedate', $duedatespec );
617 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
622 librarian_messages => $librarian_messages,
623 patron_messages => $patron_messages,
624 borrower => $borrower,
625 borrowernumber => $borrowernumber,
626 categoryname => $borrower->{'description'},
628 branchname => GetBranchName($borrower->{'branchcode'}),
629 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
630 expiry => $borrower->{'dateexpiry'},
631 roadtype => $roadtype,
632 amountold => $amountold,
633 barcodes => $barcodes,
634 stickyduedate => $stickyduedate,
635 duedatespec => $duedatespec,
636 restoreduedatespec => $restoreduedatespec,
638 totaldue => sprintf('%.2f', $total),
639 inprocess => $inprocess,
640 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
642 batch_allowed => $batch_allowed,
643 AudioAlerts => C4::Context->preference("AudioAlerts"),
644 fast_cataloging => $fast_cataloging,
645 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
646 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
647 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
648 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
649 RoutingSerials => C4::Context->preference('RoutingSerials'),
650 relatives_issues_count => $relatives_issues_count,
651 relatives_borrowernumbers => \@relatives,
654 my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
655 $template->param( picture => 1 ) if $patron_image;
657 # get authorised values with type of BOR_NOTES
659 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
662 debt_confirmed => $debt_confirmed,
663 SpecifyDueDate => $duedatespec_allow,
664 CircAutocompl => C4::Context->preference("CircAutocompl"),
665 canned_bor_notes_loop => $canned_notes,
666 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
667 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
668 modifications => Koha::Patron::Modifications->GetModifications({ borrowernumber => $borrowernumber }),
669 override_high_holds => $override_high_holds,
670 nopermission => scalar $query->param('nopermission'),
673 output_html_with_http_headers $query, $cookie, $template->output;