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::Borrower::Debarments qw(GetDebarments IsDebarred);
56 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 if ( my $barcode = $query->param('barcode') ) {
93 $barcodes = [ $barcode ];
95 my $filefh = $query->upload('uploadfile');
97 while ( my $content = <$filefh> ) {
98 $content =~ s/[\r\n]*$//g;
99 push @$barcodes, $content if $content;
101 } elsif ( my $list = $query->param('barcodelist') ) {
102 push @$barcodes, split( /\s\n/, $list );
103 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
105 @$barcodes = $query->param('barcodes');
109 $barcodes = [ uniq @$barcodes ];
111 my $template_name = q|circ/circulation.tt|;
112 my $borrowernumber = $query->param('borrowernumber');
113 my $borrower = $borrowernumber ? GetMember( borrowernumber => $borrowernumber ) : undef;
114 my $batch = $query->param('batch');
115 my $batch_allowed = 0;
116 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
117 $template_name = q|circ/circulation_batch_checkouts.tt|;
118 my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
119 if ( grep {/^$borrower->{categorycode}$/} @batch_category_codes ) {
126 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
128 template_name => $template_name,
131 authnotrequired => 0,
132 flagsrequired => { circulate => 'circulate_remaining_permissions' },
136 my $branches = GetBranches();
138 my $force_allow_issue = $query->param('forceallow') || 0;
139 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
140 $force_allow_issue = 0;
143 my $onsite_checkout = $query->param('onsite_checkout');
145 my @failedrenews = $query->param('failedrenew'); # expected to be itemnumbers
146 our %renew_failed = ();
147 for (@failedrenews) { $renew_failed{$_} = 1; }
149 my @failedreturns = $query->param('failedreturn');
150 our %return_failed = ();
151 for (@failedreturns) { $return_failed{$_} = 1; }
153 my $findborrower = $query->param('findborrower') || q{};
154 $findborrower =~ s|,| |g;
156 $branch = C4::Context->userenv->{'branch'};
157 $printer = C4::Context->userenv->{'branchprinter'};
160 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
161 if (C4::Context->preference("AutoLocation") != 1) {
162 $template->param(ManualLocation => 1);
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' }); };
179 my $issueconfirmed = $query->param('issueconfirmed');
180 my $cancelreserve = $query->param('cancelreserve');
181 my $print = $query->param('print') || q{};
182 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
183 my $charges = $query->param('charges') || q{};
185 # Check if stickyduedate is turned off
187 # was stickyduedate loaded from session?
188 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
189 $session->clear( 'stickyduedate' );
190 $stickyduedate = $query->param('stickyduedate');
191 $duedatespec = $query->param('duedatespec');
193 $session->param('auto_renew', $query->param('auto_renew'));
196 $session->clear('auto_renew');
199 my ($datedue,$invalidduedate);
201 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
202 if( $onsite_checkout && !$duedatespec_allow ) {
203 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
204 $datedue .= ' 23:59:00';
205 } elsif( $duedatespec_allow ) {
207 $datedue = eval { dt_from_string( $datedue ) };
210 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$datedue );
215 # check and see if we should print
216 if ( @$barcodes == 0 && $print eq 'maybe' ) {
220 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
221 if ( @$barcodes == 0 && $charges eq 'yes' ) {
224 borrowernumber => $borrowernumber
228 if ( $print eq 'yes' && $borrowernumber ne '' ) {
229 if ( C4::Context->boolean_preference('printcirculationslips') ) {
230 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
231 NetworkPrint($letter->{content});
233 $query->param( 'borrowernumber', '' );
234 $borrowernumber = '';
238 # STEP 2 : FIND BORROWER
239 # if there is a list of find borrowers....
243 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
245 $borrowernumber = $borrower->{borrowernumber};
247 my $dt_params = { iDisplayLength => -1 };
248 my $results = C4::Utils::DataTables::Members::search(
250 searchmember => $findborrower,
251 searchtype => 'contain',
252 dt_params => $dt_params,
255 my $borrowers = $results->{patrons};
256 if ( scalar @$borrowers == 1 ) {
257 $borrowernumber = $borrowers->[0]->{borrowernumber};
258 $query->param( 'borrowernumber', $borrowernumber );
259 $query->param( 'barcode', '' );
260 } elsif ( @$borrowers ) {
261 $template->param( borrowers => $borrowers );
263 $query->param( 'findborrower', '' );
264 $message = "'$findborrower'";
269 # get the borrower information.....
270 if ($borrowernumber) {
271 $borrower = GetMemberDetails( $borrowernumber, 0 );
272 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
274 # Warningdate is the date that the warning starts appearing
275 my ( $today_year, $today_month, $today_day) = Today();
276 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
277 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
278 # Renew day is calculated by adding the enrolment period to today
279 my ( $renew_year, $renew_month, $renew_day);
280 if ($enrol_year*$enrol_month*$enrol_day>0) {
281 ( $renew_year, $renew_month, $renew_day) =
282 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
283 0 , $borrower->{'enrolmentperiod'});
285 # if the expiry date is before today ie they have expired
286 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
287 || Date_to_Days($today_year, $today_month, $today_day )
288 > Date_to_Days($warning_year, $warning_month, $warning_day) )
290 #borrowercard expired, no issues
293 noissues => ($force_allow_issue) ? 0 : "1",
294 forceallow => $force_allow_issue,
296 renewaldate => "$renew_year-$renew_month-$renew_day",
299 # check for NotifyBorrowerDeparture
300 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
301 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
302 Date_to_Days( $today_year, $today_month, $today_day ) )
304 # borrower card soon to expire warn librarian
305 $template->param( "warndeparture" => $borrower->{dateexpiry} ,
308 if (C4::Context->preference('ReturnBeforeExpiry')){
309 $template->param("returnbeforeexpiry" => 1);
314 issuecount => $issue,
318 if ( IsDebarred($borrowernumber) ) {
320 'userdebarred' => $borrower->{debarred},
321 'debarredcomment' => $borrower->{debarredcomment},
324 if ( $borrower->{debarred} ne "9999-12-31" ) {
325 $template->param( 'userdebarreddate' => $borrower->{debarred} );
337 for my $barcode ( @$barcodes ) {
338 my $template_params = { barcode => $barcode };
339 # always check for blockers on issuing
340 my ( $error, $question, $alerts ) =
341 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess, undef, { onsite_checkout => $onsite_checkout } );
342 my $blocker = $invalidduedate ? 1 : 0;
344 $template_params->{alert} = $alerts;
346 # Get the item title for more information
347 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
348 $template_params->{authvalcode_notforloan} =
349 C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'});
351 # Fix for bug 7494: optional checkout-time fallback search for a book
353 if ( $error->{'UNKNOWN_BARCODE'}
354 && C4::Context->preference("itemBarcodeFallbackSearch")
358 $template_params->{FALLBACK} = 1;
360 my $query = "kw=" . $barcode;
361 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
363 # if multiple hits, offer options to librarian
364 if ( $total_hits > 0 ) {
366 foreach my $hit ( @{$results} ) {
368 TransformMarcToKoha( C4::Context->dbh,
369 C4::Search::new_record_from_zebra('biblioserver',$hit) );
371 # offer all barcodes individually
372 if ( $chosen->{barcode} ) {
373 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
374 my %chosen_single = %{$chosen};
375 $chosen_single{barcode} = $barcode;
376 push( @options, \%chosen_single );
380 $template_params->{options} = \@options;
384 unless( $onsite_checkout and C4::Context->preference("OnSiteCheckoutsForce") ) {
385 delete $question->{'DEBT'} if ($debt_confirmed);
386 foreach my $impossible ( keys %$error ) {
387 $template_params->{$impossible} = $$error{$impossible};
388 $template_params->{IMPOSSIBLE} = 1;
392 my $iteminfo = GetBiblioFromItemNumber(undef, $barcode);
393 if( !$blocker || $force_allow_issue ){
394 my $confirm_required = 0;
395 unless($issueconfirmed){
396 # Get the item title for more information
397 $template_params->{additional_materials} = $iteminfo->{'materials'};
398 $template_params->{itemhomebranch} = $iteminfo->{'homebranch'};
400 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
401 foreach my $needsconfirmation ( keys %$question ) {
402 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
403 $template_params->{getTitleMessageIteminfo} = $iteminfo->{'title'};
404 $template_params->{getBarcodeMessageIteminfo} = $iteminfo->{'barcode'};
405 $template_params->{NEEDSCONFIRMATION} = 1;
406 $template_params->{onsite_checkout} = $onsite_checkout;
407 $confirm_required = 1;
410 unless($confirm_required) {
411 my $issue = AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
412 $template->param( issue => $issue );
413 $session->clear('auto_renew');
418 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
419 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
421 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
423 reserveborrowernumber => $question->{'resborrowernumber'},
424 itembiblionumber => $getmessageiteminfo->{'biblionumber'}
428 $template_params->{issuecount} = $issue;
431 $iteminfo->{subtitle} = GetRecordValue('subtitle', GetMarcBiblio($iteminfo->{biblionumber}), GetFrameworkCode($iteminfo->{biblionumber}));
432 $template_params->{item} = $iteminfo;
434 push @$checkout_infos, $template_params;
437 $template->param( %{$checkout_infos->[0]} );
438 $template->param( barcode => $barcodes->[0] );
440 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
442 checkout_infos => $checkout_infos,
443 confirmation_needed => $confirmation_needed,
448 # reload the borrower info for the sake of reseting the flags.....
449 if ($borrowernumber) {
450 $borrower = GetMemberDetails( $borrowernumber, 0 );
453 ##################################################################################
455 # show all reserves of this borrower, and the position of the reservation ....
456 if ($borrowernumber) {
457 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } );
459 holds_count => $holds->count(),
460 WaitingHolds => scalar $holds->waiting(),
463 $template->param( adultborrower => 1 ) if ( $borrower->{category_type} eq 'A' || $borrower->{category_type} eq 'I' );
467 my $flags = $borrower->{'flags'};
468 foreach my $flag ( sort keys %$flags ) {
469 $template->param( flagged=> 1);
470 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
471 if ( $flags->{$flag}->{'noissues'} ) {
473 noissues => ($force_allow_issue) ? 0 : 'true',
474 forceallow => $force_allow_issue,
476 if ( $flag eq 'GNA' ) {
477 $template->param( gna => 'true' );
479 elsif ( $flag eq 'LOST' ) {
480 $template->param( lost => 'true' );
482 elsif ( $flag eq 'DBARRED' ) {
483 $template->param( dbarred => 'true' );
485 elsif ( $flag eq 'CHARGES' ) {
488 chargesmsg => $flags->{'CHARGES'}->{'message'},
489 chargesamount => $flags->{'CHARGES'}->{'amount'},
490 charges_is_blocker => 1
493 elsif ( $flag eq 'CREDITS' ) {
496 creditsmsg => $flags->{'CREDITS'}->{'message'},
497 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
502 if ( $flag eq 'CHARGES' ) {
505 chargesmsg => $flags->{'CHARGES'}->{'message'},
506 chargesamount => $flags->{'CHARGES'}->{'amount'},
509 elsif ( $flag eq 'CREDITS' ) {
512 creditsmsg => $flags->{'CREDITS'}->{'message'},
513 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
516 elsif ( $flag eq 'ODUES' ) {
519 oduesmsg => $flags->{'ODUES'}->{'message'}
522 my $items = $flags->{$flag}->{'itemlist'};
523 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
524 $template->param( nonreturns => 'true' );
527 elsif ( $flag eq 'NOTES' ) {
530 notesmsg => $flags->{'NOTES'}->{'message'}
536 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
537 $amountold =~ s/^.*\$//; # remove upto the $, if any
539 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
541 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
542 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
543 my $cnt = scalar(@$catcodes);
544 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
545 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
548 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
549 if($lib_messages_loop){ $template->param(flagged => 1 ); }
551 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
552 if($bor_messages_loop){ $template->param(flagged => 1 ); }
554 my $fast_cataloging = 0;
555 if (defined getframeworkinfo('FA')) {
559 if (C4::Context->preference('ExtendedPatronAttributes')) {
560 my $attributes = GetBorrowerAttributes($borrowernumber);
562 ExtendedPatronAttributes => 1,
563 extendedattributes => $attributes
567 ?'batch_checkout_view'
570 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
571 my $relatives_issues_count =
572 Koha::Database->new()->schema()->resultset('Issue')
573 ->count( { borrowernumber => \@relatives } );
575 my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{streettype} );
577 $template->param(%$borrower);
580 lib_messages_loop => $lib_messages_loop,
581 bor_messages_loop => $bor_messages_loop,
582 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
583 findborrower => $findborrower,
584 borrower => $borrower,
585 borrowernumber => $borrowernumber,
587 branchname => GetBranchName($borrower->{'branchcode'}),
589 printername => $printer,
590 was_renewed => $query->param('was_renewed') ? 1 : 0,
591 expiry => $borrower->{'dateexpiry'},
592 roadtype => $roadtype,
593 amountold => $amountold,
594 barcodes => $barcodes,
595 stickyduedate => $stickyduedate,
596 duedatespec => $duedatespec,
598 totaldue => sprintf('%.2f', $total),
599 inprocess => $inprocess,
600 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
602 batch_allowed => $batch_allowed,
603 soundon => C4::Context->preference("SoundOn"),
604 fast_cataloging => $fast_cataloging,
605 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
606 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
607 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
608 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
609 RoutingSerials => C4::Context->preference('RoutingSerials'),
610 relatives_issues_count => $relatives_issues_count,
611 relatives_borrowernumbers => \@relatives,
614 # save stickyduedate to session
615 if ($stickyduedate) {
616 $session->param( 'stickyduedate', $duedatespec );
619 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
620 $template->param( picture => 1 ) if $picture;
622 # get authorised values with type of BOR_NOTES
624 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
627 debt_confirmed => $debt_confirmed,
628 SpecifyDueDate => $duedatespec_allow,
629 CircAutocompl => C4::Context->preference("CircAutocompl"),
630 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
631 canned_bor_notes_loop => $canned_notes,
632 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
633 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
636 output_html_with_http_headers $query, $cookie, $template->output;