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') || '';
115 $barcode =~ s/^[ \t]+|[ \t]+$//g; # remove leading/trailing whitespace
117 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
118 my $stickyduedate = $query->param('stickyduedate');
119 my $duedatespec = $query->param('duedatespec');
120 my $issueconfirmed = $query->param('issueconfirmed');
121 my $cancelreserve = $query->param('cancelreserve');
122 my $organisation = $query->param('organisations');
123 my $print = $query->param('print');
124 my $newexpiry = $query->param('dateexpiry');
125 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
130 # if ($query->param('setcookies')) {
131 # $branchcookie = $query->cookie(-name=>'branch', -value=>"$branch", -expires=>'+1y');
132 # $printercookie = $query->cookie(-name=>'printer', -value=>"$printer", -expires=>'+1y');
136 my ($datedue,$invalidduedate,$globalduedate);
138 if(C4::Context->preference('globalDueDate') && (C4::Context->preference('globalDueDate') =~ C4::Dates->regexp('syspref'))){
139 $globalduedate = C4::Dates->new(C4::Context->preference('globalDueDate'));
141 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
142 if($duedatespec_allow){
144 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
145 my $tempdate = C4::Dates->new($duedatespec);
146 if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
147 # i.e., it has to be later than today/now
148 $datedue = $tempdate;
151 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
155 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
158 # pass global due date to tmpl if specifyduedate is true
159 # and we have no barcode (loading circ page but not checking out)
160 if($globalduedate && ! $barcode ){
161 $duedatespec = $globalduedate->output();
166 $datedue = $globalduedate if($globalduedate);
169 my $todaysdate = C4::Dates->new->output('iso');
171 # check and see if we should print
172 if ( $barcode eq '' && $print eq 'maybe' ) {
176 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
177 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
180 borrowernumber => $borrowernumber
184 if ( $print eq 'yes' && $borrowernumber ne '' ) {
185 printslip( $borrowernumber );
186 $query->param( 'borrowernumber', '' );
187 $borrowernumber = '';
191 # STEP 2 : FIND BORROWER
192 # if there is a list of find borrowers....
197 my ( $count, $borrowers ) =
198 SearchMember($findborrower, 'cardnumber', 'web' );
199 my @borrowers = @$borrowers;
201 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
203 if (C4::Context->preference("AddPatronLists")=~/code/){
204 my $categories=GetBorrowercategoryList;
205 $categories->[0]->{'first'}=1;
206 $template->param(categories=>$categories);
208 if ( $#borrowers == -1 ) {
209 $query->param( 'findborrower', '' );
210 $message = "'$findborrower'";
212 elsif ( $#borrowers == 0 ) {
213 $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
214 $query->param( 'barcode', '' );
215 $borrowernumber = $borrowers[0]->{'borrowernumber'};
218 $borrowerslist = \@borrowers;
222 # get the borrower information.....
225 if ($borrowernumber) {
226 $borrower = GetMemberDetails( $borrowernumber, 0 );
227 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
229 # Warningdate is the date that the warning starts appearing
230 my ( $today_year, $today_month, $today_day ) = Today();
231 my ( $warning_year, $warning_month, $warning_day ) = split /-/,
232 $borrower->{'dateexpiry'};
233 my ( $enrol_year, $enrol_month, $enrol_day ) = split /-/,
234 $borrower->{'dateenrolled'};
235 # Renew day is calculated by adding the enrolment period to today
236 my ( $renew_year, $renew_month, $renew_day ) =
237 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
238 0 , $borrower->{'enrolmentperiod'}) if ($enrol_year*$enrol_month*$enrol_day>0);
239 # if the expiry date is before today ie they have expired
240 if ( $warning_year*$warning_month*$warning_day==0
241 || Date_to_Days( $today_year, $today_month, $today_day )
242 > Date_to_Days( $warning_year, $warning_month, $warning_day ) )
244 #borrowercard expired, no issues
248 expired => format_date($borrower->{dateexpiry}),
249 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
252 # check for NotifyBorrowerDeparture
253 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
254 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
255 Date_to_Days( $today_year, $today_month, $today_day ) )
257 # borrower card soon to expire warn librarian
258 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
260 if ( C4::Context->preference('ReturnBeforeExpiry')){
261 $template->param("returnbeforeexpiry" => 1);
266 issuecount => $issue,
276 # always check for blockers on issuing
277 my ( $error, $question ) =
278 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
279 my $blocker = $invalidduedate ? 1 : 0;
281 delete $question->{'DEBT'} if ($debt_confirmed);
282 foreach my $impossible ( keys %$error ) {
284 $impossible => $$error{$impossible},
290 my $confirm_required = 0;
291 unless($issueconfirmed){
292 # Get the item title for more information
293 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
294 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
296 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
297 foreach my $needsconfirmation ( keys %$question ) {
299 $needsconfirmation => $$question{$needsconfirmation},
300 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
301 NEEDSCONFIRMATION => 1
303 $confirm_required = 1;
306 unless($confirm_required) {
307 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
309 if($globalduedate && ! $stickyduedate && $duedatespec_allow ){
310 $duedatespec = $globalduedate->output();
316 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
317 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
318 $template->param( issuecount => $issue );
321 # reload the borrower info for the sake of reseting the flags.....
322 if ($borrowernumber) {
323 $borrower = GetMemberDetails( $borrowernumber, 0 );
326 ##################################################################################
328 # show all reserves of this borrower, and the position of the reservation ....
329 my $borrowercategory;
331 if ($borrowernumber) {
334 # now we show the status of the borrower's reservations
335 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
337 my @WaitingReserveLoop;
339 foreach my $num_res (@borrowerreserv) {
341 my %getWaitingReserveInfo;
342 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
343 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
344 my ( $transfertwhen, $transfertfrom, $transfertto ) =
345 GetTransfers( $num_res->{'itemnumber'} );
347 $getreserv{waiting} = 0;
348 $getreserv{transfered} = 0;
349 $getreserv{nottransfered} = 0;
351 $getreserv{reservedate} = format_date( $num_res->{'reservedate'} );
352 $getreserv{title} = $getiteminfo->{'title'};
353 $getreserv{itemtype} = $itemtypeinfo->{'description'};
354 $getreserv{author} = $getiteminfo->{'author'};
355 $getreserv{barcodereserv} = $getiteminfo->{'barcode'};
356 $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
357 $getreserv{biblionumber} = $getiteminfo->{'biblionumber'};
358 $getreserv{waitingat} = GetBranchName( $num_res->{'branchcode'} );
359 # check if we have a waiting status for reservations
360 if ( $num_res->{'found'} eq 'W' ) {
361 $getreserv{color} = 'reserved';
362 $getreserv{waiting} = 1;
363 # genarate information displaying only waiting reserves
364 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
365 $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
366 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
367 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
368 $getWaitingReserveInfo{reservedate} = format_date( $num_res->{'reservedate'} );
369 $getWaitingReserveInfo{waitingat} = GetBranchName( $num_res->{'branchcode'} );
370 if($num_res->{'branchcode'} eq $branch){ $getWaitingReserveInfo{waitinghere} = 1; }
372 # check transfers with the itemnumber foud in th reservation loop
373 if ($transfertwhen) {
374 $getreserv{color} = 'transfered';
375 $getreserv{transfered} = 1;
376 $getreserv{datesent} = format_date($transfertwhen);
377 $getreserv{frombranch} = GetBranchName($transfertfrom);
380 if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
381 and not $transfertwhen )
383 $getreserv{nottransfered} = 1;
384 $getreserv{nottransferedby} =
385 GetBranchName( $getiteminfo->{'holdingbranch'} );
388 # if we don't have a reserv on item, we put the biblio infos and the waiting position
389 if ( $getiteminfo->{'title'} eq '' ) {
390 my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
391 my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} ); # fixme - we should have item-level reserves here ?
392 $getreserv{color} = 'inwait';
393 $getreserv{title} = $getbibinfo->{'title'};
394 $getreserv{nottransfered} = 0;
395 $getreserv{itemtype} = $getbibtype->{'description'};
396 $getreserv{author} = $getbibinfo->{'author'};
397 $getreserv{biblionumber} = $num_res->{'biblionumber'};
399 $getreserv{waitingposition} = $num_res->{'priority'};
400 push( @reservloop, \%getreserv );
402 # if we have a reserve waiting, initiate waitingreserveloop
403 if ($getreserv{waiting} eq 1) {
404 push (@WaitingReserveLoop, \%getWaitingReserveInfo)
409 # return result to the template
411 countreserv => scalar @reservloop,
412 reservloop => \@reservloop ,
413 WaitingReserveLoop => \@WaitingReserveLoop,
415 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
418 # make the issued books table.
419 my $todaysissues = '';
424 ## ADDED BY JF: new itemtype issuingrules counter stuff
425 my $issued_itemtypes_loop;
426 my $issued_itemtypes_count;
427 my $issued_itemtypes_allowed_count; # hashref with total allowed by itemtype
428 my $issued_itemtypes_remaining; # hashref with remaining
429 my $issued_itemtypes_flags; #hashref that stores flags
430 my @issued_itemtypes_count_loop;
433 # get each issue of the borrower & separate them in todayissues & previous issues
434 my ($issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
436 # split in 2 arrays for today & previous
437 foreach my $it ( @$issueslist ) {
438 # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
439 $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
441 ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
442 $it->{'itemnumber'}, $borrower->{'borrowernumber'}
444 $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
445 my ($can_renew, $can_renew_error) = CanBookBeRenewed(
446 $borrower->{'borrowernumber'},$it->{'itemnumber'}
448 $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
449 my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
450 $it->{'can_renew'} = $can_renew;
451 $it->{'can_confirm'} = !$can_renew && !$restype;
452 $it->{'renew_error'} = $restype;
454 $it->{'dd'} = format_date($it->{'date_due'});
455 $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
456 ($it->{'author'} eq '') and $it->{'author'} = ' ';
457 $it->{'renew_failed'} = $renew_failed[$it->{'itemnumber'}];
458 # ADDED BY JF: NEW ITEMTYPE COUNT DISPLAY
459 $issued_itemtypes_count->{ $it->{'itemtype'} }++;
461 if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
462 push @todaysissues, $it;
464 push @previousissues, $it;
467 if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
468 @todaysissues = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
471 @todaysissues = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
473 if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
474 @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
477 @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
481 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
482 # FIXME: This should utilize all the issuingrules options rather than just the defaults
483 # and it should be moved to a module
484 my $dbh = C4::Context->dbh;
486 # how many of each is allowed?
487 my $issueqty_sth = $dbh->prepare( "
488 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
490 LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
493 #my @issued_itemtypes_count; # huh?
494 $issueqty_sth->execute("*"); # This is a literal asterisk, not a wildcard.
496 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
498 # subtract how many of each this borrower has
499 $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };
501 ( $data->{'maxissueqty'} -
502 $issued_itemtypes_count->{ $data->{'description'} } );
504 # can't have a negative number of remaining
505 if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
506 $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
507 unless ( ( $data->{'maxissueqty'} < 1 )
508 || ( $data->{'itemtype'} eq "*" )
509 || ( $data->{'itemtype'} eq "CIRC" ) )
511 push @issued_itemtypes_count_loop, $data;
514 $issued_itemtypes_loop = \@issued_itemtypes_count_loop;
520 my $CGIselectborrower;
521 if ($borrowerslist) {
523 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
527 push @values, $_->{'borrowernumber'};
528 $labels{ $_->{'borrowernumber'} } =
529 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ... $_->{'address'} ";
531 $CGIselectborrower = CGI::scrolling_list(
532 -name => 'borrowernumber',
534 -id => 'borrowernumber',
537 -onclick => "window.location = '/cgi-bin/koha/circ/circulation.pl?borrowernumber=' + this.value;",
545 my $flags = $borrower->{'flags'};
548 foreach $flag ( sort keys %$flags ) {
549 $template->param( flagged=> 1);
550 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
551 if ( $flags->{$flag}->{'noissues'} ) {
556 if ( $flag eq 'GNA' ) {
557 $template->param( gna => 'true' );
559 if ( $flag eq 'LOST' ) {
560 $template->param( lost => 'true' );
562 if ( $flag eq 'DBARRED' ) {
563 $template->param( dbarred => 'true' );
565 if ( $flag eq 'CHARGES' ) {
568 chargesmsg => $flags->{'CHARGES'}->{'message'},
569 chargesamount => $flags->{'CHARGES'}->{'amount'},
570 charges_is_blocker => 1
573 if ( $flag eq 'CREDITS' ) {
576 creditsmsg => $flags->{'CREDITS'}->{'message'}
581 if ( $flag eq 'CHARGES' ) {
585 chargesmsg => $flags->{'CHARGES'}->{'message'},
586 chargesamount => $flags->{'CHARGES'}->{'amount'},
589 if ( $flag eq 'CREDITS' ) {
592 creditsmsg => $flags->{'CREDITS'}->{'message'}
595 if ( $flag eq 'ODUES' ) {
599 oduesmsg => $flags->{'ODUES'}->{'message'}
602 my $items = $flags->{$flag}->{'itemlist'};
606 # foreach my $item (@$items) {
607 # my ($iteminformation) =
608 # getiteminformation( $item->{'itemnumber'}, 0 );
609 # push @itemswaiting, $iteminformation;
612 if ( $query->param('module') ne 'returns' ) {
613 $template->param( nonreturns => 'true' );
616 if ( $flag eq 'NOTES' ) {
620 notesmsg => $flags->{'NOTES'}->{'message'}
626 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
627 my @temp = split( /\$/, $amountold );
629 if ( $borrower->{'category_type'} eq 'C') {
630 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
631 my $cnt = scalar(@$catcodes);
632 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
633 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
636 my $CGIorganisations;
637 my $member_of_institution;
638 if ( C4::Context->preference("memberofinstitution") ) {
639 my $organisations = get_institutions();
642 foreach my $organisation ( keys %$organisations ) {
643 push @orgs, $organisation;
644 $org_labels{$organisation} =
645 $organisations->{$organisation}->{'surname'};
647 $member_of_institution = 1;
648 $CGIorganisations = CGI::popup_menu(
649 -id => 'organisations',
650 -name => 'organisations',
651 -labels => \%org_labels,
656 $amountold = $temp[1];
659 issued_itemtypes_count_loop => $issued_itemtypes_loop,
660 findborrower => $findborrower,
661 borrower => $borrower,
662 borrowernumber => $borrowernumber,
664 branchname => GetBranchName($borrower->{'branchcode'}),
666 printername => $printer,
667 firstname => $borrower->{'firstname'},
668 surname => $borrower->{'surname'},
669 dateexpiry => format_date($newexpiry),
670 expiry => format_date($borrower->{'dateexpiry'}),
671 categorycode => $borrower->{'categorycode'},
672 categoryname => $borrower->{description},
673 address => $borrower->{'address'},
674 address2 => $borrower->{'address2'},
675 email => $borrower->{'email'},
676 emailpro => $borrower->{'emailpro'},
677 borrowernotes => $borrower->{'borrowernotes'},
678 city => $borrower->{'city'},
679 zipcode => $borrower->{'zipcode'},
680 phone => $borrower->{'phone'} || $borrower->{'mobile'},
681 cardnumber => $borrower->{'cardnumber'},
682 amountold => $amountold,
684 stickyduedate => $stickyduedate,
685 duedatespec => $duedatespec,
687 CGIselectborrower => $CGIselectborrower,
688 todayissues => \@todaysissues,
689 previssues => \@previousissues,
690 inprocess => $inprocess,
691 memberofinstution => $member_of_institution,
692 CGIorganisations => $CGIorganisations,
693 is_child => ($borrower->{'category_type'} eq 'C'),
698 #if ($branchcookie) {
699 #$cookie=[$cookie, $branchcookie, $printercookie];
702 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
703 $template->param( picture => 1 ) if $picture;
707 debt_confirmed => $debt_confirmed,
708 SpecifyDueDate => $duedatespec_allow,
709 CircAutocompl => C4::Context->preference("CircAutocompl"),
710 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
711 dateformat => C4::Context->preference("dateformat"),
712 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
714 output_html_with_http_headers $query, $cookie, $template->output;