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 ) {
287 $impossible => $$error{$impossible},
293 my $confirm_required = 0;
294 unless($issueconfirmed){
295 # Get the item title for more information
296 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
297 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
299 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
300 foreach my $needsconfirmation ( keys %$question ) {
302 $needsconfirmation => $$question{$needsconfirmation},
303 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
304 NEEDSCONFIRMATION => 1
306 $confirm_required = 1;
309 unless($confirm_required) {
310 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
312 if($globalduedate && ! $stickyduedate && $duedatespec_allow ){
313 $duedatespec = $globalduedate->output();
319 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
320 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
321 $template->param( issuecount => $issue );
324 # reload the borrower info for the sake of reseting the flags.....
325 if ($borrowernumber) {
326 $borrower = GetMemberDetails( $borrowernumber, 0 );
329 ##################################################################################
331 # show all reserves of this borrower, and the position of the reservation ....
332 my $borrowercategory;
334 if ($borrowernumber) {
337 # now we show the status of the borrower's reservations
338 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
340 my @WaitingReserveLoop;
342 foreach my $num_res (@borrowerreserv) {
344 my %getWaitingReserveInfo;
345 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
346 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
347 my ( $transfertwhen, $transfertfrom, $transfertto ) =
348 GetTransfers( $num_res->{'itemnumber'} );
350 $getreserv{waiting} = 0;
351 $getreserv{transfered} = 0;
352 $getreserv{nottransfered} = 0;
354 $getreserv{reservedate} = format_date( $num_res->{'reservedate'} );
355 $getreserv{title} = $getiteminfo->{'title'};
356 $getreserv{itemtype} = $itemtypeinfo->{'description'};
357 $getreserv{author} = $getiteminfo->{'author'};
358 $getreserv{barcodereserv} = $getiteminfo->{'barcode'};
359 $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
360 $getreserv{biblionumber} = $getiteminfo->{'biblionumber'};
361 $getreserv{waitingat} = GetBranchName( $num_res->{'branchcode'} );
362 # check if we have a waiting status for reservations
363 if ( $num_res->{'found'} eq 'W' ) {
364 $getreserv{color} = 'reserved';
365 $getreserv{waiting} = 1;
366 # genarate information displaying only waiting reserves
367 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
368 $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
369 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
370 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
371 $getWaitingReserveInfo{reservedate} = format_date( $num_res->{'reservedate'} );
372 $getWaitingReserveInfo{waitingat} = GetBranchName( $num_res->{'branchcode'} );
373 $getWaitingReserveInfo{waitinghere} = 1 if $num_res->{'branchcode'} eq $branch;
375 # check transfers with the itemnumber foud in th reservation loop
376 if ($transfertwhen) {
377 $getreserv{color} = 'transfered';
378 $getreserv{transfered} = 1;
379 $getreserv{datesent} = format_date($transfertwhen);
380 $getreserv{frombranch} = GetBranchName($transfertfrom);
381 } elsif ($getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'}) {
382 $getreserv{nottransfered} = 1;
383 $getreserv{nottransferedby} = GetBranchName( $getiteminfo->{'holdingbranch'} );
386 # if we don't have a reserv on item, we put the biblio infos and the waiting position
387 if ( $getiteminfo->{'title'} eq '' ) {
388 my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
389 my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} ); # fixme - we should have item-level reserves here ?
390 $getreserv{color} = 'inwait';
391 $getreserv{title} = $getbibinfo->{'title'};
392 $getreserv{nottransfered} = 0;
393 $getreserv{itemtype} = $getbibtype->{'description'};
394 $getreserv{author} = $getbibinfo->{'author'};
395 $getreserv{biblionumber} = $num_res->{'biblionumber'};
397 $getreserv{waitingposition} = $num_res->{'priority'};
398 push( @reservloop, \%getreserv );
400 # if we have a reserve waiting, initiate waitingreserveloop
401 if ($getreserv{waiting} eq 1) {
402 push (@WaitingReserveLoop, \%getWaitingReserveInfo)
407 # return result to the template
409 countreserv => scalar @reservloop,
410 reservloop => \@reservloop ,
411 WaitingReserveLoop => \@WaitingReserveLoop,
413 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
416 # make the issued books table.
417 my $todaysissues = '';
421 ## ADDED BY JF: new itemtype issuingrules counter stuff
422 my $issued_itemtypes_count;
423 my @issued_itemtypes_count_loop;
426 # get each issue of the borrower & separate them in todayissues & previous issues
427 my ($issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
429 # split in 2 arrays for today & previous
430 foreach my $it ( @$issueslist ) {
431 # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
432 $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
434 ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
435 $it->{'itemnumber'}, $borrower->{'borrowernumber'}
437 $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
438 my ($can_renew, $can_renew_error) = CanBookBeRenewed(
439 $borrower->{'borrowernumber'},$it->{'itemnumber'}
441 $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
442 my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
443 $it->{'can_renew'} = $can_renew;
444 $it->{'can_confirm'} = !$can_renew && !$restype;
445 $it->{'renew_error'} = $restype;
447 $it->{'dd'} = format_date($it->{'date_due'});
448 $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
449 ($it->{'author'} eq '') and $it->{'author'} = ' ';
450 $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
451 # ADDED BY JF: NEW ITEMTYPE COUNT DISPLAY
452 $issued_itemtypes_count->{ $it->{'itemtype'} }++;
454 if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
455 push @todaysissues, $it;
457 push @previousissues, $it;
460 if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
461 @todaysissues = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
464 @todaysissues = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
466 if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
467 @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
470 @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
474 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
475 # FIXME: This should utilize all the issuingrules options rather than just the defaults
476 # and it should be moved to a module
477 my $dbh = C4::Context->dbh;
479 # how many of each is allowed?
480 my $issueqty_sth = $dbh->prepare( "
481 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
483 LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
486 $issueqty_sth->execute("*"); # This is a literal asterisk, not a wildcard.
488 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
490 # subtract how many of each this borrower has
491 $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };
493 ( $data->{'maxissueqty'} -
494 $issued_itemtypes_count->{ $data->{'description'} } );
496 # can't have a negative number of remaining
497 if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
498 $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
499 unless ( ( $data->{'maxissueqty'} < 1 )
500 || ( $data->{'itemtype'} eq "*" )
501 || ( $data->{'itemtype'} eq "CIRC" ) )
503 push @issued_itemtypes_count_loop, $data;
511 my $CGIselectborrower;
512 if ($borrowerslist) {
514 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
518 push @values, $_->{'borrowernumber'};
519 $labels{ $_->{'borrowernumber'} } =
520 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ... $_->{'address'} ";
522 $CGIselectborrower = CGI::scrolling_list(
523 -name => 'borrowernumber',
525 -id => 'borrowernumber',
528 -onclick => "window.location = '/cgi-bin/koha/circ/circulation.pl?borrowernumber=' + this.value;",
536 my $flags = $borrower->{'flags'};
537 foreach my $flag ( sort keys %$flags ) {
538 $template->param( flagged=> 1);
539 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
540 if ( $flags->{$flag}->{'noissues'} ) {
545 if ( $flag eq 'GNA' ) {
546 $template->param( gna => 'true' );
548 elsif ( $flag eq 'LOST' ) {
549 $template->param( lost => 'true' );
551 elsif ( $flag eq 'DBARRED' ) {
552 $template->param( dbarred => 'true' );
554 elsif ( $flag eq 'CHARGES' ) {
557 chargesmsg => $flags->{'CHARGES'}->{'message'},
558 chargesamount => $flags->{'CHARGES'}->{'amount'},
559 charges_is_blocker => 1
562 elsif ( $flag eq 'CREDITS' ) {
565 creditsmsg => $flags->{'CREDITS'}->{'message'}
570 if ( $flag eq 'CHARGES' ) {
574 chargesmsg => $flags->{'CHARGES'}->{'message'},
575 chargesamount => $flags->{'CHARGES'}->{'amount'},
578 elsif ( $flag eq 'CREDITS' ) {
581 creditsmsg => $flags->{'CREDITS'}->{'message'}
584 elsif ( $flag eq 'ODUES' ) {
588 oduesmsg => $flags->{'ODUES'}->{'message'}
591 my $items = $flags->{$flag}->{'itemlist'};
595 # foreach my $item (@$items) {
596 # my ($iteminformation) =
597 # getiteminformation( $item->{'itemnumber'}, 0 );
598 # push @itemswaiting, $iteminformation;
601 if ( ! $query->param('module') or $query->param('module') ne 'returns' ) {
602 $template->param( nonreturns => 'true' );
605 elsif ( $flag eq 'NOTES' ) {
609 notesmsg => $flags->{'NOTES'}->{'message'}
615 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
616 $amountold =~ s/^.*\$//; # remove upto the $, if any
618 if ( $borrower->{'category_type'} eq 'C') {
619 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
620 my $cnt = scalar(@$catcodes);
621 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
622 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
625 my $CGIorganisations;
626 my $member_of_institution;
627 if ( C4::Context->preference("memberofinstitution") ) {
628 my $organisations = get_institutions();
631 foreach my $organisation ( keys %$organisations ) {
632 push @orgs, $organisation;
633 $org_labels{$organisation} = $organisations->{$organisation}->{'surname'};
635 $member_of_institution = 1;
636 $CGIorganisations = CGI::popup_menu(
637 -id => 'organisations',
638 -name => 'organisations',
639 -labels => \%org_labels,
645 issued_itemtypes_count_loop => \@issued_itemtypes_count_loop,
646 findborrower => $findborrower,
647 borrower => $borrower,
648 borrowernumber => $borrowernumber,
650 branchname => GetBranchName($borrower->{'branchcode'}),
652 printername => $printer,
653 firstname => $borrower->{'firstname'},
654 surname => $borrower->{'surname'},
655 dateexpiry => format_date($newexpiry),
656 expiry => format_date($borrower->{'dateexpiry'}),
657 categorycode => $borrower->{'categorycode'},
658 categoryname => $borrower->{description},
659 address => $borrower->{'address'},
660 address2 => $borrower->{'address2'},
661 email => $borrower->{'email'},
662 emailpro => $borrower->{'emailpro'},
663 borrowernotes => $borrower->{'borrowernotes'},
664 city => $borrower->{'city'},
665 zipcode => $borrower->{'zipcode'},
666 phone => $borrower->{'phone'} || $borrower->{'mobile'},
667 cardnumber => $borrower->{'cardnumber'},
668 amountold => $amountold,
670 stickyduedate => $stickyduedate,
671 duedatespec => $duedatespec,
673 CGIselectborrower => $CGIselectborrower,
674 todayissues => \@todaysissues,
675 previssues => \@previousissues,
676 inprocess => $inprocess,
677 memberofinstution => $member_of_institution,
678 CGIorganisations => $CGIorganisations,
679 is_child => ($borrower->{'category_type'} eq 'C'),
683 # save stickyduedate to session
684 if ($stickyduedate) {
685 $session->param( 'stickyduedate', $duedatespec );
688 #if ($branchcookie) {
689 #$cookie=[$cookie, $branchcookie, $printercookie];
692 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
693 $template->param( picture => 1 ) if $picture;
697 debt_confirmed => $debt_confirmed,
698 SpecifyDueDate => $duedatespec_allow,
699 CircAutocompl => C4::Context->preference("CircAutocompl"),
700 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
701 dateformat => C4::Context->preference("dateformat"),
702 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
704 output_html_with_http_headers $query, $cookie, $template->output;