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 => 'circulate_remaining_permissions' },
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,$globalduedate);
137 if(C4::Context->preference('globalDueDate') && (C4::Context->preference('globalDueDate') =~ C4::Dates->regexp('syspref'))){
138 $globalduedate = C4::Dates->new(C4::Context->preference('globalDueDate'));
140 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
141 if($duedatespec_allow){
143 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
144 my $tempdate = C4::Dates->new($duedatespec);
145 if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
146 # i.e., it has to be later than today/now
147 $datedue = $tempdate;
150 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
154 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
157 # pass global due date to tmpl if specifyduedate is true
158 # and we have no barcode (loading circ page but not checking out)
159 if($globalduedate && ! $barcode ){
160 $duedatespec = $globalduedate->output();
165 $datedue = $globalduedate if($globalduedate);
168 my $todaysdate = C4::Dates->new->output('iso');
170 # check and see if we should print
171 if ( $barcode eq '' && $print eq 'maybe' ) {
175 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
176 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
179 borrowernumber => $borrowernumber
183 if ( $print eq 'yes' && $borrowernumber ne '' ) {
184 printslip( $borrowernumber );
185 $query->param( 'borrowernumber', '' );
186 $borrowernumber = '';
190 # STEP 2 : FIND BORROWER
191 # if there is a list of find borrowers....
196 my ( $count, $borrowers ) =
197 SearchMember($findborrower, 'cardnumber', 'web' );
198 my @borrowers = @$borrowers;
200 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
202 if (C4::Context->preference("AddPatronLists")=~/code/){
203 my $categories=GetBorrowercategoryList;
204 $categories->[0]->{'first'}=1;
205 $template->param(categories=>$categories);
207 if ( $#borrowers == -1 ) {
208 $query->param( 'findborrower', '' );
209 $message = "'$findborrower'";
211 elsif ( $#borrowers == 0 ) {
212 $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
213 $query->param( 'barcode', '' );
214 $borrowernumber = $borrowers[0]->{'borrowernumber'};
217 $borrowerslist = \@borrowers;
221 # get the borrower information.....
224 if ($borrowernumber) {
225 $borrower = GetMemberDetails( $borrowernumber, 0 );
226 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
228 # Warningdate is the date that the warning starts appearing
229 my ( $today_year, $today_month, $today_day ) = Today();
230 my ( $warning_year, $warning_month, $warning_day ) = split /-/,
231 $borrower->{'dateexpiry'};
232 my ( $enrol_year, $enrol_month, $enrol_day ) = split /-/,
233 $borrower->{'dateenrolled'};
234 # Renew day is calculated by adding the enrolment period to today
235 my ( $renew_year, $renew_month, $renew_day ) =
236 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
237 0 , $borrower->{'enrolmentperiod'}) if ($enrol_year*$enrol_month*$enrol_day>0);
238 # if the expiry date is before today ie they have expired
239 if ( $warning_year*$warning_month*$warning_day==0
240 || Date_to_Days( $today_year, $today_month, $today_day )
241 > Date_to_Days( $warning_year, $warning_month, $warning_day ) )
243 #borrowercard expired, no issues
247 expired => format_date($borrower->{dateexpiry}),
248 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
251 # check for NotifyBorrowerDeparture
252 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
253 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
254 Date_to_Days( $today_year, $today_month, $today_day ) )
256 # borrower card soon to expire warn librarian
257 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
259 if ( C4::Context->preference('ReturnBeforeExpiry')){
260 $template->param("returnbeforeexpiry" => 1);
265 issuecount => $issue,
275 # always check for blockers on issuing
276 my ( $error, $question ) =
277 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
278 my $blocker = $invalidduedate ? 1 : 0;
280 delete $question->{'DEBT'} if ($debt_confirmed);
281 foreach my $impossible ( keys %$error ) {
283 $impossible => $$error{$impossible},
289 my $confirm_required = 0;
290 unless($issueconfirmed){
291 # Get the item title for more information
292 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
293 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
295 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
296 foreach my $needsconfirmation ( keys %$question ) {
298 $needsconfirmation => $$question{$needsconfirmation},
299 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
300 NEEDSCONFIRMATION => 1
302 $confirm_required = 1;
305 unless($confirm_required) {
306 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
308 if($globalduedate && ! $stickyduedate && $duedatespec_allow ){
309 $duedatespec = $globalduedate->output();
315 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
316 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
317 $template->param( issuecount => $issue );
320 # reload the borrower info for the sake of reseting the flags.....
321 if ($borrowernumber) {
322 $borrower = GetMemberDetails( $borrowernumber, 0 );
325 ##################################################################################
327 # show all reserves of this borrower, and the position of the reservation ....
328 my $borrowercategory;
330 if ($borrowernumber) {
333 # now we show the status of the borrower's reservations
334 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
336 my @WaitingReserveLoop;
338 foreach my $num_res (@borrowerreserv) {
340 my %getWaitingReserveInfo;
341 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
342 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
343 my ( $transfertwhen, $transfertfrom, $transfertto ) =
344 GetTransfers( $num_res->{'itemnumber'} );
346 $getreserv{waiting} = 0;
347 $getreserv{transfered} = 0;
348 $getreserv{nottransfered} = 0;
350 $getreserv{reservedate} = format_date( $num_res->{'reservedate'} );
351 $getreserv{title} = $getiteminfo->{'title'};
352 $getreserv{itemtype} = $itemtypeinfo->{'description'};
353 $getreserv{author} = $getiteminfo->{'author'};
354 $getreserv{barcodereserv} = $getiteminfo->{'barcode'};
355 $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
356 $getreserv{biblionumber} = $getiteminfo->{'biblionumber'};
357 $getreserv{waitingat} = GetBranchName( $num_res->{'branchcode'} );
358 # check if we have a waiting status for reservations
359 if ( $num_res->{'found'} eq 'W' ) {
360 $getreserv{color} = 'reserved';
361 $getreserv{waiting} = 1;
362 # genarate information displaying only waiting reserves
363 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
364 $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
365 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
366 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
367 $getWaitingReserveInfo{reservedate} = format_date( $num_res->{'reservedate'} );
368 $getWaitingReserveInfo{waitingat} = GetBranchName( $num_res->{'branchcode'} );
369 if($num_res->{'branchcode'} eq $branch){ $getWaitingReserveInfo{waitinghere} = 1; }
371 # check transfers with the itemnumber foud in th reservation loop
372 if ($transfertwhen) {
373 $getreserv{color} = 'transfered';
374 $getreserv{transfered} = 1;
375 $getreserv{datesent} = format_date($transfertwhen);
376 $getreserv{frombranch} = GetBranchName($transfertfrom);
379 if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
380 and not $transfertwhen )
382 $getreserv{nottransfered} = 1;
383 $getreserv{nottransferedby} =
384 GetBranchName( $getiteminfo->{'holdingbranch'} );
387 # if we don't have a reserv on item, we put the biblio infos and the waiting position
388 if ( $getiteminfo->{'title'} eq '' ) {
389 my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
390 my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} ); # fixme - we should have item-level reserves here ?
391 $getreserv{color} = 'inwait';
392 $getreserv{title} = $getbibinfo->{'title'};
393 $getreserv{nottransfered} = 0;
394 $getreserv{itemtype} = $getbibtype->{'description'};
395 $getreserv{author} = $getbibinfo->{'author'};
396 $getreserv{biblionumber} = $num_res->{'biblionumber'};
398 $getreserv{waitingposition} = $num_res->{'priority'};
399 push( @reservloop, \%getreserv );
401 # if we have a reserve waiting, initiate waitingreserveloop
402 if ($getreserv{waiting} eq 1) {
403 push (@WaitingReserveLoop, \%getWaitingReserveInfo)
408 # return result to the template
410 countreserv => scalar @reservloop,
411 reservloop => \@reservloop ,
412 WaitingReserveLoop => \@WaitingReserveLoop,
414 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
417 # make the issued books table.
418 my $todaysissues = '';
423 ## ADDED BY JF: new itemtype issuingrules counter stuff
424 my $issued_itemtypes_loop;
425 my $issued_itemtypes_count;
426 my $issued_itemtypes_allowed_count; # hashref with total allowed by itemtype
427 my $issued_itemtypes_remaining; # hashref with remaining
428 my $issued_itemtypes_flags; #hashref that stores flags
429 my @issued_itemtypes_count_loop;
432 # get each issue of the borrower & separate them in todayissues & previous issues
433 my ($issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
435 # split in 2 arrays for today & previous
436 foreach my $it ( @$issueslist ) {
437 # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
438 $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
440 ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
441 $it->{'itemnumber'}, $borrower->{'borrowernumber'}
443 $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
444 my ($can_renew, $can_renew_error) = CanBookBeRenewed(
445 $borrower->{'borrowernumber'},$it->{'itemnumber'}
447 $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
448 my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
449 $it->{'can_renew'} = $can_renew;
450 $it->{'can_confirm'} = !$can_renew && !$restype;
451 $it->{'renew_error'} = $restype;
453 $it->{'dd'} = format_date($it->{'date_due'});
454 $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
455 ($it->{'author'} eq '') and $it->{'author'} = ' ';
456 $it->{'renew_failed'} = $renew_failed[$it->{'itemnumber'}];
457 # ADDED BY JF: NEW ITEMTYPE COUNT DISPLAY
458 $issued_itemtypes_count->{ $it->{'itemtype'} }++;
460 if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
461 push @todaysissues, $it;
463 push @previousissues, $it;
466 if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
467 @todaysissues = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
470 @todaysissues = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
472 if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
473 @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
476 @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
480 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
481 # FIXME: This should utilize all the issuingrules options rather than just the defaults
482 # and it should be moved to a module
483 my $dbh = C4::Context->dbh;
485 # how many of each is allowed?
486 my $issueqty_sth = $dbh->prepare( "
487 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
489 LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
492 #my @issued_itemtypes_count; # huh?
493 $issueqty_sth->execute("*"); # This is a literal asterisk, not a wildcard.
495 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
497 # subtract how many of each this borrower has
498 $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };
500 ( $data->{'maxissueqty'} -
501 $issued_itemtypes_count->{ $data->{'description'} } );
503 # can't have a negative number of remaining
504 if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
505 $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
506 unless ( ( $data->{'maxissueqty'} < 1 )
507 || ( $data->{'itemtype'} eq "*" )
508 || ( $data->{'itemtype'} eq "CIRC" ) )
510 push @issued_itemtypes_count_loop, $data;
513 $issued_itemtypes_loop = \@issued_itemtypes_count_loop;
519 my $CGIselectborrower;
520 if ($borrowerslist) {
522 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
526 push @values, $_->{'borrowernumber'};
527 $labels{ $_->{'borrowernumber'} } =
528 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ... $_->{'address'} ";
530 $CGIselectborrower = CGI::scrolling_list(
531 -name => 'borrowernumber',
533 -id => 'borrowernumber',
536 -onclick => "window.location = '/cgi-bin/koha/circ/circulation.pl?borrowernumber=' + this.value;",
544 my $flags = $borrower->{'flags'};
547 foreach $flag ( sort keys %$flags ) {
548 $template->param( flagged=> 1);
549 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
550 if ( $flags->{$flag}->{'noissues'} ) {
555 if ( $flag eq 'GNA' ) {
556 $template->param( gna => 'true' );
558 if ( $flag eq 'LOST' ) {
559 $template->param( lost => 'true' );
561 if ( $flag eq 'DBARRED' ) {
562 $template->param( dbarred => 'true' );
564 if ( $flag eq 'CHARGES' ) {
567 chargesmsg => $flags->{'CHARGES'}->{'message'},
568 chargesamount => $flags->{'CHARGES'}->{'amount'},
569 charges_is_blocker => 1
572 if ( $flag eq 'CREDITS' ) {
575 creditsmsg => $flags->{'CREDITS'}->{'message'}
580 if ( $flag eq 'CHARGES' ) {
584 chargesmsg => $flags->{'CHARGES'}->{'message'},
585 chargesamount => $flags->{'CHARGES'}->{'amount'},
588 if ( $flag eq 'CREDITS' ) {
591 creditsmsg => $flags->{'CREDITS'}->{'message'}
594 if ( $flag eq 'ODUES' ) {
598 oduesmsg => $flags->{'ODUES'}->{'message'}
601 my $items = $flags->{$flag}->{'itemlist'};
605 # foreach my $item (@$items) {
606 # my ($iteminformation) =
607 # getiteminformation( $item->{'itemnumber'}, 0 );
608 # push @itemswaiting, $iteminformation;
611 if ( $query->param('module') ne 'returns' ) {
612 $template->param( nonreturns => 'true' );
615 if ( $flag eq 'NOTES' ) {
619 notesmsg => $flags->{'NOTES'}->{'message'}
625 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
626 my @temp = split( /\$/, $amountold );
628 if ( $borrower->{'category_type'} eq 'C') {
629 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
630 my $cnt = scalar(@$catcodes);
631 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
632 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
635 my $CGIorganisations;
636 my $member_of_institution;
637 if ( C4::Context->preference("memberofinstitution") ) {
638 my $organisations = get_institutions();
641 foreach my $organisation ( keys %$organisations ) {
642 push @orgs, $organisation;
643 $org_labels{$organisation} =
644 $organisations->{$organisation}->{'surname'};
646 $member_of_institution = 1;
647 $CGIorganisations = CGI::popup_menu(
648 -id => 'organisations',
649 -name => 'organisations',
650 -labels => \%org_labels,
655 $amountold = $temp[1];
658 issued_itemtypes_count_loop => $issued_itemtypes_loop,
659 findborrower => $findborrower,
660 borrower => $borrower,
661 borrowernumber => $borrowernumber,
663 branchname => GetBranchName($borrower->{'branchcode'}),
665 printername => $printer,
666 firstname => $borrower->{'firstname'},
667 surname => $borrower->{'surname'},
668 dateexpiry => format_date($newexpiry),
669 expiry => format_date($borrower->{'dateexpiry'}),
670 categorycode => $borrower->{'categorycode'},
671 categoryname => $borrower->{description},
672 address => $borrower->{'address'},
673 address2 => $borrower->{'address2'},
674 email => $borrower->{'email'},
675 emailpro => $borrower->{'emailpro'},
676 borrowernotes => $borrower->{'borrowernotes'},
677 city => $borrower->{'city'},
678 zipcode => $borrower->{'zipcode'},
679 phone => $borrower->{'phone'} || $borrower->{'mobile'},
680 cardnumber => $borrower->{'cardnumber'},
681 amountold => $amountold,
683 stickyduedate => $stickyduedate,
684 duedatespec => $duedatespec,
686 CGIselectborrower => $CGIselectborrower,
687 todayissues => \@todaysissues,
688 previssues => \@previousissues,
689 inprocess => $inprocess,
690 memberofinstution => $member_of_institution,
691 CGIorganisations => $CGIorganisations,
692 is_child => ($borrower->{'category_type'} eq 'C'),
697 #if ($branchcookie) {
698 #$cookie=[$cookie, $branchcookie, $printercookie];
701 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
702 $template->param( picture => 1 ) if $picture;
706 debt_confirmed => $debt_confirmed,
707 SpecifyDueDate => $duedatespec_allow,
708 CircAutocompl => C4::Context->preference("CircAutocompl"),
709 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
710 dateformat => C4::Context->preference("dateformat"),
711 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
713 output_html_with_http_headers $query, $cookie, $template->output;