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::Dates qw/format_date/;
34 use C4::Branch; # GetBranches
35 use C4::Koha; # GetPrinter
37 use C4::Utils::DataTables::Members;
46 use C4::Members::Attributes qw(GetBorrowerAttributes);
47 use Koha::Borrower::Debarments qw(GetDebarments IsDebarred);
57 use List::MoreUtils qw/uniq/;
65 my $sessionID = $query->cookie("CGISESSID") ;
66 my $session = get_session($sessionID);
68 # branch and printer are now defined by the userenv
69 # but first we have to check if someone has tried to change them
71 my $branch = $query->param('branch');
73 # update our session so the userenv is updated
74 $session->param('branch', $branch);
75 $session->param('branchname', GetBranchName($branch));
78 my $printer = $query->param('printer');
80 # update our session so the userenv is updated
81 $session->param('branchprinter', $printer);
84 if (!C4::Context->userenv && !$branch){
85 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
86 # no branch set we can't issue
87 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
93 if ( my $barcode = $query->param('barcode') ) {
94 $barcodes = [ $barcode ];
97 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
99 template_name => 'circ/circulation.tt',
102 authnotrequired => 0,
103 flagsrequired => { circulate => 'circulate_remaining_permissions' },
107 my $branches = GetBranches();
109 my $force_allow_issue = $query->param('forceallow') || 0;
110 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
111 $force_allow_issue = 0;
114 my $onsite_checkout = $query->param('onsite_checkout');
116 my @failedrenews = $query->param('failedrenew'); # expected to be itemnumbers
117 our %renew_failed = ();
118 for (@failedrenews) { $renew_failed{$_} = 1; }
120 my @failedreturns = $query->param('failedreturn');
121 our %return_failed = ();
122 for (@failedreturns) { $return_failed{$_} = 1; }
124 my $findborrower = $query->param('findborrower') || q{};
125 $findborrower =~ s|,| |g;
126 my $borrowernumber = $query->param('borrowernumber');
128 $branch = C4::Context->userenv->{'branch'};
129 $printer = C4::Context->userenv->{'branchprinter'};
132 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
133 if (C4::Context->preference("AutoLocation") != 1) {
134 $template->param(ManualLocation => 1);
137 if (C4::Context->preference("DisplayClearScreenButton")) {
138 $template->param(DisplayClearScreenButton => 1);
141 for my $barcode ( @$barcodes ) {
142 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
143 $barcode = barcodedecode($barcode)
144 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
147 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
148 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
149 my $issueconfirmed = $query->param('issueconfirmed');
150 my $cancelreserve = $query->param('cancelreserve');
151 my $print = $query->param('print') || q{};
152 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
153 my $charges = $query->param('charges') || q{};
155 # Check if stickyduedate is turned off
157 # was stickyduedate loaded from session?
158 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
159 $session->clear( 'stickyduedate' );
160 $stickyduedate = $query->param('stickyduedate');
161 $duedatespec = $query->param('duedatespec');
163 $session->param('auto_renew', $query->param('auto_renew'));
166 $session->clear('auto_renew');
169 my ($datedue,$invalidduedate);
171 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
172 if( $onsite_checkout && !$duedatespec_allow ) {
173 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
174 $datedue .= ' 23:59:00';
175 } elsif( $duedatespec_allow ) {
177 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
178 $datedue = dt_from_string($duedatespec);
181 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
186 our $todaysdate = C4::Dates->new->output('iso');
188 # check and see if we should print
189 if ( @$barcodes == 0 && $print eq 'maybe' ) {
193 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
194 if ( @$barcodes == 0 && $charges eq 'yes' ) {
197 borrowernumber => $borrowernumber
201 if ( $print eq 'yes' && $borrowernumber ne '' ) {
202 if ( C4::Context->boolean_preference('printcirculationslips') ) {
203 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
204 NetworkPrint($letter->{content});
206 $query->param( 'borrowernumber', '' );
207 $borrowernumber = '';
211 # STEP 2 : FIND BORROWER
212 # if there is a list of find borrowers....
216 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
218 $borrowernumber = $borrower->{borrowernumber};
220 my $dt_params = { iDisplayLength => -1 };
221 my $results = C4::Utils::DataTables::Members::search(
223 searchmember => $findborrower,
224 dt_params => $dt_params,
227 my $borrowers = $results->{patrons};
228 if ( scalar @$borrowers == 1 ) {
229 $borrowernumber = $borrowers->[0]->{borrowernumber};
230 $query->param( 'borrowernumber', $borrowernumber );
231 $query->param( 'barcode', '' );
232 } elsif ( @$borrowers ) {
233 $template->param( borrowers => $borrowers );
235 $query->param( 'findborrower', '' );
236 $message = "'$findborrower'";
241 # get the borrower information.....
243 if ($borrowernumber) {
244 $borrower = GetMemberDetails( $borrowernumber, 0 );
245 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
247 # Warningdate is the date that the warning starts appearing
248 my ( $today_year, $today_month, $today_day) = Today();
249 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
250 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
251 # Renew day is calculated by adding the enrolment period to today
252 my ( $renew_year, $renew_month, $renew_day);
253 if ($enrol_year*$enrol_month*$enrol_day>0) {
254 ( $renew_year, $renew_month, $renew_day) =
255 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
256 0 , $borrower->{'enrolmentperiod'});
258 # if the expiry date is before today ie they have expired
259 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
260 || Date_to_Days($today_year, $today_month, $today_day )
261 > Date_to_Days($warning_year, $warning_month, $warning_day) )
263 #borrowercard expired, no issues
266 noissues => ($force_allow_issue) ? 0 : "1",
267 forceallow => $force_allow_issue,
269 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
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" => format_date($borrower->{dateexpiry}),
280 if (C4::Context->preference('ReturnBeforeExpiry')){
281 $template->param("returnbeforeexpiry" => 1);
286 issuecount => $issue,
290 if ( IsDebarred($borrowernumber) ) {
292 'userdebarred' => $borrower->{debarred},
293 'debarredcomment' => $borrower->{debarredcomment},
296 if ( $borrower->{debarred} ne "9999-12-31" ) {
297 $template->param( 'userdebarreddate' =>
298 C4::Dates::format_date( $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")
330 $template_params->{FALLBACK} = 1;
332 my $query = "kw=" . $barcode;
333 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
335 # if multiple hits, offer options to librarian
336 if ( $total_hits > 0 ) {
338 foreach my $hit ( @{$results} ) {
340 TransformMarcToKoha( C4::Context->dbh,
341 C4::Search::new_record_from_zebra('biblioserver',$hit) );
343 # offer all barcodes individually
344 if ( $chosen->{barcode} ) {
345 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
346 my %chosen_single = %{$chosen};
347 $chosen_single{barcode} = $barcode;
348 push( @options, \%chosen_single );
352 $template_params->{options} = \@options;
356 unless( $onsite_checkout and C4::Context->preference("OnSiteCheckoutsForce") ) {
357 delete $question->{'DEBT'} if ($debt_confirmed);
358 foreach my $impossible ( keys %$error ) {
359 $template_params->{$impossible} = $$error{$impossible};
360 $template_params->{IMPOSSIBLE} = 1;
364 my $iteminfo = GetBiblioFromItemNumber(undef, $barcode);
365 if( !$blocker || $force_allow_issue ){
366 my $confirm_required = 0;
367 unless($issueconfirmed){
368 # Get the item title for more information
369 $template_params->{additional_materials} = $iteminfo->{'materials'};
370 $template_params->{itemhomebranch} = $iteminfo->{'homebranch'};
372 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
373 foreach my $needsconfirmation ( keys %$question ) {
374 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
375 $template_params->{getTitleMessageIteminfo} = $iteminfo->{'title'};
376 $template_params->{getBarcodeMessageIteminfo} = $iteminfo->{'barcode'};
377 $template_params->{NEEDSCONFIRMATION} = 1;
378 $template_params->{onsite_checkout} => $onsite_checkout,
379 $confirm_required = 1;
382 unless($confirm_required) {
383 my $issue = AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
384 $template->param( issue => $issue );
385 $session->clear('auto_renew');
390 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
392 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
394 reserveborrowernumber => $question->{'resborrowernumber'},
395 itembiblionumber => $getmessageiteminfo->{'biblionumber'}
399 $template_params->{issuecount} = $issue;
402 $iteminfo->{subtitle} = GetRecordValue('subtitle', GetMarcBiblio($iteminfo->{biblionumber}), GetFrameworkCode($iteminfo->{biblionumber}));
403 $template_params->{item} = $iteminfo;
405 push @$checkout_infos, $template_params;
408 $template->param( %{$checkout_infos->[0]} );
409 $template->param( barcode => $barcodes->[0] );
412 # reload the borrower info for the sake of reseting the flags.....
413 if ($borrowernumber) {
414 $borrower = GetMemberDetails( $borrowernumber, 0 );
417 ##################################################################################
419 # show all reserves of this borrower, and the position of the reservation ....
420 if ($borrowernumber) {
421 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } );
423 holds_count => $holds->count(),
424 WaitingHolds => scalar $holds->waiting(),
427 $template->param( adultborrower => 1 ) if ( $borrower->{category_type} eq 'A' || $borrower->{category_type} eq 'I' );
431 my $flags = $borrower->{'flags'};
432 foreach my $flag ( sort keys %$flags ) {
433 $template->param( flagged=> 1);
434 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
435 if ( $flags->{$flag}->{'noissues'} ) {
437 noissues => ($force_allow_issue) ? 0 : 'true',
438 forceallow => $force_allow_issue,
440 if ( $flag eq 'GNA' ) {
441 $template->param( gna => 'true' );
443 elsif ( $flag eq 'LOST' ) {
444 $template->param( lost => 'true' );
446 elsif ( $flag eq 'DBARRED' ) {
447 $template->param( dbarred => 'true' );
449 elsif ( $flag eq 'CHARGES' ) {
452 chargesmsg => $flags->{'CHARGES'}->{'message'},
453 chargesamount => $flags->{'CHARGES'}->{'amount'},
454 charges_is_blocker => 1
457 elsif ( $flag eq 'CREDITS' ) {
460 creditsmsg => $flags->{'CREDITS'}->{'message'},
461 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
466 if ( $flag eq 'CHARGES' ) {
469 chargesmsg => $flags->{'CHARGES'}->{'message'},
470 chargesamount => $flags->{'CHARGES'}->{'amount'},
473 elsif ( $flag eq 'CREDITS' ) {
476 creditsmsg => $flags->{'CREDITS'}->{'message'},
477 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
480 elsif ( $flag eq 'ODUES' ) {
483 oduesmsg => $flags->{'ODUES'}->{'message'}
486 my $items = $flags->{$flag}->{'itemlist'};
487 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
488 $template->param( nonreturns => 'true' );
491 elsif ( $flag eq 'NOTES' ) {
494 notesmsg => $flags->{'NOTES'}->{'message'}
500 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
501 $amountold =~ s/^.*\$//; # remove upto the $, if any
503 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
505 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
506 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
507 my $cnt = scalar(@$catcodes);
508 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
509 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
512 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
513 if($lib_messages_loop){ $template->param(flagged => 1 ); }
515 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
516 if($bor_messages_loop){ $template->param(flagged => 1 ); }
518 my $fast_cataloging = 0;
519 if (defined getframeworkinfo('FA')) {
523 if (C4::Context->preference('ExtendedPatronAttributes')) {
524 my $attributes = GetBorrowerAttributes($borrowernumber);
526 ExtendedPatronAttributes => 1,
527 extendedattributes => $attributes
531 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
532 my $relatives_issues_count =
533 Koha::Database->new()->schema()->resultset('Issue')
534 ->count( { borrowernumber => \@relatives } );
536 my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{streettype} );
538 $template->param(%$borrower);
541 lib_messages_loop => $lib_messages_loop,
542 bor_messages_loop => $bor_messages_loop,
543 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
544 findborrower => $findborrower,
545 borrower => $borrower,
546 borrowernumber => $borrowernumber,
548 branchname => GetBranchName($borrower->{'branchcode'}),
550 printername => $printer,
551 was_renewed => $query->param('was_renewed') ? 1 : 0,
552 expiry => format_date($borrower->{'dateexpiry'}),
553 roadtype => $roadtype,
554 amountold => $amountold,
555 barcodes => $barcodes,
556 stickyduedate => $stickyduedate,
557 duedatespec => $duedatespec,
559 totaldue => sprintf('%.2f', $total),
560 inprocess => $inprocess,
561 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
563 soundon => C4::Context->preference("SoundOn"),
564 fast_cataloging => $fast_cataloging,
565 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
566 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
567 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
568 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
569 RoutingSerials => C4::Context->preference('RoutingSerials'),
570 relatives_issues_count => $relatives_issues_count,
571 relatives_borrowernumbers => \@relatives,
574 # save stickyduedate to session
575 if ($stickyduedate) {
576 $session->param( 'stickyduedate', $duedatespec );
579 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
580 $template->param( picture => 1 ) if $picture;
582 # get authorised values with type of BOR_NOTES
584 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
587 debt_confirmed => $debt_confirmed,
588 SpecifyDueDate => $duedatespec_allow,
589 CircAutocompl => C4::Context->preference("CircAutocompl"),
590 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
591 canned_bor_notes_loop => $canned_notes,
592 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
593 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
596 output_html_with_http_headers $query, $cookie, $template->output;