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);
49 use Koha::Borrower::Modifications;
56 use List::MoreUtils qw/uniq/;
63 my $sessionID = $query->cookie("CGISESSID") ;
64 my $session = get_session($sessionID);
65 if (!C4::Context->userenv){
66 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
67 # no branch set we can't issue
68 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
74 my $barcode = $query->param('barcode');
75 # Barcode given by user could be '0'
76 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
77 $barcodes = [ $barcode ];
79 my $filefh = $query->upload('uploadfile');
81 while ( my $content = <$filefh> ) {
82 $content =~ s/[\r\n]*$//g;
83 push @$barcodes, $content if $content;
85 } elsif ( my $list = $query->param('barcodelist') ) {
86 push @$barcodes, split( /\s\n/, $list );
87 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
89 @$barcodes = $query->multi_param('barcodes');
93 $barcodes = [ uniq @$barcodes ];
95 my $template_name = q|circ/circulation.tt|;
96 my $borrowernumber = $query->param('borrowernumber');
97 my $borrower = $borrowernumber ? GetMember( borrowernumber => $borrowernumber ) : undef;
98 my $batch = $query->param('batch');
99 my $batch_allowed = 0;
100 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
101 $template_name = q|circ/circulation_batch_checkouts.tt|;
102 my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
103 if ( grep {/^$borrower->{categorycode}$/} @batch_category_codes ) {
110 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
112 template_name => $template_name,
115 authnotrequired => 0,
116 flagsrequired => { circulate => 'circulate_remaining_permissions' },
120 my $force_allow_issue = $query->param('forceallow') || 0;
121 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
122 $force_allow_issue = 0;
125 my $onsite_checkout = $query->param('onsite_checkout');
127 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
128 our %renew_failed = ();
129 for (@failedrenews) { $renew_failed{$_} = 1; }
131 my @failedreturns = $query->multi_param('failedreturn');
132 our %return_failed = ();
133 for (@failedreturns) { $return_failed{$_} = 1; }
135 my $searchtype = $query->param('searchtype') || q{contain};
137 my $findborrower = $query->param('findborrower') || q{};
138 $findborrower =~ s|,| |g;
140 my $branch = C4::Context->userenv->{'branch'};
142 if (C4::Context->preference("DisplayClearScreenButton")) {
143 $template->param(DisplayClearScreenButton => 1);
146 for my $barcode ( @$barcodes ) {
147 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
148 $barcode = barcodedecode($barcode)
149 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
152 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
153 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
154 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso', timeformat => '24hr' }); }
156 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
157 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
158 undef $restoreduedatespec;
160 my $issueconfirmed = $query->param('issueconfirmed');
161 my $cancelreserve = $query->param('cancelreserve');
162 my $print = $query->param('print') || q{};
163 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
164 my $charges = $query->param('charges') || q{};
166 # Check if stickyduedate is turned off
168 # was stickyduedate loaded from session?
169 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
170 $session->clear( 'stickyduedate' );
171 $stickyduedate = $query->param('stickyduedate');
172 $duedatespec = $query->param('duedatespec');
174 $session->param('auto_renew', scalar $query->param('auto_renew'));
177 $session->clear('auto_renew');
180 my ($datedue,$invalidduedate);
182 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
183 if( $onsite_checkout && !$duedatespec_allow ) {
184 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
185 $datedue .= ' 23:59:00';
186 } elsif( $duedatespec_allow ) {
187 if ( $duedatespec ) {
188 $datedue = eval { dt_from_string( $duedatespec ) };
191 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
196 # check and see if we should print
197 if ( @$barcodes == 0 && $print eq 'maybe' ) {
201 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
202 if ( @$barcodes == 0 && $charges eq 'yes' ) {
205 borrowernumber => $borrowernumber
209 if ( $print eq 'yes' && $borrowernumber ne '' ) {
210 if ( C4::Context->boolean_preference('printcirculationslips') ) {
211 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
212 NetworkPrint($letter->{content});
214 $query->param( 'borrowernumber', '' );
215 $borrowernumber = '';
219 # STEP 2 : FIND BORROWER
220 # if there is a list of find borrowers....
224 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
226 $borrowernumber = $borrower->{borrowernumber};
228 my $dt_params = { iDisplayLength => -1 };
229 my $results = C4::Utils::DataTables::Members::search(
231 searchmember => $findborrower,
232 searchtype => $searchtype,
233 dt_params => $dt_params,
236 my $borrowers = $results->{patrons};
237 if ( scalar @$borrowers == 1 ) {
238 $borrowernumber = $borrowers->[0]->{borrowernumber};
239 $query->param( 'borrowernumber', $borrowernumber );
240 $query->param( 'barcode', '' );
241 } elsif ( @$borrowers ) {
242 $template->param( borrowers => $borrowers );
244 $query->param( 'findborrower', '' );
245 $message = "'$findborrower'";
250 # get the borrower information.....
251 if ($borrowernumber) {
252 $borrower = GetMemberDetails( $borrowernumber, 0 );
253 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
255 # Warningdate is the date that the warning starts appearing
256 my ( $today_year, $today_month, $today_day) = Today();
257 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
258 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
259 # if the expiry date is before today ie they have expired
260 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
261 || Date_to_Days($today_year, $today_month, $today_day )
262 > Date_to_Days($warning_year, $warning_month, $warning_day) )
264 #borrowercard expired, no issues
267 noissues => ($force_allow_issue) ? 0 : "1",
268 forceallow => $force_allow_issue,
272 # check for NotifyBorrowerDeparture
273 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
274 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
275 Date_to_Days( $today_year, $today_month, $today_day ) )
277 # borrower card soon to expire warn librarian
278 $template->param( "warndeparture" => $borrower->{dateexpiry} ,
281 if (C4::Context->preference('ReturnBeforeExpiry')){
282 $template->param("returnbeforeexpiry" => 1);
287 issuecount => $issue,
291 if ( IsDebarred($borrowernumber) ) {
293 'userdebarred' => $borrower->{debarred},
294 'debarredcomment' => $borrower->{debarredcomment},
297 if ( $borrower->{debarred} ne "9999-12-31" ) {
298 $template->param( 'userdebarreddate' => $borrower->{debarred} );
310 for my $barcode ( @$barcodes ) {
311 my $template_params = { barcode => $barcode };
312 # always check for blockers on issuing
313 my ( $error, $question, $alerts ) =
314 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess, undef, { onsite_checkout => $onsite_checkout } );
315 my $blocker = $invalidduedate ? 1 : 0;
317 $template_params->{alert} = $alerts;
319 # Get the item title for more information
320 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
321 $template_params->{authvalcode_notforloan} =
322 C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'});
324 # Fix for bug 7494: optional checkout-time fallback search for a book
326 if ( $error->{'UNKNOWN_BARCODE'}
327 && C4::Context->preference("itemBarcodeFallbackSearch")
331 $template_params->{FALLBACK} = 1;
333 my $query = "kw=" . $barcode;
334 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
336 # if multiple hits, offer options to librarian
337 if ( $total_hits > 0 ) {
339 foreach my $hit ( @{$results} ) {
341 TransformMarcToKoha( C4::Context->dbh,
342 C4::Search::new_record_from_zebra('biblioserver',$hit) );
344 # offer all barcodes individually
345 if ( $chosen->{barcode} ) {
346 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
347 my %chosen_single = %{$chosen};
348 $chosen_single{barcode} = $barcode;
349 push( @options, \%chosen_single );
353 $template_params->{options} = \@options;
357 unless( $onsite_checkout and C4::Context->preference("OnSiteCheckoutsForce") ) {
358 delete $question->{'DEBT'} if ($debt_confirmed);
359 foreach my $impossible ( keys %$error ) {
360 $template_params->{$impossible} = $$error{$impossible};
361 $template_params->{IMPOSSIBLE} = 1;
365 my $iteminfo = GetBiblioFromItemNumber(undef, $barcode);
366 if( !$blocker || $force_allow_issue ){
367 my $confirm_required = 0;
368 unless($issueconfirmed){
369 # Get the item title for more information
370 $template_params->{additional_materials} = $iteminfo->{'materials'};
371 $template_params->{itemhomebranch} = $iteminfo->{'homebranch'};
373 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
374 foreach my $needsconfirmation ( keys %$question ) {
375 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
376 $template_params->{getTitleMessageIteminfo} = $iteminfo->{'title'};
377 $template_params->{getBarcodeMessageIteminfo} = $iteminfo->{'barcode'};
378 $template_params->{NEEDSCONFIRMATION} = 1;
379 $template_params->{onsite_checkout} = $onsite_checkout;
380 $confirm_required = 1;
383 unless($confirm_required) {
384 my $issue = AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
385 $template_params->{issue} = $issue;
386 $session->clear('auto_renew');
391 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
392 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
394 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
396 reserveborrowernumber => $question->{'resborrowernumber'},
397 itembiblionumber => $getmessageiteminfo->{'biblionumber'}
401 $template_params->{issuecount} = $issue;
404 $iteminfo->{subtitle} = GetRecordValue('subtitle', GetMarcBiblio($iteminfo->{biblionumber}), GetFrameworkCode($iteminfo->{biblionumber}));
405 $template_params->{item} = $iteminfo;
407 push @$checkout_infos, $template_params;
410 $template->param( %{$checkout_infos->[0]} );
411 $template->param( barcode => $barcodes->[0] );
413 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
415 checkout_infos => $checkout_infos,
416 confirmation_needed => $confirmation_needed,
421 # reload the borrower info for the sake of reseting the flags.....
422 if ($borrowernumber) {
423 $borrower = GetMemberDetails( $borrowernumber, 0 );
426 ##################################################################################
428 # show all reserves of this borrower, and the position of the reservation ....
429 if ($borrowernumber) {
430 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } );
431 my $waiting_holds = $holds->waiting;
433 holds_count => $holds->count(),
434 WaitingHolds => $waiting_holds,
437 $template->param( adultborrower => 1 ) if ( $borrower->{category_type} eq 'A' || $borrower->{category_type} eq 'I' );
441 my $flags = $borrower->{'flags'};
442 foreach my $flag ( sort keys %$flags ) {
443 $template->param( flagged=> 1);
444 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
445 if ( $flags->{$flag}->{'noissues'} ) {
447 noissues => ($force_allow_issue) ? 0 : 'true',
448 forceallow => $force_allow_issue,
450 if ( $flag eq 'GNA' ) {
451 $template->param( gna => 'true' );
453 elsif ( $flag eq 'LOST' ) {
454 $template->param( lost => 'true' );
456 elsif ( $flag eq 'DBARRED' ) {
457 $template->param( dbarred => 'true' );
459 elsif ( $flag eq 'CHARGES' ) {
462 chargesmsg => $flags->{'CHARGES'}->{'message'},
463 chargesamount => $flags->{'CHARGES'}->{'amount'},
464 charges_is_blocker => 1
467 elsif ( $flag eq 'CREDITS' ) {
470 creditsmsg => $flags->{'CREDITS'}->{'message'},
471 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
476 if ( $flag eq 'CHARGES' ) {
479 chargesmsg => $flags->{'CHARGES'}->{'message'},
480 chargesamount => $flags->{'CHARGES'}->{'amount'},
483 elsif ( $flag eq 'CREDITS' ) {
486 creditsmsg => $flags->{'CREDITS'}->{'message'},
487 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
490 elsif ( $flag eq 'ODUES' ) {
493 oduesmsg => $flags->{'ODUES'}->{'message'}
496 my $items = $flags->{$flag}->{'itemlist'};
497 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
498 $template->param( nonreturns => 'true' );
501 elsif ( $flag eq 'NOTES' ) {
504 notesmsg => $flags->{'NOTES'}->{'message'}
510 my $amountold = $borrower->{flags} ? $borrower->{flags}->{'CHARGES'}->{'message'} || 0 : 0;
511 $amountold =~ s/^.*\$//; # remove upto the $, if any
513 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
515 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
516 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
517 my $cnt = scalar(@$catcodes);
518 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
519 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
522 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
523 if($lib_messages_loop){ $template->param(flagged => 1 ); }
525 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
526 if($bor_messages_loop){ $template->param(flagged => 1 ); }
528 my $fast_cataloging = 0;
529 if (defined getframeworkinfo('FA')) {
533 if (C4::Context->preference('ExtendedPatronAttributes')) {
534 my $attributes = GetBorrowerAttributes($borrowernumber);
536 ExtendedPatronAttributes => 1,
537 extendedattributes => $attributes
541 ?'batch_checkout_view'
544 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
545 my $relatives_issues_count =
546 Koha::Database->new()->schema()->resultset('Issue')
547 ->count( { borrowernumber => \@relatives } );
549 my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{streettype} );
551 $template->param(%$borrower);
553 # Restore date if changed by holds and/or save stickyduedate to session
554 if ($restoreduedatespec || $stickyduedate) {
555 $duedatespec = $restoreduedatespec || $duedatespec;
557 if ($stickyduedate) {
558 $session->param( 'stickyduedate', $duedatespec );
560 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
565 lib_messages_loop => $lib_messages_loop,
566 bor_messages_loop => $bor_messages_loop,
567 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
568 findborrower => $findborrower,
569 borrower => $borrower,
570 borrowernumber => $borrowernumber,
571 categoryname => $borrower->{'description'},
573 branchname => GetBranchName($borrower->{'branchcode'}),
574 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
575 expiry => $borrower->{'dateexpiry'},
576 roadtype => $roadtype,
577 amountold => $amountold,
578 barcodes => $barcodes,
579 stickyduedate => $stickyduedate,
580 duedatespec => $duedatespec,
581 restoreduedatespec => $restoreduedatespec,
583 totaldue => sprintf('%.2f', $total),
584 inprocess => $inprocess,
585 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
587 batch_allowed => $batch_allowed,
588 AudioAlerts => C4::Context->preference("AudioAlerts"),
589 fast_cataloging => $fast_cataloging,
590 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
591 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
592 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
593 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
594 RoutingSerials => C4::Context->preference('RoutingSerials'),
595 relatives_issues_count => $relatives_issues_count,
596 relatives_borrowernumbers => \@relatives,
599 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
600 $template->param( picture => 1 ) if $picture;
602 # get authorised values with type of BOR_NOTES
604 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
607 debt_confirmed => $debt_confirmed,
608 SpecifyDueDate => $duedatespec_allow,
609 CircAutocompl => C4::Context->preference("CircAutocompl"),
610 canned_bor_notes_loop => $canned_notes,
611 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
612 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
613 nopermission => scalar $query->param('nopermission'),
614 modifications => Koha::Borrower::Modifications->GetModifications({ borrowernumber => $borrowernumber }),
617 output_html_with_http_headers $query, $cookie, $template->output;