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 my $tempdate = C4::Dates->new($duedatespec);
147 if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
148 # i.e., it has to be later than today/now
149 $datedue = $tempdate;
152 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
156 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
160 my $todaysdate = C4::Dates->new->output('iso');
162 # check and see if we should print
163 if ( $barcode eq '' && $print eq 'maybe' ) {
167 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
169 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
172 borrowernumber => $borrowernumber
176 if ( $print eq 'yes' && $borrowernumber ne '' ) {
177 printslip( $borrowernumber );
178 $query->param( 'borrowernumber', '' );
179 $borrowernumber = '';
183 # STEP 2 : FIND BORROWER
184 # if there is a list of find borrowers....
189 my ( $count, $borrowers ) =
190 SearchMember($findborrower, 'cardnumber', 'web' );
191 my @borrowers = @$borrowers;
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;
264 foreach my $impossible ( keys %$error ) {
266 $impossible => $$error{$impossible},
272 if ($issueconfirmed && $noerror) {
273 # we have no blockers for issuing and any issues needing confirmation have been resolved
274 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
277 elsif ($issueconfirmed){ # FIXME: Do something? Or is this to *intentionally* do nothing?
281 # Get the item title for more information
282 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
284 # only pass needsconfirmation to template if issuing is possible
285 foreach my $needsconfirmation ( keys %$question ) {
287 $needsconfirmation => $$question{$needsconfirmation},
288 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
289 NEEDSCONFIRMATION => 1
293 # Because of the weird conditional structure (empty elsif block),
294 # if we reached here, $issueconfirmed must be false.
295 # Also, since we moved inside the if ($noerror) conditional,
296 # this old chunky conditional can be simplified:
297 # if ( $noerror && ( $noquestion || $issueconfirmed ) ) {
299 AddIssue( $borrower, $barcode, $datedue );
304 itemhomebranch => $getmessageiteminfo->{'homebranch'} ,
305 duedatespec => $duedatespec,
309 # FIXME If the issue is confirmed, we launch another time borrdata2, now display the issue count after issue
310 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
312 issuecount => $issue,
316 # reload the borrower info for the sake of reseting the flags.....
317 if ($borrowernumber) {
318 $borrower = GetMemberDetails( $borrowernumber, 0 );
321 ##################################################################################
323 # show all reserves of this borrower, and the position of the reservation ....
324 my $borrowercategory;
326 if ($borrowernumber) {
329 # now we show the status of the borrower's reservations
330 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
332 my @WaitingReserveLoop;
334 foreach my $num_res (@borrowerreserv) {
336 my %getWaitingReserveInfo;
337 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
338 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
339 my ( $transfertwhen, $transfertfrom, $transfertto ) =
340 GetTransfers( $num_res->{'itemnumber'} );
342 $getreserv{waiting} = 0;
343 $getreserv{transfered} = 0;
344 $getreserv{nottransfered} = 0;
346 $getreserv{reservedate} = format_date( $num_res->{'reservedate'} );
347 $getreserv{title} = $getiteminfo->{'title'};
348 $getreserv{itemtype} = $itemtypeinfo->{'description'};
349 $getreserv{author} = $getiteminfo->{'author'};
350 $getreserv{barcodereserv} = $getiteminfo->{'barcode'};
351 $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
352 $getreserv{biblionumber} = $getiteminfo->{'biblionumber'};
353 $getreserv{waitingat} = GetBranchName( $num_res->{'branchcode'} );
354 # check if we have a waiting status for reservations
355 if ( $num_res->{'found'} eq 'W' ) {
356 $getreserv{color} = 'reserved';
357 $getreserv{waiting} = 1;
358 # genarate information displaying only waiting reserves
359 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
360 $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
361 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
362 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
363 $getWaitingReserveInfo{reservedate} = format_date( $num_res->{'reservedate'} );
364 $getWaitingReserveInfo{waitingat} = GetBranchName( $num_res->{'branchcode'} );
365 if($num_res->{'branchcode'} eq $branch){ $getWaitingReserveInfo{waitinghere} = 1; }
367 # check transfers with the itemnumber foud in th reservation loop
368 if ($transfertwhen) {
369 $getreserv{color} = 'transfered';
370 $getreserv{transfered} = 1;
371 $getreserv{datesent} = format_date($transfertwhen);
372 $getreserv{frombranch} = GetBranchName($transfertfrom);
375 if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
376 and not $transfertwhen )
378 $getreserv{nottransfered} = 1;
379 $getreserv{nottransferedby} =
380 GetBranchName( $getiteminfo->{'holdingbranch'} );
383 # if we don't have a reserv on item, we put the biblio infos and the waiting position
384 if ( $getiteminfo->{'title'} eq '' ) {
385 my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
386 my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} ); # fixme - we should have item-level reserves here ?
387 $getreserv{color} = 'inwait';
388 $getreserv{title} = $getbibinfo->{'title'};
389 $getreserv{waitingposition} = $num_res->{'priority'};
390 $getreserv{nottransfered} = 0;
391 $getreserv{itemtype} = $getbibtype->{'description'};
392 $getreserv{author} = $getbibinfo->{'author'};
393 $getreserv{biblionumber} = $num_res->{'biblionumber'};
395 push( @reservloop, \%getreserv );
397 # if we have a reserve waiting, initiate waitingreserveloop
398 if ($getreserv{waiting} eq 1) {
399 push (@WaitingReserveLoop, \%getWaitingReserveInfo)
404 # return result to the template
406 countreserv => scalar @reservloop,
407 reservloop => \@reservloop ,
408 WaitingReserveLoop => \@WaitingReserveLoop,
410 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
413 # make the issued books table.
414 my $todaysissues = '';
419 ## ADDED BY JF: new itemtype issuingrules counter stuff
420 my $issued_itemtypes_loop;
421 my $issued_itemtypes_count;
422 my $issued_itemtypes_allowed_count; # hashref with total allowed by itemtype
423 my $issued_itemtypes_remaining; # hashref with remaining
424 my $issued_itemtypes_flags; #hashref that stores flags
425 my @issued_itemtypes_count_loop;
429 # get each issue of the borrower & separate them in todayissues & previous issues
430 my ($countissues,$issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
432 # split in 2 arrays for today & previous
433 foreach my $it ( @$issueslist ) {
434 # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
435 $it->{'itemtype'} = (C4::Context->preference('item-level_itypes')) ? $it->{'itype'} : $it->{'itemtype'};
437 my $issuedate = $it->{'issuedate'};
438 $issuedate =~ s/-//g;
439 $issuedate = substr( $issuedate, 0, 8 );
440 ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
441 $it->{'itemnumber'}, $borrower->{'borrowernumber'}
443 $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
445 ($it->{'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 ($restype) and $it->{'can_renew'} = 0;
452 $it->{'dd'} = format_date($it->{'date_due'});
453 my $datedue = $it->{'date_due'};
455 $it->{'od'} = ($datedue < $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 == $issuedate ) {
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;
480 foreach my $book (@todaysissues) {
481 $book->{'togglecolor'} = (++$i % 2) ? 0 : 1 ;
484 foreach my $book (@previousissues) {
485 $book->{'togglecolor'} = (++$i % 2) ? 0 : 1 ;
489 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
490 # FIXME: This should utilize all the issuingrules options rather than just the defaults
491 # and it should be moved to a module
492 my $dbh = C4::Context->dbh;
494 # how many of each is allowed?
495 my $issueqty_sth = $dbh->prepare( "
496 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
498 LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
501 #my @issued_itemtypes_count; # huh?
502 $issueqty_sth->execute("*"); # FIXME: Why have a WHERE clause at all with a hardcoded "*"?
504 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
506 # subtract how many of each this borrower has
507 $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };
509 ( $data->{'maxissueqty'} -
510 $issued_itemtypes_count->{ $data->{'description'} } );
512 # can't have a negative number of remaining
513 if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
514 $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
515 unless ( ( $data->{'maxissueqty'} < 1 )
516 || ( $data->{'itemtype'} eq "*" )
517 || ( $data->{'itemtype'} eq "CIRC" ) )
519 push @issued_itemtypes_count_loop, $data;
522 $issued_itemtypes_loop = \@issued_itemtypes_count_loop;
528 my $CGIselectborrower;
529 if ($borrowerslist) {
533 . lc $a->{'firstname'} cmp lc $b->{'surname'}
534 . lc $b->{'firstname'}
538 push @values, $_->{'borrowernumber'};
539 $labels{ $_->{'borrowernumber'} } =
540 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ... $_->{'address'} ";
542 $CGIselectborrower = CGI::scrolling_list(
543 -name => 'borrowernumber',
545 -id => 'borrowernumber',
555 my $flags = $borrower->{'flags'};
558 foreach $flag ( sort keys %$flags ) {
559 $template->param( flagged=> 1);
560 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
561 if ( $flags->{$flag}->{'noissues'} ) {
566 if ( $flag eq 'GNA' ) {
567 $template->param( gna => 'true' );
569 if ( $flag eq 'LOST' ) {
570 $template->param( lost => 'true' );
572 if ( $flag eq 'DBARRED' ) {
573 $template->param( dbarred => 'true' );
575 if ( $flag eq 'CHARGES' ) {
578 chargesmsg => $flags->{'CHARGES'}->{'message'},
579 charges_is_blocker => 1
582 if ( $flag eq 'CREDITS' ) {
585 creditsmsg => $flags->{'CREDITS'}->{'message'}
590 if ( $flag eq 'CHARGES' ) {
594 chargesmsg => $flags->{'CHARGES'}->{'message'}
597 if ( $flag eq 'CREDITS' ) {
600 creditsmsg => $flags->{'CREDITS'}->{'message'}
603 if ( $flag eq 'ODUES' ) {
607 oduesmsg => $flags->{'ODUES'}->{'message'}
610 my $items = $flags->{$flag}->{'itemlist'};
614 # foreach my $item (@$items) {
615 # my ($iteminformation) =
616 # getiteminformation( $item->{'itemnumber'}, 0 );
617 # push @itemswaiting, $iteminformation;
620 if ( $query->param('module') ne 'returns' ) {
621 $template->param( nonreturns => 'true' );
624 if ( $flag eq 'NOTES' ) {
628 notesmsg => $flags->{'NOTES'}->{'message'}
634 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
635 my @temp = split( /\$/, $amountold );
637 my $CGIorganisations;
638 my $member_of_institution;
639 if ( C4::Context->preference("memberofinstitution") ) {
640 my $organisations = get_institutions();
643 foreach my $organisation ( keys %$organisations ) {
644 push @orgs, $organisation;
645 $org_labels{$organisation} =
646 $organisations->{$organisation}->{'surname'};
648 $member_of_institution = 1;
649 $CGIorganisations = CGI::popup_menu(
650 -id => 'organisations',
651 -name => 'organisations',
652 -labels => \%org_labels,
657 $amountold = $temp[1];
661 issued_itemtypes_count_loop => $issued_itemtypes_loop,
662 findborrower => $findborrower,
663 borrower => $borrower,
664 borrowernumber => $borrowernumber,
666 branchname => GetBranchName($borrower->{'branchcode'}),
668 printername => $printer,
669 firstname => $borrower->{'firstname'},
670 surname => $borrower->{'surname'},
671 dateexpiry => format_date($newexpiry),
672 expiry => format_date($borrower->{'dateexpiry'}),
673 categorycode => $borrower->{'categorycode'},
674 categoryname => $borrowercategory->{description},
675 address => $borrower->{'address'},
676 address2 => $borrower->{'address2'},
677 email => $borrower->{'email'},
678 emailpro => $borrower->{'emailpro'},
679 borrowernotes => $borrower->{'borrowernotes'},
680 city => $borrower->{'city'},
681 phone => $borrower->{'phone'} || $borrower->{'mobile'},
682 cardnumber => $borrower->{'cardnumber'},
683 amountold => $amountold,
685 stickyduedate => $stickyduedate,
687 CGIselectborrower => $CGIselectborrower,
688 todayissues => \@todaysissues,
689 previssues => \@previousissues,
690 inprocess => $inprocess,
691 memberofinstution => $member_of_institution,
692 CGIorganisations => $CGIorganisations,
697 # set return date if stickyduedate
698 if ($stickyduedate) {
700 duedatespec => $duedatespec,
704 #if ($branchcookie) {
705 #$cookie=[$cookie, $branchcookie, $printercookie];
708 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
709 $template->param( picture => 1 ) if $picture;
713 SpecifyDueDate => C4::Context->preference("SpecifyDueDate"),
714 CircAutocompl => C4::Context->preference("CircAutocompl"),
715 dateformat => C4::Context->preference("dateformat"),
716 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
718 output_html_with_http_headers $query, $cookie, $template->output;