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 # new op dev the branch and the printer are now defined by the userenv
53 # but first we have to check if someone has tried to change them
55 my $branch = $query->param('branch');
57 # update our session so the userenv is updated
58 my $sessionID = $query->cookie("CGISESSID") ;
59 my $session = get_session($sessionID);
60 $session->param('branch',$branch);
61 my $branchname = GetBranchName($branch);
62 $session->param('branchname',$branchname);
65 my $printer = $query->param('printer');
67 # update our session so the userenv is updated
68 my $sessionID = $query->cookie("CGISESSID") ;
69 my $session = get_session($sessionID);
70 $session->param('branchprinter',$printer);
73 if (!C4::Context->userenv && !$branch){
74 my $sessionID = $query->cookie("CGISESSID") ;
75 my $session = get_session($sessionID);
76 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
77 # no branch set we can't issue
78 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
83 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
85 template_name => 'circ/circulation.tmpl',
89 flagsrequired => { circulate => 1 },
93 my $branches = GetBranches();
94 my $printers = GetPrinters();
96 my @failedrenews = $query->param('failedrenew');
98 for (@failedrenews) { $renew_failed[$_] = 1; }
100 my $findborrower = $query->param('findborrower');
101 $findborrower =~ s|,| |g;
102 #$findborrower =~ s|'| |g;
103 my $borrowernumber = $query->param('borrowernumber');
105 $branch = C4::Context->userenv->{'branch'};
106 $printer = C4::Context->userenv->{'branchprinter'};
109 # If Autolocated is not activated, we show the Circulation Parameters to chage settings of librarian
110 if (C4::Context->preference("AutoLocation") ne 1) { # FIXME: string comparison to number
111 $template->param(ManualLocation => 1);
114 my $barcode = $query->param('barcode') || '';
116 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
117 my $stickyduedate = $query->param('stickyduedate');
118 my $duedatespec = $query->param('duedatespec');
119 my $issueconfirmed = $query->param('issueconfirmed');
120 my $cancelreserve = $query->param('cancelreserve');
121 my $organisation = $query->param('organisations');
122 my $print = $query->param('print');
123 my $newexpiry = $query->param('dateexpiry');
124 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
129 # if ($query->param('setcookies')) {
130 # $branchcookie = $query->cookie(-name=>'branch', -value=>"$branch", -expires=>'+1y');
131 # $printercookie = $query->cookie(-name=>'printer', -value=>"$printer", -expires=>'+1y');
135 my ($datedue,$invalidduedate);
137 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
138 my $tempdate = C4::Dates->new($duedatespec);
139 if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
140 # i.e., it has to be later than today/now
141 $datedue = $tempdate;
144 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
148 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
152 my $todaysdate = C4::Dates->new->output('iso');
154 # check and see if we should print
155 if ( $barcode eq '' && $print eq 'maybe' ) {
159 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
161 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
164 borrowernumber => $borrowernumber
168 if ( $print eq 'yes' && $borrowernumber ne '' ) {
169 printslip( $borrowernumber );
170 $query->param( 'borrowernumber', '' );
171 $borrowernumber = '';
175 # STEP 2 : FIND BORROWER
176 # if there is a list of find borrowers....
181 my ( $count, $borrowers ) =
182 SearchMember($findborrower, 'cardnumber', 'web' );
183 my @borrowers = @$borrowers;
185 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
187 if (C4::Context->preference("AddPatronLists")=~/code/){
188 my $categories=GetBorrowercategoryList;
189 $categories->[0]->{'first'}=1;
190 $template->param(categories=>$categories);
192 if ( $#borrowers == -1 ) {
193 $query->param( 'findborrower', '' );
194 $message = "'$findborrower'";
196 elsif ( $#borrowers == 0 ) {
197 $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
198 $query->param( 'barcode', '' );
199 $borrowernumber = $borrowers[0]->{'borrowernumber'};
202 $borrowerslist = \@borrowers;
206 # get the borrower information.....
209 if ($borrowernumber) {
210 $borrower = GetMemberDetails( $borrowernumber, 0 );
211 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
213 # Warningdate is the date that the warning starts appearing
214 my ( $today_year, $today_month, $today_day ) = Today();
215 my ( $warning_year, $warning_month, $warning_day ) = split /-/,
216 $borrower->{'dateexpiry'};
217 my ( $enrol_year, $enrol_month, $enrol_day ) = split /-/,
218 $borrower->{'dateenrolled'};
219 # Renew day is calculated by adding the enrolment period to today
220 my ( $renew_year, $renew_month, $renew_day ) =
221 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
222 0 , $borrower->{'enrolmentperiod'}) if ($enrol_year*$enrol_month*$enrol_day>0);
223 # if the expiry date is before today ie they have expired
224 if ( $warning_year*$warning_month*$warning_day==0
225 || Date_to_Days( $today_year, $today_month, $today_day )
226 > Date_to_Days( $warning_year, $warning_month, $warning_day ) )
228 #borrowercard expired, no issues
232 expired => format_date($borrower->{dateexpiry}),
233 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
236 # check for NotifyBorrowerDeparture
237 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
238 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
239 Date_to_Days( $today_year, $today_month, $today_day ) )
241 # borrower card soon to expire warn librarian
242 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
244 if ( C4::Context->preference('ReturnBeforeExpiry')){
245 $template->param("returnbeforeexpiry" => 1);
250 issuecount => $issue,
260 # always check for blockers on issuing
261 my ( $error, $question ) =
262 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
263 my $noerror = $invalidduedate ? 0 : 1;
265 delete $question->{'DEBT'} if ($debt_confirmed);
266 foreach my $impossible ( keys %$error ) {
267 if ($impossible eq "NOT_FOR_LOAN_CAN_FORCE"){
268 $$question{$impossible}=$$error{$impossible},
271 $impossible => $$error{$impossible},
278 if ($issueconfirmed && $noerror) {
279 # we have no blockers for issuing and any issues needing confirmation have been resolved
280 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
283 elsif ($issueconfirmed){ # FIXME: Do something? Or is this to *intentionally* do nothing?
284 if (C4::Context->preference("AllowNotForLoanOverride")){
285 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
286 $template->param(IMPOSSIBLE => 0);
292 # Get the item title for more information
293 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
295 # only pass needsconfirmation to template if issuing is possible
296 foreach my $needsconfirmation ( keys %$question ) {
298 $needsconfirmation => $$question{$needsconfirmation},
299 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
300 NEEDSCONFIRMATION => 1
304 # Because of the weird conditional structure (empty elsif block),
305 # if we reached here, $issueconfirmed must be false.
306 # Also, since we moved inside the if ($noerror) conditional,
307 # this old chunky conditional can be simplified:
308 # if ( $noerror && ( $noquestion || $issueconfirmed ) ) {
310 AddIssue( $borrower, $barcode, $datedue );
315 itemhomebranch => $getmessageiteminfo->{'homebranch'} ,
316 duedatespec => $duedatespec,
320 # FIXME If the issue is confirmed, we launch another time borrdata2, now display the issue count after issue
321 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
323 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 if($num_res->{'branchcode'} eq $branch){ $getWaitingReserveInfo{waitinghere} = 1; }
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);
386 if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
387 and not $transfertwhen )
389 $getreserv{nottransfered} = 1;
390 $getreserv{nottransferedby} =
391 GetBranchName( $getiteminfo->{'holdingbranch'} );
394 # if we don't have a reserv on item, we put the biblio infos and the waiting position
395 if ( $getiteminfo->{'title'} eq '' ) {
396 my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
397 my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} ); # fixme - we should have item-level reserves here ?
398 $getreserv{color} = 'inwait';
399 $getreserv{title} = $getbibinfo->{'title'};
400 $getreserv{nottransfered} = 0;
401 $getreserv{itemtype} = $getbibtype->{'description'};
402 $getreserv{author} = $getbibinfo->{'author'};
403 $getreserv{biblionumber} = $num_res->{'biblionumber'};
405 $getreserv{waitingposition} = $num_res->{'priority'};
406 push( @reservloop, \%getreserv );
408 # if we have a reserve waiting, initiate waitingreserveloop
409 if ($getreserv{waiting} eq 1) {
410 push (@WaitingReserveLoop, \%getWaitingReserveInfo)
415 # return result to the template
417 countreserv => scalar @reservloop,
418 reservloop => \@reservloop ,
419 WaitingReserveLoop => \@WaitingReserveLoop,
421 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
424 # make the issued books table.
425 my $todaysissues = '';
430 ## ADDED BY JF: new itemtype issuingrules counter stuff
431 my $issued_itemtypes_loop;
432 my $issued_itemtypes_count;
433 my $issued_itemtypes_allowed_count; # hashref with total allowed by itemtype
434 my $issued_itemtypes_remaining; # hashref with remaining
435 my $issued_itemtypes_flags; #hashref that stores flags
436 my @issued_itemtypes_count_loop;
439 # get each issue of the borrower & separate them in todayissues & previous issues
440 my ($issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
442 # split in 2 arrays for today & previous
443 foreach my $it ( @$issueslist ) {
444 # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
445 $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
447 ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
448 $it->{'itemnumber'}, $borrower->{'borrowernumber'}
450 $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
451 my ($can_renew, $can_renew_error) = CanBookBeRenewed(
452 $borrower->{'borrowernumber'},$it->{'itemnumber'}
454 $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
455 my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
456 $it->{'can_renew'} = $can_renew;
457 $it->{'can_confirm'} = !$can_renew && !$restype;
458 $it->{'renew_error'} = $restype;
460 $it->{'dd'} = format_date($it->{'date_due'});
461 $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
462 ($it->{'author'} eq '') and $it->{'author'} = ' ';
463 $it->{'renew_failed'} = $renew_failed[$it->{'itemnumber'}];
464 # ADDED BY JF: NEW ITEMTYPE COUNT DISPLAY
465 $issued_itemtypes_count->{ $it->{'itemtype'} }++;
467 if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
468 push @todaysissues, $it;
470 push @previousissues, $it;
473 if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
474 @todaysissues = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
477 @todaysissues = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
479 if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
480 @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
483 @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
487 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
488 # FIXME: This should utilize all the issuingrules options rather than just the defaults
489 # and it should be moved to a module
490 my $dbh = C4::Context->dbh;
492 # how many of each is allowed?
493 my $issueqty_sth = $dbh->prepare( "
494 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
496 LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
499 #my @issued_itemtypes_count; # huh?
500 $issueqty_sth->execute("*"); # This is a literal asterisk, not a wildcard.
502 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
504 # subtract how many of each this borrower has
505 $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };
507 ( $data->{'maxissueqty'} -
508 $issued_itemtypes_count->{ $data->{'description'} } );
510 # can't have a negative number of remaining
511 if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
512 $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
513 unless ( ( $data->{'maxissueqty'} < 1 )
514 || ( $data->{'itemtype'} eq "*" )
515 || ( $data->{'itemtype'} eq "CIRC" ) )
517 push @issued_itemtypes_count_loop, $data;
520 $issued_itemtypes_loop = \@issued_itemtypes_count_loop;
526 my $CGIselectborrower;
527 if ($borrowerslist) {
529 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
533 push @values, $_->{'borrowernumber'};
534 $labels{ $_->{'borrowernumber'} } =
535 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ... $_->{'address'} ";
537 $CGIselectborrower = CGI::scrolling_list(
538 -name => 'borrowernumber',
540 -id => 'borrowernumber',
543 -onclick => "window.location = '/cgi-bin/koha/circ/circulation.pl?borrowernumber=' + this.value;",
551 my $flags = $borrower->{'flags'};
554 foreach $flag ( sort keys %$flags ) {
555 $template->param( flagged=> 1);
556 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
557 if ( $flags->{$flag}->{'noissues'} ) {
562 if ( $flag eq 'GNA' ) {
563 $template->param( gna => 'true' );
565 if ( $flag eq 'LOST' ) {
566 $template->param( lost => 'true' );
568 if ( $flag eq 'DBARRED' ) {
569 $template->param( dbarred => 'true' );
571 if ( $flag eq 'CHARGES' ) {
574 chargesmsg => $flags->{'CHARGES'}->{'message'},
575 chargesamount => $flags->{'CHARGES'}->{'amount'},
576 charges_is_blocker => 1
579 if ( $flag eq 'CREDITS' ) {
582 creditsmsg => $flags->{'CREDITS'}->{'message'}
587 if ( $flag eq 'CHARGES' ) {
591 chargesmsg => $flags->{'CHARGES'}->{'message'},
592 chargesamount => $flags->{'CHARGES'}->{'amount'},
595 if ( $flag eq 'CREDITS' ) {
598 creditsmsg => $flags->{'CREDITS'}->{'message'}
601 if ( $flag eq 'ODUES' ) {
605 oduesmsg => $flags->{'ODUES'}->{'message'}
608 my $items = $flags->{$flag}->{'itemlist'};
612 # foreach my $item (@$items) {
613 # my ($iteminformation) =
614 # getiteminformation( $item->{'itemnumber'}, 0 );
615 # push @itemswaiting, $iteminformation;
618 if ( $query->param('module') ne 'returns' ) {
619 $template->param( nonreturns => 'true' );
622 if ( $flag eq 'NOTES' ) {
626 notesmsg => $flags->{'NOTES'}->{'message'}
632 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
633 my @temp = split( /\$/, $amountold );
635 if ( $borrower->{'category_type'} eq 'C') {
636 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
637 my $cnt = scalar(@$catcodes);
638 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
639 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
642 my $CGIorganisations;
643 my $member_of_institution;
644 if ( C4::Context->preference("memberofinstitution") ) {
645 my $organisations = get_institutions();
648 foreach my $organisation ( keys %$organisations ) {
649 push @orgs, $organisation;
650 $org_labels{$organisation} =
651 $organisations->{$organisation}->{'surname'};
653 $member_of_institution = 1;
654 $CGIorganisations = CGI::popup_menu(
655 -id => 'organisations',
656 -name => 'organisations',
657 -labels => \%org_labels,
662 $amountold = $temp[1];
665 issued_itemtypes_count_loop => $issued_itemtypes_loop,
666 findborrower => $findborrower,
667 borrower => $borrower,
668 borrowernumber => $borrowernumber,
670 branchname => GetBranchName($borrower->{'branchcode'}),
672 printername => $printer,
673 firstname => $borrower->{'firstname'},
674 surname => $borrower->{'surname'},
675 dateexpiry => format_date($newexpiry),
676 expiry => format_date($borrower->{'dateexpiry'}),
677 categorycode => $borrower->{'categorycode'},
678 categoryname => $borrower->{description},
679 address => $borrower->{'address'},
680 address2 => $borrower->{'address2'},
681 email => $borrower->{'email'},
682 emailpro => $borrower->{'emailpro'},
683 borrowernotes => $borrower->{'borrowernotes'},
684 city => $borrower->{'city'},
685 zipcode => $borrower->{'zipcode'},
686 phone => $borrower->{'phone'} || $borrower->{'mobile'},
687 cardnumber => $borrower->{'cardnumber'},
688 amountold => $amountold,
690 stickyduedate => $stickyduedate,
692 CGIselectborrower => $CGIselectborrower,
693 todayissues => \@todaysissues,
694 previssues => \@previousissues,
695 inprocess => $inprocess,
696 memberofinstution => $member_of_institution,
697 CGIorganisations => $CGIorganisations,
698 is_child => ($borrower->{'category_type'} eq 'C'),
702 # set return date if stickyduedate
703 if ($stickyduedate) {
705 duedatespec => $duedatespec,
709 #if ($branchcookie) {
710 #$cookie=[$cookie, $branchcookie, $printercookie];
713 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
714 $template->param( picture => 1 ) if $picture;
718 debt_confirmed => $debt_confirmed,
719 SpecifyDueDate => C4::Context->preference("SpecifyDueDate"),
720 CircAutocompl => C4::Context->preference("CircAutocompl"),
721 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
722 dateformat => C4::Context->preference("dateformat"),
723 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
725 output_html_with_http_headers $query, $cookie, $template->output;