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);
46 use Koha::Patron::Debarments qw(GetDebarments IsDebarred);
49 use Koha::Patron::Messages;
50 use Koha::Patron::Images;
57 use List::MoreUtils qw/uniq/;
64 my $sessionID = $query->cookie("CGISESSID") ;
65 my $session = get_session($sessionID);
67 # branch and printer are now defined by the userenv
68 # but first we have to check if someone has tried to change them
70 my $branch = $query->param('branch');
72 # update our session so the userenv is updated
73 $session->param('branch', $branch);
74 $session->param('branchname', GetBranchName($branch));
77 my $printer = $query->param('printer');
79 # update our session so the userenv is updated
80 $session->param('branchprinter', $printer);
83 if (!C4::Context->userenv && !$branch){
84 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
85 # no branch set we can't issue
86 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
92 my $barcode = $query->param('barcode');
93 # Barcode given by user could be '0'
94 if ( $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->param('barcodes');
111 $barcodes = [ uniq @$barcodes ];
113 my $template_name = q|circ/circulation.tt|;
114 my $borrowernumber = $query->param('borrowernumber');
115 my $borrower = $borrowernumber ? GetMember( borrowernumber => $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 if ( grep {/^$borrower->{categorycode}$/} @batch_category_codes ) {
128 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
130 template_name => $template_name,
133 authnotrequired => 0,
134 flagsrequired => { circulate => 'circulate_remaining_permissions' },
138 my $branches = GetBranches();
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->param('failedrenew'); # expected to be itemnumbers
148 our %renew_failed = ();
149 for (@failedrenews) { $renew_failed{$_} = 1; }
151 my @failedreturns = $query->param('failedreturn');
152 our %return_failed = ();
153 for (@failedreturns) { $return_failed{$_} = 1; }
155 my $findborrower = $query->param('findborrower') || q{};
156 $findborrower =~ s|,| |g;
158 $branch = C4::Context->userenv->{'branch'};
159 $printer = C4::Context->userenv->{'branchprinter'};
161 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
162 if (C4::Context->preference("AutoLocation") != 1) {
163 $template->param(ManualLocation => 1);
166 if (C4::Context->preference("DisplayClearScreenButton")) {
167 $template->param(DisplayClearScreenButton => 1);
170 for my $barcode ( @$barcodes ) {
171 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
172 $barcode = barcodedecode($barcode)
173 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
176 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
177 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
178 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso' }); }
180 my $restoreduedatespec = $query->param('restoreduedatespec') || $session->param('stickyduedate') || $duedatespec;
181 if ($restoreduedatespec eq "highholds_empty") {
182 undef $restoreduedatespec;
184 my $issueconfirmed = $query->param('issueconfirmed');
185 my $cancelreserve = $query->param('cancelreserve');
186 my $print = $query->param('print') || q{};
187 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
188 my $charges = $query->param('charges') || q{};
190 # Check if stickyduedate is turned off
192 # was stickyduedate loaded from session?
193 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
194 $session->clear( 'stickyduedate' );
195 $stickyduedate = $query->param('stickyduedate');
196 $duedatespec = $query->param('duedatespec');
198 $session->param('auto_renew', $query->param('auto_renew'));
201 $session->clear('auto_renew');
204 my ($datedue,$invalidduedate);
206 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
207 if( $onsite_checkout && !$duedatespec_allow ) {
208 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
209 $datedue .= ' 23:59:00';
210 } elsif( $duedatespec_allow ) {
211 if ( $duedatespec ) {
212 $datedue = eval { dt_from_string( $duedatespec ) };
215 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
220 # check and see if we should print
221 if ( @$barcodes == 0 && $print eq 'maybe' ) {
225 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
226 if ( @$barcodes == 0 && $charges eq 'yes' ) {
229 borrowernumber => $borrowernumber
233 if ( $print eq 'yes' && $borrowernumber ne '' ) {
234 if ( C4::Context->boolean_preference('printcirculationslips') ) {
235 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
236 NetworkPrint($letter->{content});
238 $query->param( 'borrowernumber', '' );
239 $borrowernumber = '';
243 # STEP 2 : FIND BORROWER
244 # if there is a list of find borrowers....
248 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
250 $borrowernumber = $borrower->{borrowernumber};
252 my $dt_params = { iDisplayLength => -1 };
253 my $results = C4::Utils::DataTables::Members::search(
255 searchmember => $findborrower,
256 searchtype => 'contain',
257 dt_params => $dt_params,
260 my $borrowers = $results->{patrons};
261 if ( scalar @$borrowers == 1 ) {
262 $borrowernumber = $borrowers->[0]->{borrowernumber};
263 $query->param( 'borrowernumber', $borrowernumber );
264 $query->param( 'barcode', '' );
265 } elsif ( @$borrowers ) {
266 $template->param( borrowers => $borrowers );
268 $query->param( 'findborrower', '' );
269 $message = "'$findborrower'";
274 # get the borrower information.....
275 if ($borrowernumber) {
276 $borrower = GetMemberDetails( $borrowernumber, 0 );
277 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
279 # Warningdate is the date that the warning starts appearing
280 my ( $today_year, $today_month, $today_day) = Today();
281 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
282 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
283 # if the expiry date is before today ie they have expired
284 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
285 || Date_to_Days($today_year, $today_month, $today_day )
286 > Date_to_Days($warning_year, $warning_month, $warning_day) )
288 #borrowercard expired, no issues
291 noissues => ($force_allow_issue) ? 0 : "1",
292 forceallow => $force_allow_issue,
296 # check for NotifyBorrowerDeparture
297 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
298 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
299 Date_to_Days( $today_year, $today_month, $today_day ) )
301 # borrower card soon to expire warn librarian
302 $template->param( "warndeparture" => $borrower->{dateexpiry} ,
305 if (C4::Context->preference('ReturnBeforeExpiry')){
306 $template->param("returnbeforeexpiry" => 1);
311 issuecount => $issue,
315 if ( IsDebarred($borrowernumber) ) {
317 'userdebarred' => $borrower->{debarred},
318 'debarredcomment' => $borrower->{debarredcomment},
321 if ( $borrower->{debarred} ne "9999-12-31" ) {
322 $template->param( 'userdebarreddate' => $borrower->{debarred} );
334 for my $barcode ( @$barcodes ) {
335 my $template_params = { barcode => $barcode };
336 # always check for blockers on issuing
337 my ( $error, $question, $alerts ) =
338 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess, undef, { onsite_checkout => $onsite_checkout } );
339 my $blocker = $invalidduedate ? 1 : 0;
341 $template_params->{alert} = $alerts;
343 # Get the item title for more information
344 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
345 $template_params->{authvalcode_notforloan} =
346 C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'});
348 # Fix for bug 7494: optional checkout-time fallback search for a book
350 if ( $error->{'UNKNOWN_BARCODE'}
351 && C4::Context->preference("itemBarcodeFallbackSearch")
355 $template_params->{FALLBACK} = 1;
357 my $query = "kw=" . $barcode;
358 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
360 # if multiple hits, offer options to librarian
361 if ( $total_hits > 0 ) {
363 foreach my $hit ( @{$results} ) {
365 TransformMarcToKoha( C4::Context->dbh,
366 C4::Search::new_record_from_zebra('biblioserver',$hit) );
368 # offer all barcodes individually
369 if ( $chosen->{barcode} ) {
370 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
371 my %chosen_single = %{$chosen};
372 $chosen_single{barcode} = $barcode;
373 push( @options, \%chosen_single );
377 $template_params->{options} = \@options;
381 unless( $onsite_checkout and C4::Context->preference("OnSiteCheckoutsForce") ) {
382 delete $question->{'DEBT'} if ($debt_confirmed);
383 foreach my $impossible ( keys %$error ) {
384 $template_params->{$impossible} = $$error{$impossible};
385 $template_params->{IMPOSSIBLE} = 1;
389 my $iteminfo = GetBiblioFromItemNumber(undef, $barcode);
390 if( !$blocker || $force_allow_issue ){
391 my $confirm_required = 0;
392 unless($issueconfirmed){
393 # Get the item title for more information
394 $template_params->{additional_materials} = $iteminfo->{'materials'};
395 $template_params->{itemhomebranch} = $iteminfo->{'homebranch'};
397 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
398 foreach my $needsconfirmation ( keys %$question ) {
399 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
400 $template_params->{getTitleMessageIteminfo} = $iteminfo->{'title'};
401 $template_params->{getBarcodeMessageIteminfo} = $iteminfo->{'barcode'};
402 $template_params->{NEEDSCONFIRMATION} = 1;
403 $template_params->{onsite_checkout} = $onsite_checkout;
404 $confirm_required = 1;
407 unless($confirm_required) {
408 my $issue = AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
409 $template->param( issue => $issue );
410 $session->clear('auto_renew');
415 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
416 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
418 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
420 reserveborrowernumber => $question->{'resborrowernumber'}
425 itembiblionumber => $getmessageiteminfo->{'biblionumber'}
430 $template_params->{issuecount} = $issue;
433 $iteminfo->{subtitle} = GetRecordValue('subtitle', GetMarcBiblio($iteminfo->{biblionumber}), GetFrameworkCode($iteminfo->{biblionumber}));
434 $template_params->{item} = $iteminfo;
436 push @$checkout_infos, $template_params;
439 $template->param( %{$checkout_infos->[0]} );
440 $template->param( barcode => $barcodes->[0] );
442 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
444 checkout_infos => $checkout_infos,
445 confirmation_needed => $confirmation_needed,
450 # reload the borrower info for the sake of reseting the flags.....
451 if ($borrowernumber) {
452 $borrower = GetMemberDetails( $borrowernumber, 0 );
455 ##################################################################################
457 # show all reserves of this borrower, and the position of the reservation ....
458 if ($borrowernumber) {
459 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } );
460 my $waiting_holds = $holds->waiting;
462 holds_count => $holds->count(),
463 WaitingHolds => $waiting_holds,
466 $template->param( adultborrower => 1 ) if ( $borrower->{category_type} eq 'A' || $borrower->{category_type} eq 'I' );
470 my $flags = $borrower->{'flags'};
471 foreach my $flag ( sort keys %$flags ) {
472 $template->param( flagged=> 1);
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 'CREDITS' ) {
499 creditsmsg => $flags->{'CREDITS'}->{'message'},
500 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
505 if ( $flag eq 'CHARGES' ) {
508 chargesmsg => $flags->{'CHARGES'}->{'message'},
509 chargesamount => $flags->{'CHARGES'}->{'amount'},
512 elsif ( $flag eq 'CREDITS' ) {
515 creditsmsg => $flags->{'CREDITS'}->{'message'},
516 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
519 elsif ( $flag eq 'ODUES' ) {
522 oduesmsg => $flags->{'ODUES'}->{'message'}
525 my $items = $flags->{$flag}->{'itemlist'};
526 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
527 $template->param( nonreturns => 'true' );
530 elsif ( $flag eq 'NOTES' ) {
533 notesmsg => $flags->{'NOTES'}->{'message'}
539 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
540 $amountold =~ s/^.*\$//; # remove upto the $, if any
542 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
544 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
545 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
546 my $cnt = scalar(@$catcodes);
547 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
548 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
551 my $librarian_messages = Koha::Patron::Messages->search(
553 borrowernumber => $borrowernumber,
558 my $patron_messages = Koha::Patron::Messages->search(
560 borrowernumber => $borrowernumber,
565 if( $librarian_messages->count or $patron_messages->count ) {
566 $template->param(flagged => 1)
569 my $fast_cataloging = 0;
570 if (defined getframeworkinfo('FA')) {
574 if (C4::Context->preference('ExtendedPatronAttributes')) {
575 my $attributes = GetBorrowerAttributes($borrowernumber);
577 ExtendedPatronAttributes => 1,
578 extendedattributes => $attributes
582 ?'batch_checkout_view'
585 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
586 my $relatives_issues_count =
587 Koha::Database->new()->schema()->resultset('Issue')
588 ->count( { borrowernumber => \@relatives } );
590 my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{streettype} );
592 $template->param(%$borrower);
594 # Restore date if changed by holds and/or save stickyduedate to session
595 if ($restoreduedatespec || $stickyduedate) {
596 $duedatespec = $restoreduedatespec || $duedatespec;
598 if ($stickyduedate) {
599 $session->param( 'stickyduedate', $duedatespec );
601 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
606 librarian_messages => $librarian_messages,
607 patron_messages => $patron_messages,
608 findborrower => $findborrower,
609 borrower => $borrower,
610 borrowernumber => $borrowernumber,
611 categoryname => $borrower->{'description'},
613 branchname => GetBranchName($borrower->{'branchcode'}),
615 printername => $printer,
616 was_renewed => $query->param('was_renewed') ? 1 : 0,
617 expiry => $borrower->{'dateexpiry'},
618 roadtype => $roadtype,
619 amountold => $amountold,
620 barcodes => $barcodes,
621 stickyduedate => $stickyduedate,
622 duedatespec => $duedatespec,
623 restoreduedatespec => $restoreduedatespec,
625 totaldue => sprintf('%.2f', $total),
626 inprocess => $inprocess,
627 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
629 batch_allowed => $batch_allowed,
630 AudioAlerts => C4::Context->preference("AudioAlerts"),
631 fast_cataloging => $fast_cataloging,
632 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
633 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
634 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
635 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
636 RoutingSerials => C4::Context->preference('RoutingSerials'),
637 relatives_issues_count => $relatives_issues_count,
638 relatives_borrowernumbers => \@relatives,
641 my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
642 $template->param( picture => 1 ) if $patron_image;
644 # get authorised values with type of BOR_NOTES
646 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
649 debt_confirmed => $debt_confirmed,
650 SpecifyDueDate => $duedatespec_allow,
651 CircAutocompl => C4::Context->preference("CircAutocompl"),
652 canned_bor_notes_loop => $canned_notes,
653 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
654 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
657 output_html_with_http_headers $query, $cookie, $template->output;