3 # written 8/5/2002 by Finlay
4 # script to execute issuing of books
6 # Copyright 2000-2002 Katipo Communications
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it under the
11 # terms of the GNU General Public License as published by the Free Software
12 # Foundation; either version 2 of the License, or (at your option) any later
15 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
16 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License along with
20 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
21 # Suite 330, Boston, MA 02111-1307 USA
24 # use warnings; # FIXME
28 use C4::Auth qw/:DEFAULT get_session/;
29 use C4::Dates qw/format_date/;
30 use C4::Branch; # GetBranches
31 use C4::Koha; # GetPrinter
52 my $sessionID = $query->cookie("CGISESSID") ;
53 my $session = get_session($sessionID);
55 # branch and printer are now defined by the userenv
56 # but first we have to check if someone has tried to change them
58 my $branch = $query->param('branch');
60 # update our session so the userenv is updated
61 $session->param('branch', $branch);
62 $session->param('branchname', GetBranchName($branch));
65 my $printer = $query->param('printer');
67 # update our session so the userenv is updated
68 $session->param('branchprinter', $printer);
71 if (!C4::Context->userenv && !$branch){
72 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
73 # no branch set we can't issue
74 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
79 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
81 template_name => 'circ/circulation.tmpl',
85 flagsrequired => { circulate => 'circulate_remaining_permissions' },
89 my $branches = GetBranches();
91 my @failedrenews = $query->param('failedrenew'); # expected to be itemnumbers
93 for (@failedrenews) { $renew_failed{$_} = 1; }
95 my $findborrower = $query->param('findborrower');
96 $findborrower =~ s|,| |g;
97 #$findborrower =~ s|'| |g;
98 my $borrowernumber = $query->param('borrowernumber');
100 $branch = C4::Context->userenv->{'branch'};
101 $printer = C4::Context->userenv->{'branchprinter'};
104 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
105 if (C4::Context->preference("AutoLocation") ne 1) { # FIXME: string comparison to number
106 $template->param(ManualLocation => 1);
109 my $barcode = $query->param('barcode') || '';
110 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
112 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
113 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
114 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
115 my $issueconfirmed = $query->param('issueconfirmed');
116 my $cancelreserve = $query->param('cancelreserve');
117 my $organisation = $query->param('organisations');
118 my $print = $query->param('print');
119 my $newexpiry = $query->param('dateexpiry');
120 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
122 # Check if stickyduedate is turned off
124 # was stickyduedate loaded from session?
125 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
126 $session->clear( 'stickyduedate' );
127 $stickyduedate = $query->param('stickyduedate');
128 $duedatespec = $query->param('duedatespec');
135 # if ($query->param('setcookies')) {
136 # $branchcookie = $query->cookie(-name=>'branch', -value=>"$branch", -expires=>'+1y');
137 # $printercookie = $query->cookie(-name=>'printer', -value=>"$printer", -expires=>'+1y');
141 my ($datedue,$invalidduedate,$globalduedate);
143 if(C4::Context->preference('globalDueDate') && (C4::Context->preference('globalDueDate') =~ C4::Dates->regexp('syspref'))){
144 $globalduedate = C4::Dates->new(C4::Context->preference('globalDueDate'));
146 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
147 if($duedatespec_allow){
149 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
150 my $tempdate = C4::Dates->new($duedatespec);
151 if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
152 # i.e., it has to be later than today/now
153 $datedue = $tempdate;
156 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
160 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
163 # pass global due date to tmpl if specifyduedate is true
164 # and we have no barcode (loading circ page but not checking out)
165 if($globalduedate && ! $barcode ){
166 $duedatespec = $globalduedate->output();
171 $datedue = $globalduedate if ($globalduedate);
174 my $todaysdate = C4::Dates->new->output('iso');
176 # check and see if we should print
177 if ( $barcode eq '' && $print eq 'maybe' ) {
181 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
182 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
185 borrowernumber => $borrowernumber
189 if ( $print eq 'yes' && $borrowernumber ne '' ) {
190 printslip( $borrowernumber );
191 $query->param( 'borrowernumber', '' );
192 $borrowernumber = '';
196 # STEP 2 : FIND BORROWER
197 # if there is a list of find borrowers....
202 my ($count, $borrowers) = SearchMember($findborrower, 'cardnumber', 'web');
203 my @borrowers = @$borrowers;
204 if (C4::Context->preference("AddPatronLists")) {
206 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
208 if (C4::Context->preference("AddPatronLists")=~/code/){
209 my $categories = GetBorrowercategoryList;
210 $categories->[0]->{'first'} = 1;
211 $template->param(categories=>$categories);
214 if ( $#borrowers == -1 ) {
215 $query->param( 'findborrower', '' );
216 $message = "'$findborrower'";
218 elsif ( $#borrowers == 0 ) {
219 $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
220 $query->param( 'barcode', '' );
221 $borrowernumber = $borrowers[0]->{'borrowernumber'};
224 $borrowerslist = \@borrowers;
228 # get the borrower information.....
230 if ($borrowernumber) {
231 $borrower = GetMemberDetails( $borrowernumber, 0 );
232 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
234 # Warningdate is the date that the warning starts appearing
235 my ( $today_year, $today_month, $today_day) = Today();
236 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
237 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
238 # Renew day is calculated by adding the enrolment period to today
239 my ( $renew_year, $renew_month, $renew_day) =
240 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
241 0 , $borrower->{'enrolmentperiod'}) if ($enrol_year*$enrol_month*$enrol_day>0);
242 # if the expiry date is before today ie they have expired
243 if ( $warning_year*$warning_month*$warning_day==0
244 || Date_to_Days($today_year, $today_month, $today_day )
245 > Date_to_Days($warning_year, $warning_month, $warning_day) )
247 #borrowercard expired, no issues
251 expired => format_date($borrower->{dateexpiry}),
252 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
255 # check for NotifyBorrowerDeparture
256 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
257 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
258 Date_to_Days( $today_year, $today_month, $today_day ) )
260 # borrower card soon to expire warn librarian
261 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
263 if (C4::Context->preference('ReturnBeforeExpiry')){
264 $template->param("returnbeforeexpiry" => 1);
269 issuecount => $issue,
279 # always check for blockers on issuing
280 my ( $error, $question ) =
281 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
282 my $blocker = $invalidduedate ? 1 : 0;
284 delete $question->{'DEBT'} if ($debt_confirmed);
285 foreach my $impossible ( keys %$error ) {
286 if ($impossible eq "NOT_FOR_LOAN_CAN_FORCE"){
287 $$question{$impossible}=$$error{$impossible},
290 $impossible => $$error{$impossible},
296 my $confirm_required = 0;
297 unless($issueconfirmed){
298 # Get the item title for more information
299 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
300 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
302 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
303 foreach my $needsconfirmation ( keys %$question ) {
305 $needsconfirmation => $$question{$needsconfirmation},
306 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
307 NEEDSCONFIRMATION => 1
309 $confirm_required = 1;
312 unless($confirm_required) {
313 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
315 if($globalduedate && ! $stickyduedate && $duedatespec_allow ){
316 $duedatespec = $globalduedate->output();
322 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
323 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
324 $template->param( issuecount => $issue );
327 # reload the borrower info for the sake of reseting the flags.....
328 if ($borrowernumber) {
329 $borrower = GetMemberDetails( $borrowernumber, 0 );
332 ##################################################################################
334 # show all reserves of this borrower, and the position of the reservation ....
335 my $borrowercategory;
337 if ($borrowernumber) {
340 # now we show the status of the borrower's reservations
341 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
343 my @WaitingReserveLoop;
345 foreach my $num_res (@borrowerreserv) {
347 my %getWaitingReserveInfo;
348 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
349 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
350 my ( $transfertwhen, $transfertfrom, $transfertto ) =
351 GetTransfers( $num_res->{'itemnumber'} );
353 $getreserv{waiting} = 0;
354 $getreserv{transfered} = 0;
355 $getreserv{nottransfered} = 0;
357 $getreserv{reservedate} = format_date( $num_res->{'reservedate'} );
358 $getreserv{title} = $getiteminfo->{'title'};
359 $getreserv{itemtype} = $itemtypeinfo->{'description'};
360 $getreserv{author} = $getiteminfo->{'author'};
361 $getreserv{barcodereserv} = $getiteminfo->{'barcode'};
362 $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
363 $getreserv{biblionumber} = $getiteminfo->{'biblionumber'};
364 $getreserv{waitingat} = GetBranchName( $num_res->{'branchcode'} );
365 # check if we have a waiting status for reservations
366 if ( $num_res->{'found'} eq 'W' ) {
367 $getreserv{color} = 'reserved';
368 $getreserv{waiting} = 1;
369 # genarate information displaying only waiting reserves
370 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
371 $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
372 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
373 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
374 $getWaitingReserveInfo{reservedate} = format_date( $num_res->{'reservedate'} );
375 $getWaitingReserveInfo{waitingat} = GetBranchName( $num_res->{'branchcode'} );
376 $getWaitingReserveInfo{waitinghere} = 1 if $num_res->{'branchcode'} eq $branch;
378 # check transfers with the itemnumber foud in th reservation loop
379 if ($transfertwhen) {
380 $getreserv{color} = 'transfered';
381 $getreserv{transfered} = 1;
382 $getreserv{datesent} = format_date($transfertwhen);
383 $getreserv{frombranch} = GetBranchName($transfertfrom);
384 } elsif ($getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'}) {
385 $getreserv{nottransfered} = 1;
386 $getreserv{nottransferedby} = GetBranchName( $getiteminfo->{'holdingbranch'} );
389 # if we don't have a reserv on item, we put the biblio infos and the waiting position
390 if ( $getiteminfo->{'title'} eq '' ) {
391 my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
392 my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} ); # fixme - we should have item-level reserves here ?
393 $getreserv{color} = 'inwait';
394 $getreserv{title} = $getbibinfo->{'title'};
395 $getreserv{nottransfered} = 0;
396 $getreserv{itemtype} = $getbibtype->{'description'};
397 $getreserv{author} = $getbibinfo->{'author'};
398 $getreserv{biblionumber} = $num_res->{'biblionumber'};
400 $getreserv{waitingposition} = $num_res->{'priority'};
401 push( @reservloop, \%getreserv );
403 # if we have a reserve waiting, initiate waitingreserveloop
404 if ($getreserv{waiting} eq 1) {
405 push (@WaitingReserveLoop, \%getWaitingReserveInfo)
410 # return result to the template
412 countreserv => scalar @reservloop,
413 reservloop => \@reservloop ,
414 WaitingReserveLoop => \@WaitingReserveLoop,
416 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
419 # make the issued books table.
420 my $todaysissues = '';
424 ## ADDED BY JF: new itemtype issuingrules counter stuff
425 my $issued_itemtypes_count;
426 my @issued_itemtypes_count_loop;
429 # get each issue of the borrower & separate them in todayissues & previous issues
430 my ($issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
432 # split in 2 arrays for today & previous
433 foreach my $it ( @$issueslist ) {
434 # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
435 $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
437 ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
438 $it->{'itemnumber'}, $borrower->{'borrowernumber'}
440 $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
441 my ($can_renew, $can_renew_error) = CanBookBeRenewed(
442 $borrower->{'borrowernumber'},$it->{'itemnumber'}
444 $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
445 my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
446 $it->{'can_renew'} = $can_renew;
447 $it->{'can_confirm'} = !$can_renew && !$restype;
448 $it->{'renew_error'} = $restype;
450 $it->{'dd'} = format_date($it->{'date_due'});
451 $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
452 ($it->{'author'} eq '') and $it->{'author'} = ' ';
453 $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
454 # ADDED BY JF: NEW ITEMTYPE COUNT DISPLAY
455 $issued_itemtypes_count->{ $it->{'itemtype'} }++;
457 if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
458 push @todaysissues, $it;
460 push @previousissues, $it;
463 if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
464 @todaysissues = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
467 @todaysissues = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
469 if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
470 @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
473 @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
477 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
478 # FIXME: This should utilize all the issuingrules options rather than just the defaults
479 # and it should be moved to a module
480 my $dbh = C4::Context->dbh;
482 # how many of each is allowed?
483 my $issueqty_sth = $dbh->prepare( "
484 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
486 LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
489 $issueqty_sth->execute("*"); # This is a literal asterisk, not a wildcard.
491 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
493 # subtract how many of each this borrower has
494 $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };
496 ( $data->{'maxissueqty'} -
497 $issued_itemtypes_count->{ $data->{'description'} } );
499 # can't have a negative number of remaining
500 if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
501 $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
502 unless ( ( $data->{'maxissueqty'} < 1 )
503 || ( $data->{'itemtype'} eq "*" )
504 || ( $data->{'itemtype'} eq "CIRC" ) )
506 push @issued_itemtypes_count_loop, $data;
514 my $CGIselectborrower;
515 if ($borrowerslist) {
517 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
521 push @values, $_->{'borrowernumber'};
522 $labels{ $_->{'borrowernumber'} } =
523 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ... $_->{'address'} ";
525 $CGIselectborrower = CGI::scrolling_list(
526 -name => 'borrowernumber',
528 -id => 'borrowernumber',
531 -onclick => "window.location = '/cgi-bin/koha/circ/circulation.pl?borrowernumber=' + this.value;",
539 my $flags = $borrower->{'flags'};
540 foreach my $flag ( sort keys %$flags ) {
541 $template->param( flagged=> 1);
542 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
543 if ( $flags->{$flag}->{'noissues'} ) {
548 if ( $flag eq 'GNA' ) {
549 $template->param( gna => 'true' );
551 elsif ( $flag eq 'LOST' ) {
552 $template->param( lost => 'true' );
554 elsif ( $flag eq 'DBARRED' ) {
555 $template->param( dbarred => 'true' );
557 elsif ( $flag eq 'CHARGES' ) {
560 chargesmsg => $flags->{'CHARGES'}->{'message'},
561 chargesamount => $flags->{'CHARGES'}->{'amount'},
562 charges_is_blocker => 1
565 elsif ( $flag eq 'CREDITS' ) {
568 creditsmsg => $flags->{'CREDITS'}->{'message'}
573 if ( $flag eq 'CHARGES' ) {
577 chargesmsg => $flags->{'CHARGES'}->{'message'},
578 chargesamount => $flags->{'CHARGES'}->{'amount'},
581 elsif ( $flag eq 'CREDITS' ) {
584 creditsmsg => $flags->{'CREDITS'}->{'message'}
587 elsif ( $flag eq 'ODUES' ) {
591 oduesmsg => $flags->{'ODUES'}->{'message'}
594 my $items = $flags->{$flag}->{'itemlist'};
598 # foreach my $item (@$items) {
599 # my ($iteminformation) =
600 # getiteminformation( $item->{'itemnumber'}, 0 );
601 # push @itemswaiting, $iteminformation;
604 if ( ! $query->param('module') or $query->param('module') ne 'returns' ) {
605 $template->param( nonreturns => 'true' );
608 elsif ( $flag eq 'NOTES' ) {
612 notesmsg => $flags->{'NOTES'}->{'message'}
618 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
619 $amountold =~ s/^.*\$//; # remove upto the $, if any
621 if ( $borrower->{'category_type'} eq 'C') {
622 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
623 my $cnt = scalar(@$catcodes);
624 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
625 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
628 my $CGIorganisations;
629 my $member_of_institution;
630 if ( C4::Context->preference("memberofinstitution") ) {
631 my $organisations = get_institutions();
634 foreach my $organisation ( keys %$organisations ) {
635 push @orgs, $organisation;
636 $org_labels{$organisation} = $organisations->{$organisation}->{'surname'};
638 $member_of_institution = 1;
639 $CGIorganisations = CGI::popup_menu(
640 -id => 'organisations',
641 -name => 'organisations',
642 -labels => \%org_labels,
647 # Computes full borrower address
648 my (undef, $roadttype_hashref) = &GetRoadTypes();
649 my $address = $borrower->{'streetnumber'}.' '.$roadttype_hashref->{$borrower->{'streettype'}}.' '.$borrower->{'address'};
652 issued_itemtypes_count_loop => \@issued_itemtypes_count_loop,
653 findborrower => $findborrower,
654 borrower => $borrower,
655 borrowernumber => $borrowernumber,
657 branchname => GetBranchName($borrower->{'branchcode'}),
659 printername => $printer,
660 firstname => $borrower->{'firstname'},
661 surname => $borrower->{'surname'},
662 dateexpiry => format_date($newexpiry),
663 expiry => format_date($borrower->{'dateexpiry'}),
664 categorycode => $borrower->{'categorycode'},
665 categoryname => $borrower->{description},
667 address2 => $borrower->{'address2'},
668 email => $borrower->{'email'},
669 emailpro => $borrower->{'emailpro'},
670 borrowernotes => $borrower->{'borrowernotes'},
671 city => $borrower->{'city'},
672 zipcode => $borrower->{'zipcode'},
673 phone => $borrower->{'phone'} || $borrower->{'mobile'},
674 cardnumber => $borrower->{'cardnumber'},
675 amountold => $amountold,
677 stickyduedate => $stickyduedate,
678 duedatespec => $duedatespec,
680 CGIselectborrower => $CGIselectborrower,
681 todayissues => \@todaysissues,
682 previssues => \@previousissues,
683 inprocess => $inprocess,
684 memberofinstution => $member_of_institution,
685 CGIorganisations => $CGIorganisations,
686 is_child => ($borrower->{'category_type'} eq 'C'),
690 # save stickyduedate to session
691 if ($stickyduedate) {
692 $session->param( 'stickyduedate', $duedatespec );
695 #if ($branchcookie) {
696 #$cookie=[$cookie, $branchcookie, $printercookie];
699 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
700 $template->param( picture => 1 ) if $picture;
704 debt_confirmed => $debt_confirmed,
705 SpecifyDueDate => $duedatespec_allow,
707 output_html_with_http_headers $query, $cookie, $template->output;