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 under the
13 # terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 2 of the License, or (at your option) any later
17 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
18 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License along
22 # with Koha; if not, write to the Free Software Foundation, Inc.,
23 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
30 use C4::Auth qw/:DEFAULT get_session haspermission/;
31 use C4::Dates qw/format_date/;
32 use C4::Branch; # GetBranches
33 use C4::Koha; # GetPrinter
42 use C4::Members::Attributes qw(GetBorrowerAttributes);
43 use Koha::Borrower::Debarments qw(GetDebarments IsDebarred);
53 use List::MoreUtils qw/uniq/;
61 my $sessionID = $query->cookie("CGISESSID") ;
62 my $session = get_session($sessionID);
64 # branch and printer are now defined by the userenv
65 # but first we have to check if someone has tried to change them
67 my $branch = $query->param('branch');
69 # update our session so the userenv is updated
70 $session->param('branch', $branch);
71 $session->param('branchname', GetBranchName($branch));
74 my $printer = $query->param('printer');
76 # update our session so the userenv is updated
77 $session->param('branchprinter', $printer);
80 if (!C4::Context->userenv && !$branch){
81 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
82 # no branch set we can't issue
83 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
88 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
90 template_name => 'circ/circulation.tt',
94 flagsrequired => { circulate => 'circulate_remaining_permissions' },
98 my $branches = GetBranches();
100 my $force_allow_issue = $query->param('forceallow') || 0;
101 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
102 $force_allow_issue = 0;
105 my @failedrenews = $query->param('failedrenew'); # expected to be itemnumbers
106 our %renew_failed = ();
107 for (@failedrenews) { $renew_failed{$_} = 1; }
109 my @failedreturns = $query->param('failedreturn');
110 our %return_failed = ();
111 for (@failedreturns) { $return_failed{$_} = 1; }
113 my $findborrower = $query->param('findborrower') || q{};
114 $findborrower =~ s|,| |g;
115 my $borrowernumber = $query->param('borrowernumber');
117 $branch = C4::Context->userenv->{'branch'};
118 $printer = C4::Context->userenv->{'branchprinter'};
121 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
122 if (C4::Context->preference("AutoLocation") != 1) {
123 $template->param(ManualLocation => 1);
126 if (C4::Context->preference("DisplayClearScreenButton")) {
127 $template->param(DisplayClearScreenButton => 1);
130 my $barcode = $query->param('barcode') || q{};
131 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
133 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
134 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
135 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
136 my $issueconfirmed = $query->param('issueconfirmed');
137 my $cancelreserve = $query->param('cancelreserve');
138 my $print = $query->param('print') || q{};
139 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
140 my $charges = $query->param('charges') || q{};
142 # Check if stickyduedate is turned off
144 # was stickyduedate loaded from session?
145 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
146 $session->clear( 'stickyduedate' );
147 $stickyduedate = $query->param('stickyduedate');
148 $duedatespec = $query->param('duedatespec');
150 $session->param('auto_renew', $query->param('auto_renew'));
153 $session->clear('auto_renew');
156 my ($datedue,$invalidduedate);
158 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
159 if($duedatespec_allow){
161 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
162 $datedue = dt_from_string($duedatespec);
165 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
170 our $todaysdate = C4::Dates->new->output('iso');
172 # check and see if we should print
173 if ( $barcode eq '' && $print eq 'maybe' ) {
177 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
178 if ( $barcode eq '' && $charges eq 'yes' ) {
181 borrowernumber => $borrowernumber
185 if ( $print eq 'yes' && $borrowernumber ne '' ) {
186 if ( C4::Context->boolean_preference('printcirculationslips') ) {
187 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
188 NetworkPrint($letter->{content});
190 $query->param( 'borrowernumber', '' );
191 $borrowernumber = '';
195 # STEP 2 : FIND BORROWER
196 # if there is a list of find borrowers....
201 my $borrowers = Search($findborrower, 'cardnumber') || [];
202 if (C4::Context->preference("AddPatronLists")) {
204 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
206 if (C4::Context->preference("AddPatronLists")=~/code/){
207 my $categories = GetBorrowercategoryList;
208 $categories->[0]->{'first'} = 1;
209 $template->param(categories=>$categories);
212 if ( @$borrowers == 0 ) {
213 $query->param( 'findborrower', '' );
214 $message = "'$findborrower'";
216 elsif ( @$borrowers == 1 ) {
217 $borrowernumber = $borrowers->[0]->{'borrowernumber'};
218 $query->param( 'borrowernumber', $borrowernumber );
219 $query->param( 'barcode', '' );
222 $borrowerslist = $borrowers;
226 # get the borrower information.....
228 if ($borrowernumber) {
229 $borrower = GetMemberDetails( $borrowernumber, 0 );
230 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
232 # Warningdate is the date that the warning starts appearing
233 my ( $today_year, $today_month, $today_day) = Today();
234 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
235 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
236 # Renew day is calculated by adding the enrolment period to today
237 my ( $renew_year, $renew_month, $renew_day);
238 if ($enrol_year*$enrol_month*$enrol_day>0) {
239 ( $renew_year, $renew_month, $renew_day) =
240 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
241 0 , $borrower->{'enrolmentperiod'});
243 # if the expiry date is before today ie they have expired
244 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
245 || Date_to_Days($today_year, $today_month, $today_day )
246 > Date_to_Days($warning_year, $warning_month, $warning_day) )
248 #borrowercard expired, no issues
251 noissues => ($force_allow_issue) ? 0 : "1",
252 forceallow => $force_allow_issue,
254 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
257 # check for NotifyBorrowerDeparture
258 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
259 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
260 Date_to_Days( $today_year, $today_month, $today_day ) )
262 # borrower card soon to expire warn librarian
263 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
265 if (C4::Context->preference('ReturnBeforeExpiry')){
266 $template->param("returnbeforeexpiry" => 1);
271 issuecount => $issue,
275 if ( IsDebarred($borrowernumber) ) {
277 'userdebarred' => $borrower->{debarred},
278 'debarredcomment' => $borrower->{debarredcomment},
281 if ( $borrower->{debarred} ne "9999-12-31" ) {
282 $template->param( 'userdebarreddate' =>
283 C4::Dates::format_date( $borrower->{debarred} ) );
294 # always check for blockers on issuing
295 my ( $error, $question, $alerts ) =
296 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
297 my $blocker = $invalidduedate ? 1 : 0;
299 $template->param( alert => $alerts );
301 # Get the item title for more information
302 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
304 authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
306 # Fix for bug 7494: optional checkout-time fallback search for a book
308 if ( $error->{'UNKNOWN_BARCODE'}
309 && C4::Context->preference("itemBarcodeFallbackSearch") )
311 $template->param( FALLBACK => 1 );
313 my $query = "kw=" . $barcode;
314 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
316 # if multiple hits, offer options to librarian
317 if ( $total_hits > 0 ) {
319 foreach my $hit ( @{$results} ) {
321 TransformMarcToKoha( C4::Context->dbh,
322 C4::Search::new_record_from_zebra('biblioserver',$hit) );
324 # offer all barcodes individually
325 if ( $chosen->{barcode} ) {
326 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
327 my %chosen_single = %{$chosen};
328 $chosen_single{barcode} = $barcode;
329 push( @options, \%chosen_single );
333 $template->param( options => \@options );
337 delete $question->{'DEBT'} if ($debt_confirmed);
338 foreach my $impossible ( keys %$error ) {
340 $impossible => $$error{$impossible},
345 if( !$blocker || $force_allow_issue ){
346 my $confirm_required = 0;
347 unless($issueconfirmed){
348 # Get the item title for more information
349 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
350 $template->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
351 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
353 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
354 foreach my $needsconfirmation ( keys %$question ) {
356 $needsconfirmation => $$question{$needsconfirmation},
357 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
358 getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
359 NEEDSCONFIRMATION => 1
361 $confirm_required = 1;
364 unless($confirm_required) {
365 AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, $session->param('auto_renew') );
366 $session->clear('auto_renew');
371 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
372 $template->param( issuecount => $issue );
375 # reload the borrower info for the sake of reseting the flags.....
376 if ($borrowernumber) {
377 $borrower = GetMemberDetails( $borrowernumber, 0 );
380 ##################################################################################
382 # show all reserves of this borrower, and the position of the reservation ....
383 if ($borrowernumber) {
385 holds_count => Koha::Database->new()->schema()->resultset('Reserve')
386 ->count( { borrowernumber => $borrowernumber } ) );
388 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
394 if ($borrowerslist) {
396 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
400 push @values, $_->{'borrowernumber'};
401 $labels{ $_->{'borrowernumber'} } =
402 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ... $_->{'address'} ";
411 my $flags = $borrower->{'flags'};
412 foreach my $flag ( sort keys %$flags ) {
413 $template->param( flagged=> 1);
414 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
415 if ( $flags->{$flag}->{'noissues'} ) {
417 noissues => ($force_allow_issue) ? 0 : 'true',
418 forceallow => $force_allow_issue,
420 if ( $flag eq 'GNA' ) {
421 $template->param( gna => 'true' );
423 elsif ( $flag eq 'LOST' ) {
424 $template->param( lost => 'true' );
426 elsif ( $flag eq 'DBARRED' ) {
427 $template->param( dbarred => 'true' );
429 elsif ( $flag eq 'CHARGES' ) {
432 chargesmsg => $flags->{'CHARGES'}->{'message'},
433 chargesamount => $flags->{'CHARGES'}->{'amount'},
434 charges_is_blocker => 1
437 elsif ( $flag eq 'CREDITS' ) {
440 creditsmsg => $flags->{'CREDITS'}->{'message'},
441 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
446 if ( $flag eq 'CHARGES' ) {
449 chargesmsg => $flags->{'CHARGES'}->{'message'},
450 chargesamount => $flags->{'CHARGES'}->{'amount'},
453 elsif ( $flag eq 'CREDITS' ) {
456 creditsmsg => $flags->{'CREDITS'}->{'message'},
457 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
460 elsif ( $flag eq 'ODUES' ) {
463 oduesmsg => $flags->{'ODUES'}->{'message'}
466 my $items = $flags->{$flag}->{'itemlist'};
467 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
468 $template->param( nonreturns => 'true' );
471 elsif ( $flag eq 'NOTES' ) {
474 notesmsg => $flags->{'NOTES'}->{'message'}
480 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
481 $amountold =~ s/^.*\$//; # remove upto the $, if any
483 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
485 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
486 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
487 my $cnt = scalar(@$catcodes);
488 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
489 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
492 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
493 if($lib_messages_loop){ $template->param(flagged => 1 ); }
495 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
496 if($bor_messages_loop){ $template->param(flagged => 1 ); }
498 # Computes full borrower address
500 push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
501 push @fulladdress, C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
502 push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
504 my $fast_cataloging = 0;
505 if (defined getframeworkinfo('FA')) {
509 if (C4::Context->preference('ExtendedPatronAttributes')) {
510 my $attributes = GetBorrowerAttributes($borrowernumber);
512 ExtendedPatronAttributes => 1,
513 extendedattributes => $attributes
517 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
518 my $relatives_issues_count =
519 Koha::Database->new()->schema()->resultset('Issue')
520 ->count( { borrowernumber => \@relatives } );
523 lib_messages_loop => $lib_messages_loop,
524 bor_messages_loop => $bor_messages_loop,
525 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
526 findborrower => $findborrower,
527 borrower => $borrower,
528 borrowernumber => $borrowernumber,
530 branchname => GetBranchName($borrower->{'branchcode'}),
532 printername => $printer,
533 firstname => $borrower->{'firstname'},
534 surname => $borrower->{'surname'},
535 showname => $borrower->{'showname'},
536 category_type => $borrower->{'category_type'},
537 was_renewed => $query->param('was_renewed') ? 1 : 0,
538 expiry => format_date($borrower->{'dateexpiry'}),
539 categorycode => $borrower->{'categorycode'},
540 categoryname => $borrower->{description},
541 address => join(' ', @fulladdress),
542 address2 => $borrower->{'address2'},
543 email => $borrower->{'email'},
544 emailpro => $borrower->{'emailpro'},
545 borrowernotes => $borrower->{'borrowernotes'},
546 city => $borrower->{'city'},
547 state => $borrower->{'state'},
548 zipcode => $borrower->{'zipcode'},
549 country => $borrower->{'country'},
550 phone => $borrower->{'phone'},
551 mobile => $borrower->{'mobile'},
552 phonepro => $borrower->{'phonepro'},
553 cardnumber => $borrower->{'cardnumber'},
554 othernames => $borrower->{'othernames'},
555 amountold => $amountold,
557 stickyduedate => $stickyduedate,
558 duedatespec => $duedatespec,
560 selectborrower => $selectborrower,
561 totaldue => sprintf('%.2f', $total),
562 inprocess => $inprocess,
563 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
565 soundon => C4::Context->preference("SoundOn"),
566 fast_cataloging => $fast_cataloging,
567 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
568 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
569 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
570 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
571 RoutingSerials => C4::Context->preference('RoutingSerials'),
572 relatives_issues_count => $relatives_issues_count,
573 relatives_borrowernumbers => \@relatives,
576 # save stickyduedate to session
577 if ($stickyduedate) {
578 $session->param( 'stickyduedate', $duedatespec );
581 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
582 $template->param( picture => 1 ) if $picture;
584 # get authorised values with type of BOR_NOTES
586 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
589 debt_confirmed => $debt_confirmed,
590 SpecifyDueDate => $duedatespec_allow,
591 CircAutocompl => C4::Context->preference("CircAutocompl"),
592 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
593 export_remove_fields => C4::Context->preference("ExportRemoveFields"),
594 export_with_csv_profile => C4::Context->preference("ExportWithCsvProfile"),
595 canned_bor_notes_loop => $canned_notes,
596 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
599 output_html_with_http_headers $query, $cookie, $template->output;