2 # Please use 8-character tabs for this file (indents are every 4 characters)
4 package C4::Circulation::Circ2;
8 #package to deal with circulation
9 #written 3/11/99 by olwen@katipo.co.nz
12 # Copyright 2000-2002 Katipo Communications
14 # This file is part of Koha.
16 # Koha is free software; you can redistribute it and/or modify it under the
17 # terms of the GNU General Public License as published by the Free Software
18 # Foundation; either version 2 of the License, or (at your option) any later
21 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
22 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
23 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License along with
26 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
27 # Suite 330, Boston, MA 02111-1307 USA
39 use C4::Calendar::Calendar;
43 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
45 # set the version for version checking
50 C4::Circulation::Circ2 - Koha circulation module
54 use C4::Circulation::Circ2;
58 The functions in this module deal with circulation, issues, and
59 returns, as well as general information about the library.
60 Also deals with stocktaking.
82 &listitemsforinventory
88 &get_current_return_date_of
96 # &getbranches &getprinters &getbranch &getprinter => moved to C4::Koha.pm
99 @issues = &itemissues($biblionumber, $biblio);
101 Looks up information about who has borrowed the bookZ<>(s) with the
104 C<$biblio> is ignored.
106 C<&itemissues> returns an array of references-to-hash. The keys
107 include the fields from the C<items> table in the Koha database.
108 Additional keys include:
114 If the item is currently on loan, this gives the due date.
116 If the item is not on loan, then this is either "Available" or
117 "Cancelled", if the item has been withdrawn.
121 If the item is currently on loan, this gives the card number of the
122 patron who currently has the item.
124 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
126 These give the timestamp for the last three times the item was
129 =item C<card0>, C<card1>, C<card2>
131 The card number of the last three patrons who borrowed this item.
133 =item C<borrower0>, C<borrower1>, C<borrower2>
135 The borrower number of the last three patrons who borrowed this item.
142 my ($dbh,$data, $itemnumber)=@_;
149 # Find out who currently has this item.
150 # FIXME - Wouldn't it be better to do this as a left join of
151 # some sort? Currently, this code assumes that if
152 # fetchrow_hashref() fails, then the book is on the shelf.
153 # fetchrow_hashref() can fail for any number of reasons (e.g.,
154 # database server crash), not just because no items match the
156 my $sth2 = $dbh->prepare("select * from issues,borrowers
158 and returndate is NULL
159 and issues.borrowernumber = borrowers.borrowernumber");
161 $sth2->execute($itemnumber);
162 if (my $data2 = $sth2->fetchrow_hashref) {
164 $data->{'date_due'}=$data2->{'date_due'};
165 $data->{'datelastborrowed'} = $data2->{'issue_date'};
166 $data->{'card'} = $data2->{'cardnumber'};
167 $data->{'borrower'} = $data2->{'borrowernumber'};
172 my $sth2 = $dbh->prepare("select * from reserveissue,borrowers
175 and reserveissue.borrowernumber = borrowers.borrowernumber");
177 $sth2->execute($itemnumber);
178 if (my $data2 = $sth2->fetchrow_hashref) {
180 $data->{'date_due'}=$data2->{'duetime'};
181 $data->{'datelastborrowed'} = $data2->{'restime'};
182 $data->{'card'} = $data2->{'cardnumber'};
183 $data->{'borrower'} = $data2->{'borrowernumber'};
188 # Find the last 2 people who borrowed this item.
189 $sth2 = $dbh->prepare("select * from issues, borrowers
191 and issues.borrowernumber = borrowers.borrowernumber
192 and returndate is not NULL
193 order by returndate desc,timestamp desc limit 2") ;
194 $sth2->execute($itemnumber) ;
196 while (my $data2 = $sth2->fetchrow_hashref) {
197 $data->{"timestamp$i2"} = $data2->{'timestamp'};
198 $data->{"card$i2"} = $data2->{'cardnumber'};
199 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
200 $data->{'datelastborrowed'} = $data2->{'issue_date'} unless $data->{'datelastborrowed'};
212 &itemseen($dbh,$itemnum)
213 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
214 C<$itemnum> is the item number
219 my ($dbh,$itemnumber) = @_;
220 my $sth=$dbh->prepare("select biblionumber from items where itemnumber=?");
221 $sth->execute($itemnumber);
222 my ($biblionumber)=$sth->fetchrow;
223 XMLmoditemonefield($dbh,$biblionumber,$itemnumber,'itemlost',"0",1);
225 my ($sec,$min,$hour,$mday,$mon,$year) = localtime();
228 my $timestamp = sprintf("%4d%02d%02d%02d%02d%02d.0",
229 $year,$mon,$mday,$hour,$min,$sec);
230 XMLmoditemonefield($dbh,$biblionumber,$itemnumber,'datelastseen', $timestamp);
232 sub itemseenbarcode {
233 my ($dbh,$barcode) = @_;
234 my $sth=$dbh->prepare("select biblionumber,itemnumber from items where barcode=$barcode");
236 my ($biblionumber,$itemnumber)=$sth->fetchrow;
237 XMLmoditemonefield($dbh,$biblionumber,$itemnumber,'itemlost',"0",1);
238 my ($sec,$min,$hour,$mday,$mon,$year) = localtime();
241 my $timestamp = sprintf("%4d%02d%02d%02d%02d%02d.0",$year,$mon,$mday,$hour,$min,$sec);
242 XMLmoditemonefield($dbh,$biblionumber,$itemnumber,'datelastseen', $timestamp);
245 sub listitemsforinventory {
246 my ($minlocation,$datelastseen,$offset,$size) = @_;
256 push @kohafields, "classification","datelastseen";
257 push @values,$minlocation,$datelastseen;
258 push @relations,"\@attr 5=1 \@attr 6=3 \@attr 4=1 ","\@attr 2=1 ";
259 push @and_or,"\@and";
261 ($count,$facets,@results)=ZEBRAsearch_kohafields(\@kohafields,\@values,\@relations,$sort,\@and_or,0,"",$offset,$size);
263 push @kohafields, "classification";
264 push @values,$minlocation;
265 push @relations,"\@attr 5=1 \@attr 6=3 \@attr 4=1 ";
268 ($count,$facets,@results)=ZEBRAsearch_kohafields(\@kohafields,\@values,\@relations,$sort,\@and_or,0,"",$offset,$size);
281 =head3 $str = &decode($chunk);
285 Decodes a segment of a string emitted by a CueCat barcode scanner and
294 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
297 my $seq = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
298 my @s = map { index($seq,$_); } split(//,$encoded);
313 my $n = (($s[0] << 6 | $s[1]) << 6 | $s[2]) << 6 | $s[3];
314 $r .=chr(($n >> 16) ^ 67) .
315 chr(($n >> 8 & 255) ^ 67) .
316 chr(($n & 255) ^ 67);
319 $r = substr($r,0,length($r)-$l);
323 =head2 getiteminformation
327 $item = &getiteminformation($env, $itemnumber, $barcode);
329 Looks up information about an item, given either its item number or
330 its barcode. If C<$itemnumber> is a nonzero value, it is used;
331 otherwise, C<$barcode> is used.
333 C<$env> is effectively ignored, but should be a reference-to-hash.
335 C<$item> is a reference-to-hash whose keys are fields from the biblio,
336 items, and biblioitems tables of the Koha database. It may also
337 contain the following keys:
343 The due date on this item, if it has been borrowed and not returned
344 yet. The date is in YYYY-MM-DD format.
352 True if the item may not be borrowed.
361 sub getiteminformation {
362 # returns a hash of item information together with biblio given either the itemnumber or the barcode
363 my ($env, $itemnumber, $barcode) = @_;
364 my $dbh=C4::Context->dbh;
365 my ($itemrecord)=XMLgetitem($dbh,$itemnumber,$barcode);
366 return undef unless $itemrecord; ## This is to prevent a system crash if barcode does not exist
367 my $itemhash=XML_xml2hash_onerecord($itemrecord);
368 my $iteminformation=XMLmarc2koha_onerecord($dbh,$itemhash,"holdings");
369 ##Now get full biblio details from MARC
370 if ($iteminformation) {
371 my ($record)=XMLgetbiblio($dbh,$iteminformation->{'biblionumber'});
372 my $recordhash=XML_xml2hash_onerecord($record);
373 my $biblio=XMLmarc2koha_onerecord($dbh,$recordhash,"biblios");
374 foreach my $field (keys %$biblio){
375 $iteminformation->{$field}=$biblio->{$field};
377 $iteminformation->{'date_due'}="" if $iteminformation->{'date_due'} eq "0000-00-00";
378 ($iteminformation->{'dewey'} == 0) && ($iteminformation->{'dewey'}='');
380 return($iteminformation);
387 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
389 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
391 C<$newbranch> is the code for the branch to which the item should be transferred.
393 C<$barcode> is the barcode of the item to be transferred.
395 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
396 Otherwise, if an item is reserved, the transfer fails.
398 Returns three values:
402 is true if the transfer was successful.
406 is a reference-to-hash which may have any of the following keys:
412 There is no item in the catalog with the given barcode. The value is C<$barcode>.
416 The item's home branch is permanent. This doesn't prevent the item from being transferred, though. The value is the code of the item's home branch.
418 C<DestinationEqualsHolding>
420 The item is already at the branch to which it is being transferred. The transfer is nonetheless considered to have failed. The value should be ignored.
424 The item was on loan, and C<&transferbook> automatically returned it before transferring it. The value is the borrower number of the patron who had the item.
428 The item was reserved. The value is a reference-to-hash whose keys are fields from the reserves table of the Koha database, and C<biblioitemnumber>. It also has the key C<ResFound>, whose value is either C<Waiting> or C<Reserved>.
432 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
442 ##This routine is reverted to origional state
443 ##This routine is used when a book physically arrives at a branch due to user returning it there
444 ## so record the fact that holdingbranch is changed.
446 # transfer book code....
447 my ($tbr, $barcode, $ignoreRs,$user) = @_;
450 my $dbh=C4::Context->dbh;
452 my $branches = GetBranches();
454 my $iteminformation = getiteminformation(\%env, 0, $barcode);
456 if (not $iteminformation) {
457 $messages->{'BadBarcode'} = $barcode;
460 # get branches of book...
461 my $hbr = $iteminformation->{'homebranch'};
462 my $fbr = $iteminformation->{'holdingbranch'};
464 if ($hbr && $branches->{$hbr}->{'PE'}) {
465 $messages->{'IsPermanent'} = $hbr;
467 # can't transfer book if is already there....
468 # FIXME - Why not? Shouldn't it trivially succeed?
470 $messages->{'DestinationEqualsHolding'} = 1;
473 # check if it is still issued to someone, return it...
474 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
475 if ($currentborrower) {
476 returnbook($barcode, $fbr);
477 $messages->{'WasReturned'} = $currentborrower;
480 # FIXME - Don't call &CheckReserves unless $ignoreRs is true.
481 # That'll save a database query.
482 my ($resfound, $resrec) = CheckReserves($iteminformation->{'itemnumber'});
483 if ($resfound and not $ignoreRs) {
484 $resrec->{'ResFound'} = $resfound;
485 $messages->{'ResFound'} = $resrec;
488 #actually do the transfer....
490 dotransfer($iteminformation->{'itemnumber'}, $fbr, $tbr,$user);
491 $messages->{'WasTransfered'} = 1;
493 return ($dotransfer, $messages, $iteminformation);
499 ## The book has arrived at this branch because it has been returned there
500 ## So we update the fact the book is in that branch not that we want to send the book to that branch
502 my ($itm, $fbr, $tbr,$user) = @_;
503 my $dbh = C4::Context->dbh;
505 #new entry in branchtransfers....
506 my $sth=$dbh->prepare("INSERT INTO branchtransfers (itemnumber, frombranch, datearrived, tobranch,comments) VALUES (?, ?, now(), ?,?)");
507 $sth->execute($itm, $fbr, $tbr,$user);
508 #update holdingbranch in items .....
509 &domarctransfer($dbh,$itm,$tbr);
510 ## Item seen taken out of this loop to optimize ZEBRA updates
511 # &itemseen($dbh,$itm);
516 my ($dbh,$itemnumber,$holdingbranch) = @_;
517 $itemnumber=~s /\'//g;
518 my $sth=$dbh->prepare("select biblionumber from items where itemnumber=$itemnumber");
520 my ($biblionumber)=$sth->fetchrow;
521 XMLmoditemonefield($dbh,$biblionumber,$itemnumber,'holdingbranch',$holdingbranch,1);
525 =head2 canbookbeissued
527 Check if a book can be issued.
529 my ($issuingimpossible,$needsconfirmation) = canbookbeissued($env,$borrower,$barcode,$year,$month,$day);
533 C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
535 C<$borrower> hash with borrower informations (from getpatroninformation)
537 C<$barcode> is the bar code of the book being issued.
539 C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
547 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
548 Possible values are :
552 sticky due date is invalid
556 borrower gone with no address
560 borrower declared it's card lost
566 =head3 UNKNOWN_BARCODE
580 item is restricted (set by ??)
584 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
585 Possible values are :
593 renewing, not issuing
595 =head3 ISSUED_TO_ANOTHER
597 issued to someone else.
601 reserved for someone else.
605 sticky due date is invalid
609 if the borrower borrows to much things
613 # check if a book can be issued.
614 # returns an array with errors if any
627 my $borrower = shift;
628 my $iteminformation = shift;
629 my $cat_borrower = $borrower->{'categorycode'};
630 my $branch_borrower = $borrower->{'branchcode'};
631 my $dbh = C4::Context->dbh;
632 my $sth = $dbh->prepare('select itemtype from biblio where biblionumber = ?');
633 $sth->execute($iteminformation->{'biblionumber'});
634 my $type = $sth->fetchrow;
635 $sth = $dbh->prepare('select * from issuingrules where categorycode = ? and itemtype = ? and branchcode = ?');
636 my $sth2 = $dbh->prepare("select COUNT(*) from issues i, items it, biblio b where i.borrowernumber = ? and i.returndate is null and i.itemnumber = it.itemnumber and b.biblionumber=it.biblionumber and b.itemtype like ?");
637 my $sth3 = $dbh->prepare('select COUNT(*) from issues where borrowernumber = ? and returndate is null');
640 # check the 3 parameters
641 #print "content-type: text/plain \n\n";
642 #print "$cat_borrower, $type, $branch_borrower";
643 $sth->execute($cat_borrower, $type, $branch_borrower);
644 my $result = $sth->fetchrow_hashref;
645 if (defined($result->{maxissueqty})) {
646 # print "content-type: text/plain \n\n";
647 #print "$cat_borrower, $type, $branch_borrower";
648 $sth2->execute($borrower->{'borrowernumber'}, $type);
649 my $alreadyissued = $sth2->fetchrow;
650 # print "***" . $alreadyissued;
651 #print "----". $result->{'maxissueqty'};
652 if ($result->{'maxissueqty'} <= $alreadyissued) {
653 return ("$type $alreadyissued / max:".($result->{'maxissueqty'}+0));
660 $sth->execute($cat_borrower, $type, "");
661 $result = $sth->fetchrow_hashref;
662 if (defined($result->{maxissueqty})) {
663 $sth2->execute($borrower->{'borrowernumber'}, $type);
664 my $alreadyissued = $sth2->fetchrow;
665 if ($result->{'maxissueqty'} <= $alreadyissued){
666 return ("$type $alreadyissued / max:".($result->{'maxissueqty'}+0));
672 # check for itemtype=*
673 $sth->execute($cat_borrower, "*", $branch_borrower);
674 $result = $sth->fetchrow_hashref;
675 if (defined($result->{maxissueqty})) {
676 $sth3->execute($borrower->{'borrowernumber'});
677 my ($alreadyissued) = $sth3->fetchrow;
678 if ($result->{'maxissueqty'} <= $alreadyissued){
679 # warn "HERE : $alreadyissued / ($result->{maxissueqty} for $borrower->{'borrowernumber'}";
680 return ("$type $alreadyissued / max:".($result->{'maxissueqty'}+0));
686 #check for borrowertype=*
687 $sth->execute("*", $type, $branch_borrower);
688 $result = $sth->fetchrow_hashref;
689 if (defined($result->{maxissueqty})) {
690 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
691 my $alreadyissued = $sth2->fetchrow;
692 if ($result->{'maxissueqty'} <= $alreadyissued){
693 return ("$type $alreadyissued / max:".($result->{'maxissueqty'}+0));
699 #check for borrowertype=*;itemtype=*
700 $sth->execute("*", "*", $branch_borrower);
701 $result = $sth->fetchrow_hashref;
702 if (defined($result->{maxissueqty})) {
703 $sth3->execute($borrower->{'borrowernumber'});
704 my $alreadyissued = $sth3->fetchrow;
705 if ($result->{'maxissueqty'} <= $alreadyissued){
706 return ("$type $alreadyissued / max:".($result->{'maxissueqty'}+0));
712 $sth->execute("*", $type, "");
713 $result = $sth->fetchrow_hashref;
714 if (defined($result->{maxissueqty}) && $result->{maxissueqty}>=0) {
715 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
716 my $alreadyissued = $sth2->fetchrow;
717 if ($result->{'maxissueqty'} <= $alreadyissued){
718 return ("$type $alreadyissued / max:".($result->{'maxissueqty'}+0));
724 $sth->execute($cat_borrower, "*", "");
725 $result = $sth->fetchrow_hashref;
726 if (defined($result->{maxissueqty})) {
727 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
728 my $alreadyissued = $sth2->fetchrow;
729 if ($result->{'maxissueqty'} <= $alreadyissued){
730 return ("$type $alreadyissued / max:".($result->{'maxissueqty'}+0));
736 $sth->execute("*", "*", "");
737 $result = $sth->fetchrow_hashref;
738 if (defined($result->{maxissueqty})) {
739 $sth3->execute($borrower->{'borrowernumber'});
740 my $alreadyissued = $sth3->fetchrow;
741 if ($result->{'maxissueqty'} <= $alreadyissued){
742 return ("$type $alreadyissued / max:".($result->{'maxissueqty'}+0));
753 sub canbookbeissued {
754 my ($env,$borrower,$barcode,$year,$month,$day,$inprocess) = @_;
755 my %needsconfirmation; # filled with problems that needs confirmations
756 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
757 my $iteminformation = getiteminformation($env, 0, $barcode);
758 my $dbh = C4::Context->dbh;
762 my ($duedate, $invalidduedate) = fixdate($year, $month, $day);
763 $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
768 if ($borrower->{flags}->{GNA}) {
769 $issuingimpossible{GNA} = 1;
771 if ($borrower->{flags}->{'LOST'}) {
772 $issuingimpossible{CARD_LOST} = 1;
774 if ($borrower->{flags}->{'DBARRED'}) {
775 $issuingimpossible{DEBARRED} = 1;
777 my $today=get_today();
778 if (DATE_diff($borrower->{expiry},$today)<0) {
779 $issuingimpossible{EXPIRED} = 1;
786 my $amount = checkaccount($env,$borrower->{'borrowernumber'}, $dbh,$duedate);
787 if(C4::Context->preference("IssuingInProcess")){
788 my $amountlimit = C4::Context->preference("noissuescharge");
789 if ($amount > $amountlimit && !$inprocess) {
790 $issuingimpossible{DEBT} = sprintf("%.2f",$amount);
791 } elsif ($amount <= $amountlimit && !$inprocess) {
792 $needsconfirmation{DEBT} = sprintf("%.2f",$amount);
796 $needsconfirmation{DEBT} = $amount;
802 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
804 my $toomany = TooMany($borrower, $iteminformation);
805 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
806 $issuingimpossible{TOO_MANY} = $toomany if $toomany;
810 unless ($iteminformation->{barcode}) {
811 $issuingimpossible{UNKNOWN_BARCODE} = 1;
813 if ($iteminformation->{'notforloan'} > 0) {
814 $issuingimpossible{NOT_FOR_LOAN} = 1;
816 if ($iteminformation->{'itemtype'} eq 'REF') {
817 $issuingimpossible{NOT_FOR_LOAN} = 1;
819 if ($iteminformation->{'wthdrawn'} == 1) {
820 $issuingimpossible{WTHDRAWN} = 1;
822 if ($iteminformation->{'restricted'} == 1) {
823 $issuingimpossible{RESTRICTED} = 1;
825 if ($iteminformation->{'shelf'} eq 'Res') {
826 $issuingimpossible{IN_RESERVE} = 1;
828 if (C4::Context->preference("IndependantBranches")){
829 my $userenv = C4::Context->userenv;
830 if (($userenv)&&($userenv->{flags} != 1)){
831 $issuingimpossible{NOTSAMEBRANCH} = 1 if ($iteminformation->{'holdingbranch'} ne $userenv->{branch} ) ;
836 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
838 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
839 if ($currentborrower eq $borrower->{'borrowernumber'}) {
840 # Already issued to current borrower. Ask whether the loan should
842 my ($renewstatus) = renewstatus($env, $borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
843 if ($renewstatus == 0) { # no more renewals allowed
844 $issuingimpossible{NO_MORE_RENEWALS} = 1;
846 if (C4::Context->preference("strictrenewals")){
847 ###if this is set do not allow automatic renewals
848 ##the new renew script will do same strict checks as issues and return error codes
849 $needsconfirmation{RENEW_ISSUE} = 1;
853 } elsif ($currentborrower) {
854 # issued to someone else
855 my $currborinfo = getpatroninformation(0,$currentborrower);
856 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
857 $needsconfirmation{ISSUED_TO_ANOTHER} = "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
859 # See if the item is on RESERVE
860 my ($restype, $res) = CheckReserves($iteminformation->{'itemnumber'});
862 my $resbor = $res->{'borrowernumber'};
863 if ($resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting") {
864 # The item is on reserve and waiting, but has been
865 # reserved by some other patron.
866 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
867 my $branches = GetBranches();
868 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
869 $needsconfirmation{RESERVE_WAITING} = "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
870 # CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
871 } elsif ($restype eq "Reserved") {
872 # The item is on reserve for someone else.
873 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
874 my $branches = GetBranches();
875 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
876 $needsconfirmation{RESERVED} = "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
879 if(C4::Context->preference("LibraryName") eq "Horowhenua Library Trust"){
880 if ($borrower->{'categorycode'} eq 'W'){
881 my %issuingimpossible;
882 return(\%issuingimpossible,\%needsconfirmation);
886 return(\%issuingimpossible,\%needsconfirmation);
891 Issue a book. Does no check, they are done in canbookbeissued. If we reach this sub, it means the user confirmed if needed.
893 &issuebook($env,$borrower,$barcode,$date)
897 C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
899 C<$borrower> hash with borrower informations (from getpatroninformation)
901 C<$barcode> is the bar code of the book being issued.
903 C<$date> contains the max date of return. calculated if empty.
908 # issuing book. We already have checked it can be issued, so, just issue it !
911 ### fix me STOP using koha hashes, change so that XML hash is used
912 my ($env,$borrower,$barcode,$date,$cancelreserve) = @_;
913 my $dbh = C4::Context->dbh;
914 my $itemrecord=XMLgetitemhash($dbh,"",$barcode);
915 my $iteminformation=XMLmarc2koha_onerecord($dbh,$itemrecord,"holdings");
916 $iteminformation->{'itemtype'}=MARCfind_itemtype($dbh,$iteminformation->{biblionumber});
919 # check if we just renew the issue.
921 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
922 if ($currentborrower eq $borrower->{'borrowernumber'}) {
923 my ($charge,$itemtype) = calc_charges($env, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'});
925 createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge);
926 $iteminformation->{'charge'} = $charge;
928 &UpdateStats($env,$env->{'branchcode'},'renew',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
929 if (C4::Context->preference("strictrenewals")){
930 $error=renewstatus($env, $borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
931 renewbook($env, $borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'}) if ($error>1);
933 renewbook($env, $borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
939 if ($currentborrower ne '') {
940 # This book is currently on loan, but not to the person
941 # who wants to borrow it now. mark it returned before issuing to the new borrower
942 returnbook($iteminformation->{'barcode'}, $env->{'branchcode'});
943 #warn "return : ".$borrower->{borrowernumber}." / I : ".$iteminformation->{'itemnumber'};
946 # See if the item is on reserve.
947 my ($restype, $res) = CheckReserves($iteminformation->{'itemnumber'});
948 #warn "$restype,$res";
950 my $resbor = $res->{'borrowernumber'};
951 if ($resbor eq $borrower->{'borrowernumber'}) {
952 # The item is on reserve to the current patron
954 # warn "FillReserve";
955 } elsif ($restype eq "Waiting") {
957 # The item is on reserve and waiting, but has been
958 # reserved by some other patron.
959 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
960 my $branches = GetBranches();
961 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
963 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
965 # set waiting reserve to first in reserve queue as book isn't waiting now
966 UpdateReserve(1, $res->{'biblionumber'}, $res->{'borrowernumber'}, $res->{'branchcode'});
968 } elsif ($restype eq "Reserved") {
970 # The item is on reserve for someone else.
971 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
972 my $branches = GetBranches();
973 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
974 if ($cancelreserve) {
975 # cancel reserves on this item
976 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
977 # also cancel reserve on biblio related to this item
978 # my $st_Fbiblio = $dbh->prepare("select biblionumber from items where itemnumber=?");
979 # $st_Fbiblio->execute($res->{'itemnumber'});
980 # my $biblionumber = $st_Fbiblio->fetchrow;
981 # CancelReserve($iteminformation->{'biblionumber'},0,$res->{'borrowernumber'});
982 # warn "CancelReserve $res->{'itemnumber'}, $res->{'borrowernumber'}";
984 my $tobrcd = ReserveWaiting($res->{'itemnumber'}, $res->{'borrowernumber'});
985 transferbook($tobrcd,$barcode, 1);
986 # warn "transferbook";
991 my $sth=$dbh->prepare("insert into issues (borrowernumber, itemnumber, date_due, branchcode,issue_date) values (?,?,?,?,NOW())");
992 my $loanlength = getLoanLength($borrower->{'categorycode'},$iteminformation->{'itemtype'},$borrower->{'branchcode'});
995 my @datearr = localtime();
996 $dateduef = (1900+$datearr[5])."-".($datearr[4]+1)."-". $datearr[3];
998 my $calendar = C4::Calendar::Calendar->new(branchcode => $borrower->{'branchcode'});
999 my ($yeardue, $monthdue, $daydue) = split /-/, $dateduef;
1000 ($daydue, $monthdue, $yeardue) = $calendar->addDate($daydue, $monthdue, $yeardue, $loanlength);
1001 $dateduef = "$yeardue-".sprintf ("%0.2d", $monthdue)."-". sprintf("%0.2d",$daydue);
1007 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
1008 if (C4::Context->preference('ReturnBeforeExpiry') && $dateduef gt $borrower->{expiry}) {
1009 $dateduef=$borrower->{expiry};
1011 $sth->execute($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'}, $dateduef, $env->{'branchcode'});
1013 $iteminformation->{'issues'}++;
1014 ##Record in MARC the new data ,date_due as due date,issue count and the borrowernumber
1015 $itemrecord=XML_writeline($itemrecord, "issues", $iteminformation->{'issues'},"holdings");
1016 $itemrecord=XML_writeline($itemrecord, "date_due", $dateduef,"holdings");
1017 $itemrecord=XML_writeline($itemrecord, "borrowernumber", $borrower->{'borrowernumber'},"holdings");
1018 $itemrecord=XML_writeline($itemrecord, "itemlost", "0","holdings");
1019 $itemrecord=XML_writeline($itemrecord, "onloan", "1","holdings");
1020 # find today's date as timestamp
1021 my ($sec,$min,$hour,$mday,$mon,$year) = localtime();
1024 my $timestamp = sprintf("%4d%02d%02d%02d%02d%02d.0",
1025 $year,$mon,$mday,$hour,$min,$sec);
1026 $itemrecord=XML_writeline($itemrecord, "datelastseen", $timestamp,"holdings");
1027 ##Now update the zebradb
1028 NEWmoditem($dbh,$itemrecord,$iteminformation->{'biblionumber'},$iteminformation->{'itemnumber'});
1029 # If it costs to borrow this book, charge it to the patron's account.
1030 my ($charge,$itemtype)=calc_charges($env, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'});
1032 createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge);
1033 $iteminformation->{'charge'}=$charge;
1035 # Record the fact that this book was issued in SQL
1036 &UpdateStats($env,$env->{'branchcode'},'issue',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
1041 =head2 getLoanLength
1043 Get loan length for an itemtype, a borrower type and a branch
1045 my $loanlength = &getLoanLength($borrowertype,$itemtype,branchcode)
1050 my ($borrowertype,$itemtype,$branchcode) = @_;
1051 my $dbh = C4::Context->dbh;
1052 my $sth = $dbh->prepare("select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=?");
1053 # try to find issuelength & return the 1st available.
1054 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1055 $sth->execute($borrowertype,$itemtype,$branchcode);
1056 my $loanlength = $sth->fetchrow_hashref;
1057 return $loanlength->{issuelength} if defined($loanlength);
1059 $sth->execute($borrowertype,$itemtype,"");
1060 $loanlength = $sth->fetchrow_hashref;
1061 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1063 $sth->execute($borrowertype,"*",$branchcode);
1064 $loanlength = $sth->fetchrow_hashref;
1065 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1067 $sth->execute("*",$itemtype,$branchcode);
1068 $loanlength = $sth->fetchrow_hashref;
1069 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1071 $sth->execute($borrowertype,"*","");
1072 $loanlength = $sth->fetchrow_hashref;
1073 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1075 $sth->execute("*","*",$branchcode);
1076 $loanlength = $sth->fetchrow_hashref;
1077 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1079 $sth->execute("*",$itemtype,"");
1080 $loanlength = $sth->fetchrow_hashref;
1081 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1083 $sth->execute("*","*","");
1084 $loanlength = $sth->fetchrow_hashref;
1085 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1087 # if no rule is set => 21 days (hardcoded)
1092 ($doreturn, $messages, $iteminformation, $borrower) =
1093 &returnbook($barcode, $branch);
1097 C<$barcode> is the bar code of the book being returned. C<$branch> is
1098 the code of the branch where the book is being returned.
1100 C<&returnbook> returns a list of four items:
1102 C<$doreturn> is true iff the return succeeded.
1104 C<$messages> is a reference-to-hash giving the reason for failure:
1110 No item with this barcode exists. The value is C<$barcode>.
1114 The book is not currently on loan. The value is C<$barcode>.
1116 =item C<IsPermanent>
1118 The book's home branch is a permanent collection. If you have borrowed
1119 this book, you are not allowed to return it. The value is the code for
1120 the book's home branch.
1124 This book has been withdrawn/cancelled. The value should be ignored.
1128 The item was reserved. The value is a reference-to-hash whose keys are
1129 fields from the reserves table of the Koha database, and
1130 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1131 either C<Waiting>, C<Reserved>, or 0.
1135 C<$borrower> is a reference-to-hash, giving information about the
1136 patron who last borrowed the book.
1140 # FIXME - This API is bogus. There's no need to return $borrower and
1141 # $iteminformation; the caller can ask about those separately, if it
1142 # cares (it'd be inefficient to make two database calls instead of
1143 # one, but &getpatroninformation and &getiteminformation can be
1144 # memoized if this is an issue).
1146 # The ($doreturn, $messages) tuple is redundant: if the return
1147 # succeeded, that's all the caller needs to know. So &returnbook can
1148 # return 1 and 0 on success and failure, and set
1149 # $C4::Circulation::Circ2::errmsg to indicate the error. Or it can
1150 # return undef for success, and an error message on error (though this
1151 # is more C-ish than Perl-ish).
1154 my ($barcode, $branch) = @_;
1157 my $dbh = C4::Context->dbh;
1159 die '$branch not defined' unless defined $branch; # just in case (bug 170)
1160 # get information on item
1161 my $itemrecord=XMLgetitemhash($dbh,"",$barcode);
1162 if (not $itemrecord) {
1163 $messages->{'BadBarcode'} = $barcode;
1165 return ($doreturn, $messages, undef, undef);
1167 my $iteminformation=XMLmarc2koha_onerecord($dbh,$itemrecord,"holdings");
1168 $iteminformation->{'itemtype'}=MARCfind_itemtype($dbh,$iteminformation->{biblionumber});
1171 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
1172 if ((not $currentborrower) && $doreturn) {
1173 $messages->{'NotIssued'} = $barcode;
1176 # check if the book is in a permanent collection....
1177 my $hbr = $iteminformation->{'homebranch'};
1178 my $branches = GetBranches();
1179 if ($branches->{$hbr}->{'PE'}) {
1180 $messages->{'IsPermanent'} = $hbr;
1182 # check that the book has been cancelled
1183 if ($iteminformation->{'wthdrawn'}) {
1184 $messages->{'wthdrawn'} = 1;
1187 # update issues, thereby returning book (should push this out into another subroutine
1188 my ($borrower) = getpatroninformation(\%env, $currentborrower, 0);
1190 my $sth = $dbh->prepare("update issues set returndate = now() where (itemnumber = ?) and (returndate is null)");
1191 $sth->execute( $iteminformation->{'itemnumber'});
1192 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1196 $itemrecord=XML_writeline($itemrecord, "date_due", "","holdings");
1197 $itemrecord=XML_writeline($itemrecord, "onloan", "0","holdings");
1198 $itemrecord=XML_writeline($itemrecord, "borrowernumber", "","holdings");
1200 my ($transfered, $mess, $item) = transferbook($branch, $barcode, 1);
1201 my ($sec,$min,$hour,$mday,$mon,$year) = localtime();
1204 my $timestamp = sprintf("%4d%02d%02d%02d%02d%02d.0",
1205 $year,$mon,$mday,$hour,$min,$sec);
1206 $itemrecord=XML_writeline($itemrecord, "datelastseen", $timestamp,"holdings");
1209 ($borrower) = getpatroninformation(\%env, $currentborrower, 0);
1210 # transfer book to the current branch
1213 $messages->{'WasTransfered'} = 1; # FIXME is the "= 1" right?
1215 # fix up the accounts.....
1216 if ($iteminformation->{'itemlost'}) {
1217 fixaccountforlostandreturned($iteminformation, $borrower);
1218 $messages->{'WasLost'} = 1; # FIXME is the "= 1" right?
1219 $itemrecord=XML_writeline($itemrecord, "itemlost", "","holdings");
1221 ####WARNING-- FIXME#########
1222 ### The following new script is commented out
1223 ## I did not understand what it is supposed to do.
1224 ## If a book is returned at one branch it is automatically recorded being in that branch by
1225 ## transferbook script. This scrip tries to find out whether it was sent thre
1226 ## Well whether sent or not it is physically there and transferbook records this fact in MARCrecord as well
1227 ## If this script is trying to do something else it should be uncommented and also add support for updating MARC record --TG
1228 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1229 # check if we have a transfer for this document
1230 # my $checktransfer = checktransferts($iteminformation->{'itemnumber'});
1231 # if we have a return, we update the line of transfers with the datearrived
1232 # if ($checktransfer){
1233 # my $sth = $dbh->prepare("update branchtransfers set datearrived = now() where itemnumber= ? AND datearrived IS NULL");
1234 # $sth->execute($iteminformation->{'itemnumber'});
1236 # now we check if there is a reservation with the validate of transfer if we have one, we can set it with the status 'W'
1237 # my $updateWaiting = SetWaitingStatus($iteminformation->{'itemnumber'});
1239 # if we don't have a transfer on run, we check if the document is not in his homebranch and there is not a reservation, we transfer this one to his home branch directly if system preference Automaticreturn is turn on .
1241 # my $checkreserves = CheckReserves($iteminformation->{'itemnumber'});
1242 # if (($iteminformation->{'homebranch'} ne $iteminformation->{'holdingbranch'}) and (not $checkreserves) and (C4::Context->preference("AutomaticItemReturn") == 1)){
1243 # my $automatictransfer = dotransfer($iteminformation->{'itemnumber'},$iteminformation->{'holdingbranch'},$iteminformation->{'homebranch'});
1244 # $messages->{'WasTransfered'} = 1;
1247 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1248 # fix up the overdues in accounts...
1249 fixoverduesonreturn($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
1250 $itemrecord=XML_writeline($itemrecord, "itemoverdue", "","holdings");
1251 # find reserves.....
1252 my ($resfound, $resrec) = CheckReserves($iteminformation->{'itemnumber'});
1254 # my $tobrcd = ReserveWaiting($resrec->{'itemnumber'}, $resrec->{'borrowernumber'});
1255 $resrec->{'ResFound'} = $resfound;
1256 $messages->{'ResFound'} = $resrec;
1258 ##Now update the zebradb
1259 NEWmoditem($dbh,$itemrecord,$iteminformation->{'biblionumber'},$iteminformation->{'itemnumber'});
1261 # Record the fact that this book was returned.
1262 UpdateStats(\%env, $branch ,'return','0','',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
1263 return ($doreturn, $messages, $iteminformation, $borrower);
1266 =head2 fixaccountforlostandreturned
1268 &fixaccountforlostandreturned($iteminfo,$borrower);
1270 Calculates the charge for a book lost and returned (Not exported & used only once)
1272 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1274 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1278 sub fixaccountforlostandreturned {
1279 my ($iteminfo, $borrower) = @_;
1281 my $dbh = C4::Context->dbh;
1282 my $itm = $iteminfo->{'itemnumber'};
1283 # check for charge made for lost book
1284 my $sth = $dbh->prepare("select * from accountlines where (itemnumber = ?) and (accounttype='L' or accounttype='Rep') order by date desc");
1285 $sth->execute($itm);
1286 if (my $data = $sth->fetchrow_hashref) {
1287 # writeoff this amount
1289 my $amount = $data->{'amount'};
1290 my $acctno = $data->{'accountno'};
1292 if ($data->{'amountoutstanding'} == $amount) {
1293 $offset = $data->{'amount'};
1296 $offset = $amount - $data->{'amountoutstanding'};
1297 $amountleft = $data->{'amountoutstanding'} - $amount;
1299 my $usth = $dbh->prepare("update accountlines set accounttype = 'LR',amountoutstanding='0'
1300 where (borrowernumber = ?)
1301 and (itemnumber = ?) and (accountno = ?) ");
1302 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1304 #check if any credit is left if so writeoff other accounts
1305 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1306 if ($amountleft < 0){
1309 if ($amountleft > 0){
1310 my $msth = $dbh->prepare("select * from accountlines where (borrowernumber = ?)
1311 and (amountoutstanding >0) order by date");
1312 $msth->execute($data->{'borrowernumber'});
1313 # offset transactions
1316 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1317 if ($accdata->{'amountoutstanding'} < $amountleft) {
1319 $amountleft -= $accdata->{'amountoutstanding'};
1321 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1324 my $thisacct = $accdata->{'accountno'};
1325 my $usth = $dbh->prepare("update accountlines set amountoutstanding= ?
1326 where (borrowernumber = ?)
1327 and (accountno=?)");
1328 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1330 $usth = $dbh->prepare("insert into accountoffsets
1331 (borrowernumber, accountno, offsetaccount, offsetamount)
1334 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1339 if ($amountleft > 0){
1342 my $desc="Book Returned ".$iteminfo->{'barcode'};
1343 $usth = $dbh->prepare("insert into accountlines
1344 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1345 values (?,?,now(),?,?,'CR',?)");
1346 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1348 $usth = $dbh->prepare("insert into accountoffsets
1349 (borrowernumber, accountno, offsetaccount, offsetamount)
1351 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1353 # $usth = $dbh->prepare("update items set paidfor='' where itemnumber=?");
1354 # $usth->execute($itm);
1361 =head2 fixoverdueonreturn
1363 &fixoverdueonreturn($brn,$itm);
1367 C<$brn> borrowernumber
1373 sub fixoverduesonreturn {
1374 my ($brn, $itm) = @_;
1375 my $dbh = C4::Context->dbh;
1376 # check for overdue fine
1377 my $sth = $dbh->prepare("select * from accountlines where (borrowernumber = ?) and (itemnumber = ?) and (accounttype='FU' or accounttype='O')");
1378 $sth->execute($brn,$itm);
1379 # alter fine to show that the book has been returned
1380 if (my $data = $sth->fetchrow_hashref) {
1381 my $usth=$dbh->prepare("update accountlines set accounttype='F' where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)");
1382 $usth->execute($brn,$itm,$data->{'accountno'});
1391 # NOTE!: If you change this function, be sure to update the POD for
1392 # &getpatroninformation.
1394 # $flags = &patronflags($env, $patron, $dbh);
1397 # {message} Message showing patron's credit or debt
1398 # {noissues} Set if patron owes >$5.00
1399 # {GNA} Set if patron gone w/o address
1400 # {message} "Borrower has no valid address"
1402 # {LOST} Set if patron's card reported lost
1403 # {message} Message to this effect
1405 # {DBARRED} Set is patron is debarred
1406 # {message} Message to this effect
1408 # {NOTES} Set if patron has notes
1409 # {message} Notes about patron
1410 # {ODUES} Set if patron has overdue books
1412 # {itemlist} ref-to-array: list of overdue books
1413 # {itemlisttext} Text list of overdue items
1414 # {WAITING} Set if there are items available that the
1416 # {message} Message to this effect
1417 # {itemlist} ref-to-array: list of available items
1419 # Original subroutine for Circ2.pm
1421 my ($env, $patroninformation, $dbh) = @_;
1422 my $amount = C4::Accounts2::checkaccount($env, $patroninformation->{'borrowernumber'}, $dbh);
1425 my $noissuescharge = C4::Context->preference("noissuescharge");
1426 $flaginfo{'message'}= sprintf "Patron owes \$%.02f", $amount;
1427 if ($amount > $noissuescharge) {
1428 $flaginfo{'noissues'} = 1;
1430 $flags{'CHARGES'} = \%flaginfo;
1431 } elsif ($amount < 0){
1433 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
1434 $flags{'CHARGES'} = \%flaginfo;
1436 if ($patroninformation->{'gonenoaddress'} == 1) {
1438 $flaginfo{'message'} = 'Borrower has no valid address.';
1439 $flaginfo{'noissues'} = 1;
1440 $flags{'GNA'} = \%flaginfo;
1442 if ($patroninformation->{'lost'} == 1) {
1444 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
1445 $flaginfo{'noissues'} = 1;
1446 $flags{'LOST'} = \%flaginfo;
1448 if ($patroninformation->{'debarred'} == 1) {
1450 $flaginfo{'message'} = 'Borrower is Debarred.';
1451 $flaginfo{'noissues'} = 1;
1452 $flags{'DBARRED'} = \%flaginfo;
1454 if ($patroninformation->{'borrowernotes'}) {
1456 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
1457 $flags{'NOTES'} = \%flaginfo;
1459 my ($odues, $itemsoverdue)
1460 = checkoverdues($env, $patroninformation->{'borrowernumber'}, $dbh);
1463 $flaginfo{'message'} = "Yes";
1464 $flaginfo{'itemlist'} = $itemsoverdue;
1465 foreach (sort {$a->{'date_due'} cmp $b->{'date_due'}} @$itemsoverdue) {
1466 $flaginfo{'itemlisttext'}.="$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
1468 $flags{'ODUES'} = \%flaginfo;
1470 my ($nowaiting, $itemswaiting)
1471 = CheckWaiting($patroninformation->{'borrowernumber'});
1472 if ($nowaiting > 0) {
1474 $flaginfo{'message'} = "Reserved items available";
1475 $flaginfo{'itemlist'} = $itemswaiting;
1476 $flags{'WAITING'} = \%flaginfo;
1484 # From Main.pm, modified to return a list of overdueitems, in addition to a count
1485 #checks whether a borrower has overdue items
1486 my ($env, $bornum, $dbh)=@_;
1487 my $today=get_today();
1490 my $sth = $dbh->prepare("SELECT issues.* , i.biblionumber as biblionumber,b.* FROM issues, items i,biblio b
1491 WHERE i.itemnumber=issues.itemnumber
1492 AND i.biblionumber=b.biblionumber
1493 AND issues.borrowernumber = ?
1494 AND issues.returndate is NULL
1495 AND issues.date_due < ?");
1496 $sth->execute($bornum,$today);
1497 while (my $data = $sth->fetchrow_hashref) {
1499 push (@overdueitems, $data);
1503 return ($count, \@overdueitems);
1507 sub currentborrower {
1508 # Original subroutine for Circ2.pm
1509 my ($itemnumber) = @_;
1510 my $dbh = C4::Context->dbh;
1512 my $sth=$dbh->prepare("select borrowers.borrowernumber from
1513 issues,borrowers where issues.itemnumber=? and
1514 issues.borrowernumber=borrowers.borrowernumber and issues.returndate is
1516 $sth->execute($itemnumber);
1517 my ($borrower) = $sth->fetchrow;
1521 # FIXME - Not exported, but used in 'updateitem.pl' anyway.
1522 sub checkreserve_to_delete {
1523 # Check for reserves for biblio
1524 my ($env,$dbh,$itemnum)=@_;
1526 my $sth = $dbh->prepare("select * from reserves,items
1527 where (items.itemnumber = ?)
1528 and (reserves.cancellationdate is NULL)
1529 and (items.biblionumber = reserves.biblionumber)
1530 and ((reserves.found = 'W')
1531 or (reserves.found is null))
1532 order by priority");
1533 $sth->execute($itemnum);
1535 my $data=$sth->fetchrow_hashref;
1536 while ($data && $resbor eq '') {
1538 my $const = $data->{'constrainttype'};
1539 if ($const eq "a") {
1540 $resbor = $data->{'borrowernumber'};
1543 my $csth = $dbh->prepare("select * from reserveconstraints,items
1544 where (borrowernumber=?)
1546 and reserveconstraints.biblionumber=?
1547 and (items.itemnumber=? )");
1548 $csth->execute($data->{'borrowernumber'},$data->{'biblionumber'},$data->{'reservedate'},$itemnum);
1549 if (my $cdata=$csth->fetchrow_hashref) {$found = 1;}
1550 if ($const eq 'o') {
1551 if ($found eq 1) {$resbor = $data->{'borrowernumber'};}
1553 if ($found eq 0) {$resbor = $data->{'borrowernumber'};}
1557 $data=$sth->fetchrow_hashref;
1560 return ($resbor,$resrec);
1563 =head2 currentissues
1565 $issues = ¤tissues($env, $borrower);
1567 Returns a list of books currently on loan to a patron.
1569 If C<$env-E<gt>{todaysissues}> is set and true, C<¤tissues> only
1570 returns information about books issued today. If
1571 C<$env-E<gt>{nottodaysissues}> is set and true, C<¤tissues> only
1572 returns information about books issued before today. If both are
1573 specified, C<$env-E<gt>{todaysissues}> is ignored. If neither is
1574 specified, C<¤tissues> returns all of the patron's issues.
1576 C<$borrower->{borrowernumber}> is the borrower number of the patron
1577 whose issues we want to list.
1579 C<¤tissues> returns a PHP-style array: C<$issues> is a
1580 reference-to-hash whose keys are integers in the range 1...I<n>, where
1581 I<n> is the number of items on issue (either today or before today).
1582 C<$issues-E<gt>{I<n>}> is a reference-to-hash whose keys are all of
1583 the fields of the biblio, biblioitems, items, and issues fields of the
1584 Koha database for that particular item.
1590 # New subroutine for Circ2.pm
1591 my ($env, $borrower) = @_;
1592 my $dbh = C4::Context->dbh;
1595 my $borrowernumber = $borrower->{'borrowernumber'};
1598 # Figure out whether to get the books issued today, or earlier.
1599 # FIXME - $env->{todaysissues} and $env->{nottodaysissues} can
1600 # both be specified, but are mutually-exclusive. This is bogus.
1601 # Make this a flag. Or better yet, return everything in (reverse)
1602 # chronological order and let the caller figure out which books
1603 # were issued today.
1604 my $today=get_today();
1605 if ($env->{'todaysissues'}) {
1607 $crit=" and issues.timestamp like '$today%' ";
1609 if ($env->{'nottodaysissues'}) {
1611 $crit=" and !(issues.timestamp like '$today%') ";
1614 # FIXME - Does the caller really need every single field from all
1616 my $sth=$dbh->prepare("select * from issues,items where
1617 borrowernumber=? and issues.itemnumber=items.itemnumber and
1619 $crit order by issues.date_due");
1620 $sth->execute($borrowernumber);
1621 while (my $data = $sth->fetchrow_hashref) {
1624 if ($data->{'date_due'} lt $today) {
1625 $data->{'overdue'}=1;
1627 my $itemnumber=$data->{'itemnumber'};
1628 # FIXME - Consecutive integers as hash keys? You have GOT to
1629 # be kidding me! Use an array, fercrissakes!
1630 $currentissues{$counter}=$data;
1634 return(\%currentissues);
1639 $issues = &getissues($borrowernumber);
1641 Returns the set of books currently on loan to a patron.
1643 C<$borrowernumber> is the patron's borrower number.
1645 C<&getissues> returns a PHP-style array: C<$issues> is a
1646 reference-to-hash whose keys are integers in the range 0..I<n>-1,
1647 where I<n> is the number of books the patron currently has on loan.
1649 The values of C<$issues> are references-to-hash whose keys are
1650 selected fields from the issues, items, biblio, and biblioitems tables
1651 of the Koha database.
1656 my ($borrower) = @_;
1657 my $dbh = C4::Context->dbh;
1658 my $borrowernumber = $borrower->{'borrowernumber'};
1662 my $todaysdate=get_today();
1664 my $select = "SELECT *
1665 FROM issues,items,biblio
1666 WHERE issues.borrowernumber = ?
1667 AND issues.itemnumber = items.itemnumber
1668 AND items.biblionumber = biblio.biblionumber
1669 AND issues.returndate IS NULL
1670 ORDER BY issues.date_due";
1672 my $sth=$dbh->prepare($select);
1673 $sth->execute($borrowernumber);
1674 while (my $data = $sth->fetchrow_hashref) {
1675 if ($data->{'date_due'} lt $todaysdate) {
1676 $data->{'overdue'} = 1;
1678 $currentissues{$counter} = $data;
1683 return(\%currentissues);
1688 # check for reserves waiting
1689 my ($env,$dbh,$bornum)=@_;
1691 my $sth = $dbh->prepare("select * from reserves where (borrowernumber = ?) and (reserves.found='W') and cancellationdate is NULL");
1692 $sth->execute($bornum);
1694 if (my $data=$sth->fetchrow_hashref) {
1695 $itemswaiting[$cnt] =$data;
1699 return ($cnt,\@itemswaiting);
1704 $ok = &renewstatus($env, $dbh, $borrowernumber, $itemnumber);
1706 Find out whether a borrowed item may be renewed.
1710 C<$dbh> is a DBI handle to the Koha database.
1712 C<$borrowernumber> is the borrower number of the patron who currently
1713 has the item on loan.
1715 C<$itemnumber> is the number of the item to renew.
1717 C<$renewstatus> returns a true value iff the item may be renewed. The
1718 item must currently be on loan to the specified borrower; renewals
1719 must be allowed for the item's type; and the borrower must not have
1720 already renewed the loan.
1725 # check renewal status
1726 ##If system preference "strictrenewals" is used This script will try to return $renewok=2 or $renewok=3 as error messages
1728 my ($env,$bornum,$itemnumber)=@_;
1729 my $dbh=C4::Context->dbh;
1734 # Look in the issues table for this item, lent to this borrower,
1735 # and not yet returned.
1736 my $borrower=C4::Members::getpatroninformation($dbh,$bornum,undef);
1738 # FIXME - I think this function could be redone to use only one SQL call.
1739 my $sth1 = $dbh->prepare("select * from issues,items,biblio
1740 where (borrowernumber = ?)
1741 and (issues.itemnumber = ?)
1742 and items.biblionumber=biblio.biblionumber
1743 and returndate is null
1744 and items.itemnumber=issues.itemnumber");
1745 $sth1->execute($bornum,$itemnumber);
1746 my $data1 = $sth1->fetchrow_hashref;
1748 # Found a matching item
1749 if (C4::Context->preference("LibraryName") eq "NEU Grand Library"){
1750 ##privileged get renewal whatever the case may be
1751 if ($borrower->{'categorycode'} eq 'P'){
1756 # See if this item may be renewed.
1757 my $sth2 = $dbh->prepare("select renewalsallowed from itemtypes where itemtypes.itemtype=?");
1758 $sth2->execute($data1->{itemtype});
1759 if (my $data2=$sth2->fetchrow_hashref) {
1760 $renews = $data2->{'renewalsallowed'};
1762 if ($renews > $data1->{'renewals'}) {
1765 if (C4::Context->preference("strictrenewals")){
1770 ($resfound, $resrec) = CheckReserves($itemnumber);
1772 if (C4::Context->preference("strictrenewals")){
1778 ($resfound, $resrec) = CheckReserves($itemnumber);
1780 if (C4::Context->preference("strictrenewals")){
1786 if (C4::Context->preference("strictrenewals")){
1787 ### A new system pref "allowRenewalsBefore" prevents the renewal before a set amount of days left before expiry
1788 ## Try to find whether book can be renewed at this date
1791 my $allowRenewalsBefore = C4::Context->preference("allowRenewalsBefore");
1792 my $today=get_today();
1794 # Find the issues record for this book###
1795 my $sth=$dbh->prepare("select SUBDATE(date_due, $allowRenewalsBefore) from issues where itemnumber=? and returndate is null");
1796 $sth->execute($itemnumber);
1797 my $startdate=$sth->fetchrow;
1800 my $difference = DATE_diff($today,$startdate);
1801 if ($difference < 0) {
1813 &renewbook($env, $borrowernumber, $itemnumber, $datedue);
1817 C<$env-E<gt>{branchcode}> is the code of the branch where the
1818 renewal is taking place.
1820 C<$env-E<gt>{usercode}> is the value to log in C<statistics.usercode>
1821 in the Koha database.
1823 C<$borrowernumber> is the borrower number of the patron who currently
1826 C<$itemnumber> is the number of the item to renew.
1828 C<$datedue> can be used to set the due date. If C<$datedue> is the
1829 empty string, C<&renewbook> will calculate the due date automatically
1830 from the book's item type. If you wish to set the due date manually,
1831 C<$datedue> should be in the form YYYY-MM-DD.
1836 my ($env,$bornum,$itemnumber,$datedue)=@_;
1837 # mark book as renewed
1840 my $dbh=C4::Context->dbh;
1842 my $iteminformation = getiteminformation($env, $itemnumber,0);
1846 if ($datedue eq "" ) {
1848 my $borrower = C4::Members::getpatroninformation($env,$bornum,0);
1849 $loanlength = getLoanLength($borrower->{'categorycode'},$iteminformation->{'itemtype'},$borrower->{'branchcode'});
1851 my $datedue=get_today();
1852 my $calendar = C4::Calendar::Calendar->new(branchcode => $borrower->{'branchcode'});
1853 my ($yeardue, $monthdue, $daydue) = split /-/, $datedue;
1854 ($daydue, $monthdue, $yeardue) = $calendar->addDate($daydue, $monthdue, $yeardue, $loanlength);
1855 $datedue = "$yeardue-".sprintf ("%0.2d", $monthdue)."-". sprintf("%0.2d",$daydue);
1857 # Update the issues record to have the new due date, and a new count
1858 # of how many times it has been renewed.
1860 $sth=$dbh->prepare("update issues set date_due = ?, renewals = renewals+1
1861 where borrowernumber=? and itemnumber=? and returndate is null");
1862 $sth->execute($datedue,$bornum,$itemnumber);
1865 ## Update items and marc record with new date -T.G
1866 &XMLmoditemonefield($dbh,$iteminformation->{'biblionumber'},$iteminformation->{'itemnumber'},'date_due',$datedue);
1869 UpdateStats($env,$env->{'branchcode'},'renew','','',$itemnumber,$iteminformation->{'itemtype'},$bornum);
1871 # Charge a new rental fee, if applicable?
1872 my ($charge,$type)=calc_charges($env, $itemnumber, $bornum);
1874 my $accountno=getnextacctno($env,$bornum,$dbh);
1875 $sth=$dbh->prepare("Insert into accountlines (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding,itemnumber)
1876 values (?,?,now(),?,?,?,?,?)");
1877 $sth->execute($bornum,$accountno,$charge,"Renewal of Rental Item $iteminformation->{'title'} $iteminformation->{'barcode'}",'Rent',$charge,$itemnumber);
1880 }# end of rental charge
1882 return format_date($datedue);
1893 ($charge, $item_type) = &calc_charges($env, $itemnumber, $borrowernumber);
1895 Calculate how much it would cost for a given patron to borrow a given
1896 item, including any applicable discounts.
1900 C<$itemnumber> is the item number of item the patron wishes to borrow.
1902 C<$borrowernumber> is the patron's borrower number.
1904 C<&calc_charges> returns two values: C<$charge> is the rental charge,
1905 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1911 # calculate charges due
1912 my ($env, $itemnumber, $bornum)=@_;
1914 my $dbh = C4::Context->dbh;
1916 my $sth= $dbh->prepare("select itemtype from biblio,items where items.biblionumber=biblio.biblionumber and itemnumber=?");
1917 $sth->execute($itemnumber);
1918 my $itemtype=$sth->fetchrow;
1921 my $sth1= $dbh->prepare("select rentalcharge from itemtypes where itemtypes.itemtype=?");
1922 $sth1->execute($itemtype);
1924 $charge = $sth1->fetchrow;
1925 my $q2 = "select rentaldiscount from issuingrules,borrowers
1926 where (borrowers.borrowernumber = ?)
1927 and (borrowers.categorycode = issuingrules.categorycode)
1928 and (issuingrules.itemtype = ?)";
1929 my $sth2=$dbh->prepare($q2);
1930 $sth2->execute($bornum,$itemtype);
1931 if (my $data2=$sth2->fetchrow_hashref) {
1932 my $discount = $data2->{'rentaldiscount'};
1933 if ($discount eq 'NULL') {
1936 $charge = ($charge *(100 - $discount)) / 100;
1937 # warn "discount is $discount";
1942 return ($charge,$itemtype);
1949 my ($env,$dbh,$itemnumber,$bornum,$charge) = @_;
1950 my $nextaccntno = getnextacctno($env,$bornum,$dbh);
1951 my $sth = $dbh->prepare(<<EOT);
1952 INSERT INTO accountlines
1953 (borrowernumber, itemnumber, accountno,
1954 date, amount, description, accounttype,
1957 now(), ?, 'Rental', 'Rent',
1960 $sth->execute($bornum, $itemnumber, $nextaccntno, $charge, $charge);
1969 ($status, $record) = &find_reserves($itemnumber);
1971 Looks up an item in the reserves.
1973 C<$itemnumber> is the itemnumber to look up.
1975 C<$status> is true iff the search was successful.
1977 C<$record> is a reference-to-hash describing the reserve. Its keys are
1978 the fields from the reserves table of the Koha database.
1982 # FIXME - This API is bogus: just return the record, or undef if none
1986 my ($itemnumber) = @_;
1987 my $dbh = C4::Context->dbh;
1988 my ($itemdata) = getiteminformation("", $itemnumber,0);
1989 my $sth = $dbh->prepare("select * from reserves where ((found = 'W') or (found is null)) and biblionumber = ? and cancellationdate is NULL order by priority, reservedate");
1990 $sth->execute($itemdata->{'biblionumber'});
1995 # FIXME - I'm not really sure what's going on here, but since we
1996 # only want one result, wouldn't it be possible (and far more
1997 # efficient) to do something clever in SQL that only returns one
1999 while ($resrec = $sth->fetchrow_hashref) {
2001 if ($resrec->{'found'} eq "W") {
2002 if ($resrec->{'itemnumber'} eq $itemnumber) {
2006 # FIXME - Use 'elsif' to avoid unnecessary indentation.
2007 if ($resrec->{'constrainttype'} eq "a") {
2010 my $consth = $dbh->prepare("select * from reserveconstraints where borrowernumber = ? and reservedate = ? and biblionumber = ? ");
2011 $consth->execute($resrec->{'borrowernumber'},$resrec->{'reservedate'},$resrec->{'biblionumber'});
2012 if (my $conrec = $consth->fetchrow_hashref) {
2013 if ($resrec->{'constrainttype'} eq "o") {
2022 my $updsth = $dbh->prepare("update reserves set found = 'W', itemnumber = ? where borrowernumber = ? and reservedate = ? and biblionumber = ?");
2023 $updsth->execute($itemnumber,$resrec->{'borrowernumber'},$resrec->{'reservedate'},$resrec->{'biblionumber'});
2029 return ($resfound,$lastrec);
2033 my ($year, $month, $day) = @_;
2036 if (($year eq 0) && ($month eq 0) && ($year eq 0)) {
2037 # $env{'datedue'}='';
2039 if (($year eq 0) || ($month eq 0) || ($year eq 0)) {
2042 if (($day>30) && (($month==4) || ($month==6) || ($month==9) || ($month==11))) {
2043 $invalidduedate = 1;
2044 } elsif (($day > 29) && ($month == 2)) {
2046 } elsif (($month == 2) && ($day > 28) && (($year%4) && ((!($year%100) || ($year%400))))) {
2049 $date="$year-$month-$day";
2053 return ($date, $invalidduedate);
2056 sub get_current_return_date_of {
2057 my (@itemnumbers) = @_;
2063 WHERE itemnumber IN ('.join(',', @itemnumbers).') AND returndate IS NULL
2065 return get_infos_of($query, 'itemnumber', 'date_due');
2068 sub get_transfert_infos {
2069 my ($itemnumber) = @_;
2071 my $dbh = C4::Context->dbh;
2077 FROM branchtransfers
2078 WHERE itemnumber = ?
2079 AND datearrived IS NULL
2081 my $sth = $dbh->prepare($query);
2082 $sth->execute($itemnumber);
2084 my @row = $sth->fetchrow_array();
2092 sub DeleteTransfer {
2093 my($itemnumber) = @_;
2094 my $dbh = C4::Context->dbh;
2095 my $sth=$dbh->prepare("DELETE FROM branchtransfers
2097 AND datearrived is null ");
2098 $sth->execute($itemnumber);
2102 sub GetTransfersFromBib {
2103 my($frombranch,$tobranch) = @_;
2104 my $dbh = C4::Context->dbh;
2105 my $sth=$dbh->prepare("SELECT itemnumber,datesent,frombranch FROM
2109 AND datearrived is null ");
2110 $sth->execute($frombranch,$tobranch);
2113 while (my $data=$sth->fetchrow_hashref){
2114 $gettransfers[$i]=$data;
2118 return(@gettransfers);
2121 sub GetReservesToBranch {
2122 my($frombranch,$default) = @_;
2123 my $dbh = C4::Context->dbh;
2124 my $sth=$dbh->prepare("SELECT borrowernumber,reservedate,itemnumber,timestamp FROM
2126 where priority='0' AND cancellationdate is null
2129 AND found is null ");
2130 $sth->execute($frombranch,$default);
2133 while (my $data=$sth->fetchrow_hashref){
2134 $transreserv[$i]=$data;
2138 return(@transreserv);
2141 sub GetReservesForBranch {
2142 my($frombranch) = @_;
2143 my $dbh = C4::Context->dbh;
2144 my $sth=$dbh->prepare("SELECT borrowernumber,reservedate,itemnumber,waitingdate FROM
2146 where priority='0' AND cancellationdate is null
2148 AND branchcode=? order by reservedate");
2149 $sth->execute($frombranch);
2152 while (my $data=$sth->fetchrow_hashref){
2153 $transreserv[$i]=$data;
2157 return(@transreserv);
2160 sub checktransferts{
2161 my($itemnumber) = @_;
2162 my $dbh = C4::Context->dbh;
2163 my $sth=$dbh->prepare("SELECT datesent,frombranch,tobranch FROM branchtransfers
2164 WHERE itemnumber = ? AND datearrived IS NULL");
2165 $sth->execute($itemnumber);
2166 my @tranferts = $sth->fetchrow_array;
2169 return (@tranferts);
2180 Koha Developement team <info@koha.org>