3 # Please use 8-character tabs for this file (indents are every 4 characters)
5 # written 8/5/2002 by Finlay
6 # script to execute issuing of books
8 # Copyright 2000-2002 Katipo Communications
10 # This file is part of Koha.
12 # Koha is free software; you can redistribute it and/or modify it under the
13 # terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 2 of the License, or (at your option) any later
17 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
18 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License along with
22 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
23 # Suite 330, Boston, MA 02111-1307 USA
29 use C4::Auth qw/:DEFAULT get_session/;
30 use C4::Dates qw/format_date/;
31 use C4::Branch; # GetBranches
32 use C4::Koha; # GetPrinter
53 # new op dev the branch and the printer are now defined by the userenv
54 # but first we have to check if someone has tried to change them
56 my $branch = $query->param('branch');
58 # update our session so the userenv is updated
59 my $dbh=C4::Context->dbh;
60 my $sessionID = $query->cookie("CGISESSID") ;
61 my $session = get_session($sessionID);
62 $session->param('branch',$branch);
63 my $branchname = GetBranchName($branch);
64 $session->param('branchname',$branchname);
67 my $printer = $query->param('printer');
69 # update our session so the userenv is updated
70 my $dbh=C4::Context->dbh;
71 my $sessionID = $query->cookie("CGISESSID") ;
72 my $session = get_session($sessionID);
73 $session->param('branchprinter',$printer);
76 if (!C4::Context->userenv && !$branch){
77 my $sessionID = $query->cookie("CGISESSID") ;
78 my $session = get_session($sessionID);
79 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
80 # no branch set we can't issue
81 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
86 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
88 template_name => 'circ/circulation.tmpl',
92 flagsrequired => { circulate => 1 },
95 my $branches = GetBranches();
97 my $printers = GetPrinters();
99 my @failedrenews = $query->param('failedrenew');
101 for (@failedrenews) { $renew_failed[$_] = 1; }
103 my $findborrower = $query->param('findborrower');
104 $findborrower =~ s|,| |g;
105 #$findborrower =~ s|'| |g;
106 my $borrowernumber = $query->param('borrowernumber');
108 $branch = C4::Context->userenv->{'branch'};
109 $printer = C4::Context->userenv->{'branchprinter'};
112 # If Autolocated is not activated, we show the Circulation Parameters to chage settings of librarian
113 if (C4::Context->preference("AutoLocation") ne 1)
120 my $barcode = $query->param('barcode') || '';
122 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
123 my $year = $query->param('year');
124 my $month = $query->param('month');
125 my $day = $query->param('day');
126 my $stickyduedate = $query->param('stickyduedate');
127 my $duedatespec = $query->param('duedatespec');
128 my $issueconfirmed = $query->param('issueconfirmed');
129 my $cancelreserve = $query->param('cancelreserve');
130 my $organisation = $query->param('organisations');
131 my $print = $query->param('print');
132 my $newexpiry = $query->param('dateexpiry');
137 # if ($query->param('setcookies')) {
138 # $branchcookie = $query->cookie(-name=>'branch', -value=>"$branch", -expires=>'+1y');
139 # $printercookie = $query->cookie(-name=>'printer', -value=>"$printer", -expires=>'+1y');
143 my ($datedue,$invalidduedate);
145 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
146 $datedue = C4::Dates->new($duedatespec);
149 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
153 my $todaysdate = C4::Dates->new->output('iso');
155 # check and see if we should print
156 if ( $barcode eq '' && $print eq 'maybe' ) {
160 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
162 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
165 borrowernumber => $borrowernumber
169 if ( $print eq 'yes' && $borrowernumber ne '' ) {
170 printslip( $borrowernumber );
171 $query->param( 'borrowernumber', '' );
172 $borrowernumber = '';
176 # STEP 2 : FIND BORROWER
177 # if there is a list of find borrowers....
182 my ( $count, $borrowers ) =
183 SearchMember($findborrower, 'cardnumber', 'web' );
184 my @borrowers = @$borrowers;
185 if ( $#borrowers == -1 ) {
186 $query->param( 'findborrower', '' );
187 $message = "'$findborrower'";
189 elsif ( $#borrowers == 0 ) {
190 $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
191 $query->param( 'barcode', '' );
192 $borrowernumber = $borrowers[0]->{'borrowernumber'};
195 $borrowerslist = \@borrowers;
199 # get the borrower information.....
202 if ($borrowernumber) {
203 $borrower = GetMemberDetails( $borrowernumber, 0 );
204 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
206 # Warningdate is the date that the warning starts appearing
207 my ( $today_year, $today_month, $today_day ) = Today();
208 my ( $warning_year, $warning_month, $warning_day ) = split /-/,
209 $borrower->{'dateexpiry'};
210 my ( $enrol_year, $enrol_month, $enrol_day ) = split /-/,
211 $borrower->{'dateenrolled'};
212 # Renew day is calculated by adding the enrolment period to today
213 my ( $renew_year, $renew_month, $renew_day ) =
214 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
215 0 , $borrower->{'enrolmentperiod'}) if ($enrol_year*$enrol_month*$enrol_day>0);
216 # if the expiry date is before today ie they have expired
217 if ( $warning_year*$warning_month*$warning_day==0
218 || Date_to_Days( $today_year, $today_month, $today_day )
219 > Date_to_Days( $warning_year, $warning_month, $warning_day ) )
221 #borrowercard expired, no issues
225 expired => format_date($borrower->{dateexpiry}),
226 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
229 # check for NotifyBorrowerDeparture
230 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
231 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
232 Date_to_Days( $today_year, $today_month, $today_day ) )
234 # borrower card soon to expire warn librarian
235 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
237 if ( C4::Context->preference('ReturnBeforeExpiry')){
238 $template->param("returnbeforeexpiry" => 1);
243 issuecount => $issue,
253 # always check for blockers on issuing
254 my ( $error, $question ) =
255 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
256 my $noerror = $invalidduedate ? 0 : 1;
257 foreach my $impossible ( keys %$error ) {
259 $impossible => $$error{$impossible},
265 if ($issueconfirmed && $noerror) {
266 # we have no blockers for issuing and any issues needing confirmation have been resolved
267 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
270 elsif ($issueconfirmed){ # FIXME: Do something? Or is this to *intentionally* do nothing?
274 # Get the item title for more information
275 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
277 # only pass needsconfirmation to template if issuing is possible
278 foreach my $needsconfirmation ( keys %$question ) {
280 $needsconfirmation => $$question{$needsconfirmation},
281 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
282 NEEDSCONFIRMATION => 1
286 # Because of the weird conditional structure (empty elsif block),
287 # if we reached here, $issueconfirmed must be false.
288 # Also, since we moved inside the if ($noerror) conditional,
289 # this old chunky conditional can be simplified:
290 # if ( $noerror && ( $noquestion || $issueconfirmed ) ) {
292 AddIssue( $borrower, $barcode, $datedue );
297 itemhomebranch => $getmessageiteminfo->{'homebranch'} ,
298 duedatespec => $duedatespec,
302 # FIXME If the issue is confirmed, we launch another time borrdata2, now display the issue count after issue
303 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
305 issuecount => $issue,
309 # reload the borrower info for the sake of reseting the flags.....
310 if ($borrowernumber) {
311 $borrower = GetMemberDetails( $borrowernumber, 0 );
314 ##################################################################################
316 # show all reserves of this borrower, and the position of the reservation ....
317 my $borrowercategory;
319 if ($borrowernumber) {
322 # now we show the status of the borrower's reservations
323 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
325 my @WaitingReserveLoop;
327 foreach my $num_res (@borrowerreserv) {
329 my %getWaitingReserveInfo;
330 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
331 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
332 my ( $transfertwhen, $transfertfrom, $transfertto ) =
333 GetTransfers( $num_res->{'itemnumber'} );
335 $getreserv{waiting} = 0;
336 $getreserv{transfered} = 0;
337 $getreserv{nottransfered} = 0;
339 $getreserv{reservedate} = format_date( $num_res->{'reservedate'} );
340 $getreserv{title} = $getiteminfo->{'title'};
341 $getreserv{itemtype} = $itemtypeinfo->{'description'};
342 $getreserv{author} = $getiteminfo->{'author'};
343 $getreserv{barcodereserv} = $getiteminfo->{'barcode'};
344 $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
345 $getreserv{biblionumber} = $getiteminfo->{'biblionumber'};
346 $getreserv{waitingat} = GetBranchName( $num_res->{'branchcode'} );
347 # check if we have a waiting status for reservations
348 if ( $num_res->{'found'} eq 'W' ) {
349 $getreserv{color} = 'reserved';
350 $getreserv{waiting} = 1;
351 # genarate information displaying only waiting reserves
352 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
353 $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
354 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
355 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
356 $getWaitingReserveInfo{reservedate} = format_date( $num_res->{'reservedate'} );
357 $getWaitingReserveInfo{waitingat} = GetBranchName( $num_res->{'branchcode'} );
358 if($num_res->{'branchcode'} eq $branch){ $getWaitingReserveInfo{waitinghere} = 1; }
360 # check transfers with the itemnumber foud in th reservation loop
361 if ($transfertwhen) {
362 $getreserv{color} = 'transfered';
363 $getreserv{transfered} = 1;
364 $getreserv{datesent} = format_date($transfertwhen);
365 $getreserv{frombranch} = GetBranchName($transfertfrom);
368 if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
369 and not $transfertwhen )
371 $getreserv{nottransfered} = 1;
372 $getreserv{nottransferedby} =
373 GetBranchName( $getiteminfo->{'holdingbranch'} );
376 # if we don't have a reserv on item, we put the biblio infos and the waiting position
377 if ( $getiteminfo->{'title'} eq '' ) {
378 my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
379 my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} ); # fixme - we should have item-level reserves here ?
380 $getreserv{color} = 'inwait';
381 $getreserv{title} = $getbibinfo->{'title'};
382 $getreserv{waitingposition} = $num_res->{'priority'};
383 $getreserv{nottransfered} = 0;
384 $getreserv{itemtype} = $getbibtype->{'description'};
385 $getreserv{author} = $getbibinfo->{'author'};
386 $getreserv{biblionumber} = $num_res->{'biblionumber'};
388 push( @reservloop, \%getreserv );
390 # if we have a reserve waiting, initiate waitingreserveloop
391 if ($getreserv{waiting} eq 1) {
392 push (@WaitingReserveLoop, \%getWaitingReserveInfo)
397 # return result to the template
399 countreserv => scalar @reservloop,
400 reservloop => \@reservloop ,
401 WaitingReserveLoop => \@WaitingReserveLoop,
403 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
406 # make the issued books table.
407 my $todaysissues = '';
412 ## ADDED BY JF: new itemtype issuingrules counter stuff
413 my $issued_itemtypes_loop;
414 my $issued_itemtypes_count;
415 my $issued_itemtypes_allowed_count; # hashref with total allowed by itemtype
416 my $issued_itemtypes_remaining; # hashref with remaining
417 my $issued_itemtypes_flags; #hashref that stores flags
418 my @issued_itemtypes_count_loop;
422 # get each issue of the borrower & separate them in todayissues & previous issues
423 my ($countissues,$issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
425 # split in 2 arrays for today & previous
426 foreach my $it ( @$issueslist ) {
427 # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
428 $it->{'itemtype'} = (C4::Context->preference('item-level_itypes')) ? $it->{'itype'} : $it->{'itemtype'};
430 my $issuedate = $it->{'issuedate'};
431 $issuedate =~ s/-//g;
432 $issuedate = substr( $issuedate, 0, 8 );
433 ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
434 $it->{'itemnumber'}, $borrower->{'borrowernumber'}
436 $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
438 ($it->{'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 ($restype) and $it->{'can_renew'} = 0;
445 $it->{'dd'} = format_date($it->{'date_due'});
446 my $datedue = $it->{'date_due'};
448 $it->{'od'} = ($datedue < $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 == $issuedate ) {
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;
473 foreach my $book (@todaysissues) {
474 $book->{'togglecolor'} = (++$i % 2) ? 0 : 1 ;
477 foreach my $book (@previousissues) {
478 $book->{'togglecolor'} = (++$i % 2) ? 0 : 1 ;
482 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
483 # FIXME: This should utilize all the issuingrules options rather than just the defaults
484 # and it should be moved to a module
485 my $dbh = C4::Context->dbh;
487 # how many of each is allowed?
488 my $issueqty_sth = $dbh->prepare( "
489 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
491 LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
494 #my @issued_itemtypes_count; # huh?
495 $issueqty_sth->execute("*"); # FIXME: Why have a WHERE clause at all with a hardcoded "*"?
497 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
499 # subtract how many of each this borrower has
500 $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };
502 ( $data->{'maxissueqty'} -
503 $issued_itemtypes_count->{ $data->{'description'} } );
505 # can't have a negative number of remaining
506 if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
507 $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
508 unless ( ( $data->{'maxissueqty'} < 1 )
509 || ( $data->{'itemtype'} eq "*" )
510 || ( $data->{'itemtype'} eq "CIRC" ) )
512 push @issued_itemtypes_count_loop, $data;
515 $issued_itemtypes_loop = \@issued_itemtypes_count_loop;
521 my $CGIselectborrower;
522 if ($borrowerslist) {
526 . lc $a->{'firstname'} cmp lc $b->{'surname'}
527 . lc $b->{'firstname'}
531 push @values, $_->{'borrowernumber'};
532 $labels{ $_->{'borrowernumber'} } =
533 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ... $_->{'address'} ";
535 $CGIselectborrower = CGI::scrolling_list(
536 -name => 'borrowernumber',
538 -id => 'borrowernumber',
548 my $flags = $borrower->{'flags'};
551 foreach $flag ( sort keys %$flags ) {
552 $template->param( flagged=> 1);
553 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
554 if ( $flags->{$flag}->{'noissues'} ) {
559 if ( $flag eq 'GNA' ) {
560 $template->param( gna => 'true' );
562 if ( $flag eq 'LOST' ) {
563 $template->param( lost => 'true' );
565 if ( $flag eq 'DBARRED' ) {
566 $template->param( dbarred => 'true' );
568 if ( $flag eq 'CHARGES' ) {
571 chargesmsg => $flags->{'CHARGES'}->{'message'}
574 if ( $flag eq 'CREDITS' ) {
577 creditsmsg => $flags->{'CREDITS'}->{'message'}
582 if ( $flag eq 'CHARGES' ) {
586 chargesmsg => $flags->{'CHARGES'}->{'message'}
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 my $CGIorganisations;
630 my $member_of_institution;
631 if ( C4::Context->preference("memberofinstitution") ) {
632 my $organisations = get_institutions();
635 foreach my $organisation ( keys %$organisations ) {
636 push @orgs, $organisation;
637 $org_labels{$organisation} =
638 $organisations->{$organisation}->{'surname'};
640 $member_of_institution = 1;
641 $CGIorganisations = CGI::popup_menu(
642 -id => 'organisations',
643 -name => 'organisations',
644 -labels => \%org_labels,
649 $amountold = $temp[1];
653 issued_itemtypes_count_loop => $issued_itemtypes_loop,
654 findborrower => $findborrower,
655 borrower => $borrower,
656 borrowernumber => $borrowernumber,
658 branchname => GetBranchName($borrower->{'branchcode'}),
660 printername => $printer,
661 firstname => $borrower->{'firstname'},
662 surname => $borrower->{'surname'},
663 dateexpiry => format_date($newexpiry),
664 expiry => format_date($borrower->{'dateexpiry'}),
665 categorycode => $borrower->{'categorycode'},
666 categoryname => $borrowercategory->{description},
667 address => $borrower->{'address'},
668 address2 => $borrower->{'address2'},
669 email => $borrower->{'email'},
670 emailpro => $borrower->{'emailpro'},
671 borrowernotes => $borrower->{'borrowernotes'},
672 city => $borrower->{'city'},
673 phone => $borrower->{'phone'} || $borrower->{'mobile'},
674 cardnumber => $borrower->{'cardnumber'},
675 amountold => $amountold,
677 stickyduedate => $stickyduedate,
679 CGIselectborrower => $CGIselectborrower,
680 todayissues => \@todaysissues,
681 previssues => \@previousissues,
682 inprocess => $inprocess,
683 memberofinstution => $member_of_institution,
684 CGIorganisations => $CGIorganisations,
689 # set return date if stickyduedate
690 if ($stickyduedate) {
692 duedatespec => $duedatespec,
696 #if ($branchcookie) {
697 #$cookie=[$cookie, $branchcookie, $printercookie];
700 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
701 $template->param( picture => 1 ) if $picture;
705 SpecifyDueDate => C4::Context->preference("SpecifyDueDate"),
706 CircAutocompl => C4::Context->preference("CircAutocompl"),
707 dateformat => C4::Context->preference("dateformat"),
708 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
710 output_html_with_http_headers $query, $cookie, $template->output;