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 => 1 },
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);
137 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
138 my $tempdate = C4::Dates->new($duedatespec);
139 if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
140 # i.e., it has to be later than today/now
141 $datedue = $tempdate;
144 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
148 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
152 my $todaysdate = C4::Dates->new->output('iso');
154 # check and see if we should print
155 if ( $barcode eq '' && $print eq 'maybe' ) {
159 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
161 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
164 borrowernumber => $borrowernumber
168 if ( $print eq 'yes' && $borrowernumber ne '' ) {
169 printslip( $borrowernumber );
170 $query->param( 'borrowernumber', '' );
171 $borrowernumber = '';
175 # STEP 2 : FIND BORROWER
176 # if there is a list of find borrowers....
181 my ( $count, $borrowers ) =
182 SearchMember($findborrower, 'cardnumber', 'web' );
183 my @borrowers = @$borrowers;
184 if ( $#borrowers == -1 ) {
185 $query->param( 'findborrower', '' );
186 $message = "'$findborrower'";
188 elsif ( $#borrowers == 0 ) {
189 $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
190 $query->param( 'barcode', '' );
191 $borrowernumber = $borrowers[0]->{'borrowernumber'};
194 $borrowerslist = \@borrowers;
198 # get the borrower information.....
201 if ($borrowernumber) {
202 $borrower = GetMemberDetails( $borrowernumber, 0 );
203 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
205 # Warningdate is the date that the warning starts appearing
206 my ( $today_year, $today_month, $today_day ) = Today();
207 my ( $warning_year, $warning_month, $warning_day ) = split /-/,
208 $borrower->{'dateexpiry'};
209 my ( $enrol_year, $enrol_month, $enrol_day ) = split /-/,
210 $borrower->{'dateenrolled'};
211 # Renew day is calculated by adding the enrolment period to today
212 my ( $renew_year, $renew_month, $renew_day ) =
213 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
214 0 , $borrower->{'enrolmentperiod'}) if ($enrol_year*$enrol_month*$enrol_day>0);
215 # if the expiry date is before today ie they have expired
216 if ( $warning_year*$warning_month*$warning_day==0
217 || Date_to_Days( $today_year, $today_month, $today_day )
218 > Date_to_Days( $warning_year, $warning_month, $warning_day ) )
220 #borrowercard expired, no issues
224 expired => format_date($borrower->{dateexpiry}),
225 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
228 # check for NotifyBorrowerDeparture
229 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
230 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
231 Date_to_Days( $today_year, $today_month, $today_day ) )
233 # borrower card soon to expire warn librarian
234 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
236 if ( C4::Context->preference('ReturnBeforeExpiry')){
237 $template->param("returnbeforeexpiry" => 1);
242 issuecount => $issue,
252 # always check for blockers on issuing
253 my ( $error, $question ) =
254 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
255 my $noerror = $invalidduedate ? 0 : 1;
257 delete $question->{'DEBT'} if ($debt_confirmed);
258 foreach my $impossible ( keys %$error ) {
260 $impossible => $$error{$impossible},
266 if ($issueconfirmed && $noerror) {
267 # we have no blockers for issuing and any issues needing confirmation have been resolved
268 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
271 elsif ($issueconfirmed){ # FIXME: Do something? Or is this to *intentionally* do nothing?
275 # Get the item title for more information
276 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
278 # only pass needsconfirmation to template if issuing is possible
279 foreach my $needsconfirmation ( keys %$question ) {
281 $needsconfirmation => $$question{$needsconfirmation},
282 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
283 NEEDSCONFIRMATION => 1
287 # Because of the weird conditional structure (empty elsif block),
288 # if we reached here, $issueconfirmed must be false.
289 # Also, since we moved inside the if ($noerror) conditional,
290 # this old chunky conditional can be simplified:
291 # if ( $noerror && ( $noquestion || $issueconfirmed ) ) {
293 AddIssue( $borrower, $barcode, $datedue );
298 itemhomebranch => $getmessageiteminfo->{'homebranch'} ,
299 duedatespec => $duedatespec,
303 # FIXME If the issue is confirmed, we launch another time borrdata2, now display the issue count after issue
304 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
306 issuecount => $issue,
310 # reload the borrower info for the sake of reseting the flags.....
311 if ($borrowernumber) {
312 $borrower = GetMemberDetails( $borrowernumber, 0 );
315 ##################################################################################
317 # show all reserves of this borrower, and the position of the reservation ....
318 my $borrowercategory;
320 if ($borrowernumber) {
323 # now we show the status of the borrower's reservations
324 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
326 my @WaitingReserveLoop;
328 foreach my $num_res (@borrowerreserv) {
330 my %getWaitingReserveInfo;
331 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
332 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
333 my ( $transfertwhen, $transfertfrom, $transfertto ) =
334 GetTransfers( $num_res->{'itemnumber'} );
336 $getreserv{waiting} = 0;
337 $getreserv{transfered} = 0;
338 $getreserv{nottransfered} = 0;
340 $getreserv{reservedate} = format_date( $num_res->{'reservedate'} );
341 $getreserv{title} = $getiteminfo->{'title'};
342 $getreserv{itemtype} = $itemtypeinfo->{'description'};
343 $getreserv{author} = $getiteminfo->{'author'};
344 $getreserv{barcodereserv} = $getiteminfo->{'barcode'};
345 $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
346 $getreserv{biblionumber} = $getiteminfo->{'biblionumber'};
347 $getreserv{waitingat} = GetBranchName( $num_res->{'branchcode'} );
348 # check if we have a waiting status for reservations
349 if ( $num_res->{'found'} eq 'W' ) {
350 $getreserv{color} = 'reserved';
351 $getreserv{waiting} = 1;
352 # genarate information displaying only waiting reserves
353 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
354 $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
355 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
356 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
357 $getWaitingReserveInfo{reservedate} = format_date( $num_res->{'reservedate'} );
358 $getWaitingReserveInfo{waitingat} = GetBranchName( $num_res->{'branchcode'} );
359 if($num_res->{'branchcode'} eq $branch){ $getWaitingReserveInfo{waitinghere} = 1; }
361 # check transfers with the itemnumber foud in th reservation loop
362 if ($transfertwhen) {
363 $getreserv{color} = 'transfered';
364 $getreserv{transfered} = 1;
365 $getreserv{datesent} = format_date($transfertwhen);
366 $getreserv{frombranch} = GetBranchName($transfertfrom);
369 if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
370 and not $transfertwhen )
372 $getreserv{nottransfered} = 1;
373 $getreserv{nottransferedby} =
374 GetBranchName( $getiteminfo->{'holdingbranch'} );
377 # if we don't have a reserv on item, we put the biblio infos and the waiting position
378 if ( $getiteminfo->{'title'} eq '' ) {
379 my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
380 my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} ); # fixme - we should have item-level reserves here ?
381 $getreserv{color} = 'inwait';
382 $getreserv{title} = $getbibinfo->{'title'};
383 $getreserv{nottransfered} = 0;
384 $getreserv{itemtype} = $getbibtype->{'description'};
385 $getreserv{author} = $getbibinfo->{'author'};
386 $getreserv{biblionumber} = $num_res->{'biblionumber'};
388 $getreserv{waitingposition} = $num_res->{'priority'};
389 push( @reservloop, \%getreserv );
391 # if we have a reserve waiting, initiate waitingreserveloop
392 if ($getreserv{waiting} eq 1) {
393 push (@WaitingReserveLoop, \%getWaitingReserveInfo)
398 # return result to the template
400 countreserv => scalar @reservloop,
401 reservloop => \@reservloop ,
402 WaitingReserveLoop => \@WaitingReserveLoop,
404 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
407 # make the issued books table.
408 my $todaysissues = '';
413 ## ADDED BY JF: new itemtype issuingrules counter stuff
414 my $issued_itemtypes_loop;
415 my $issued_itemtypes_count;
416 my $issued_itemtypes_allowed_count; # hashref with total allowed by itemtype
417 my $issued_itemtypes_remaining; # hashref with remaining
418 my $issued_itemtypes_flags; #hashref that stores flags
419 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 ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
431 $it->{'itemnumber'}, $borrower->{'borrowernumber'}
433 $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
434 my ($can_renew, $can_renew_error) = CanBookBeRenewed(
435 $borrower->{'borrowernumber'},$it->{'itemnumber'}
437 $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
438 my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
439 $it->{'can_renew'} = $can_renew;
440 $it->{'can_confirm'} = !$can_renew && !$restype;
441 $it->{'renew_error'} = $restype;
443 $it->{'dd'} = format_date($it->{'date_due'});
444 $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
445 ($it->{'author'} eq '') and $it->{'author'} = ' ';
446 $it->{'renew_failed'} = $renew_failed[$it->{'itemnumber'}];
447 # ADDED BY JF: NEW ITEMTYPE COUNT DISPLAY
448 $issued_itemtypes_count->{ $it->{'itemtype'} }++;
450 if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
451 push @todaysissues, $it;
453 push @previousissues, $it;
456 if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
457 @todaysissues = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
460 @todaysissues = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
462 if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
463 @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
466 @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
470 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
471 # FIXME: This should utilize all the issuingrules options rather than just the defaults
472 # and it should be moved to a module
473 my $dbh = C4::Context->dbh;
475 # how many of each is allowed?
476 my $issueqty_sth = $dbh->prepare( "
477 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
479 LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
482 #my @issued_itemtypes_count; # huh?
483 $issueqty_sth->execute("*"); # FIXME: Why have a WHERE clause at all with a hardcoded "*"?
485 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
487 # subtract how many of each this borrower has
488 $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };
490 ( $data->{'maxissueqty'} -
491 $issued_itemtypes_count->{ $data->{'description'} } );
493 # can't have a negative number of remaining
494 if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
495 $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
496 unless ( ( $data->{'maxissueqty'} < 1 )
497 || ( $data->{'itemtype'} eq "*" )
498 || ( $data->{'itemtype'} eq "CIRC" ) )
500 push @issued_itemtypes_count_loop, $data;
503 $issued_itemtypes_loop = \@issued_itemtypes_count_loop;
509 my $CGIselectborrower;
510 if ($borrowerslist) {
512 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
516 push @values, $_->{'borrowernumber'};
517 $labels{ $_->{'borrowernumber'} } =
518 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ... $_->{'address'} ";
520 $CGIselectborrower = CGI::scrolling_list(
521 -name => 'borrowernumber',
523 -id => 'borrowernumber',
533 my $flags = $borrower->{'flags'};
536 foreach $flag ( sort keys %$flags ) {
537 $template->param( flagged=> 1);
538 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
539 if ( $flags->{$flag}->{'noissues'} ) {
544 if ( $flag eq 'GNA' ) {
545 $template->param( gna => 'true' );
547 if ( $flag eq 'LOST' ) {
548 $template->param( lost => 'true' );
550 if ( $flag eq 'DBARRED' ) {
551 $template->param( dbarred => 'true' );
553 if ( $flag eq 'CHARGES' ) {
556 chargesmsg => $flags->{'CHARGES'}->{'message'},
557 chargesamount => $flags->{'CHARGES'}->{'amount'},
558 charges_is_blocker => 1
561 if ( $flag eq 'CREDITS' ) {
564 creditsmsg => $flags->{'CREDITS'}->{'message'}
569 if ( $flag eq 'CHARGES' ) {
573 chargesmsg => $flags->{'CHARGES'}->{'message'},
574 chargesamount => $flags->{'CHARGES'}->{'amount'},
577 if ( $flag eq 'CREDITS' ) {
580 creditsmsg => $flags->{'CREDITS'}->{'message'}
583 if ( $flag eq 'ODUES' ) {
587 oduesmsg => $flags->{'ODUES'}->{'message'}
590 my $items = $flags->{$flag}->{'itemlist'};
594 # foreach my $item (@$items) {
595 # my ($iteminformation) =
596 # getiteminformation( $item->{'itemnumber'}, 0 );
597 # push @itemswaiting, $iteminformation;
600 if ( $query->param('module') ne 'returns' ) {
601 $template->param( nonreturns => 'true' );
604 if ( $flag eq 'NOTES' ) {
608 notesmsg => $flags->{'NOTES'}->{'message'}
614 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
615 my @temp = split( /\$/, $amountold );
617 if ( $borrower->{'category_type'} eq 'C') {
618 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
619 my $cnt = scalar(@$catcodes);
620 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
621 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
624 my $CGIorganisations;
625 my $member_of_institution;
626 if ( C4::Context->preference("memberofinstitution") ) {
627 my $organisations = get_institutions();
630 foreach my $organisation ( keys %$organisations ) {
631 push @orgs, $organisation;
632 $org_labels{$organisation} =
633 $organisations->{$organisation}->{'surname'};
635 $member_of_institution = 1;
636 $CGIorganisations = CGI::popup_menu(
637 -id => 'organisations',
638 -name => 'organisations',
639 -labels => \%org_labels,
644 $amountold = $temp[1];
647 issued_itemtypes_count_loop => $issued_itemtypes_loop,
648 findborrower => $findborrower,
649 borrower => $borrower,
650 borrowernumber => $borrowernumber,
652 branchname => GetBranchName($borrower->{'branchcode'}),
654 printername => $printer,
655 firstname => $borrower->{'firstname'},
656 surname => $borrower->{'surname'},
657 dateexpiry => format_date($newexpiry),
658 expiry => format_date($borrower->{'dateexpiry'}),
659 categorycode => $borrower->{'categorycode'},
660 categoryname => $borrower->{description},
661 address => $borrower->{'address'},
662 address2 => $borrower->{'address2'},
663 email => $borrower->{'email'},
664 emailpro => $borrower->{'emailpro'},
665 borrowernotes => $borrower->{'borrowernotes'},
666 city => $borrower->{'city'},
667 zipcode => $borrower->{'zipcode'},
668 phone => $borrower->{'phone'} || $borrower->{'mobile'},
669 cardnumber => $borrower->{'cardnumber'},
670 amountold => $amountold,
672 stickyduedate => $stickyduedate,
674 CGIselectborrower => $CGIselectborrower,
675 todayissues => \@todaysissues,
676 previssues => \@previousissues,
677 inprocess => $inprocess,
678 memberofinstution => $member_of_institution,
679 CGIorganisations => $CGIorganisations,
680 is_child => ($borrower->{'category_type'} eq 'C'),
684 # set return date if stickyduedate
685 if ($stickyduedate) {
687 duedatespec => $duedatespec,
691 #if ($branchcookie) {
692 #$cookie=[$cookie, $branchcookie, $printercookie];
695 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
696 $template->param( picture => 1 ) if $picture;
700 debt_confirmed => $debt_confirmed,
701 SpecifyDueDate => C4::Context->preference("SpecifyDueDate"),
702 CircAutocompl => C4::Context->preference("CircAutocompl"),
703 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
704 dateformat => C4::Context->preference("dateformat"),
705 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
707 output_html_with_http_headers $query, $cookie, $template->output;