2 # Please use 8-character tabs for this file (indents are every 4 characters)
4 package C4::Circulation::Circ2;
8 #package to deal with Returns
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
41 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
43 # set the version for version checking
48 C4::Circulation::Circ2 - Koha circulation module
52 use C4::Circulation::Circ2;
56 The functions in this module deal with circulation, issues, and
57 returns, as well as general information about the library.
58 Also deals with stocktaking.
81 &listitemsforinventory
84 get_current_return_date_of
93 # &getbranches &getprinters &getbranch &getprinter => moved to C4::Koha.pm
98 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
99 C<$itemnum> is the item number
105 my $dbh = C4::Context->dbh;
106 my $sth = $dbh->prepare("update items set itemlost=0, datelastseen = now() where items.itemnumber = ?");
107 $sth->execute($itemnum);
114 Mark item as borrowed. Is called when an item is issued.
115 C<$itemnum> is the item number
121 my $dbh = C4::Context->dbh;
122 my $sth = $dbh->prepare("update items set itemlost=0, datelastborrowed = now() where items.itemnumber = ?");
123 $sth->execute($itemnum);
127 sub listitemsforinventory {
128 my ($minlocation,$maxlocation,$datelastseen,$offset,$size) = @_;
129 my $dbh = C4::Context->dbh;
130 my $sth = $dbh->prepare("select itemnumber,barcode,itemcallnumber,title,author from items,biblio where items.biblionumber=biblio.biblionumber and itemcallnumber>= ? and itemcallnumber <=? and (datelastseen< ? or datelastseen is null) order by itemcallnumber,title");
131 $sth->execute($minlocation,$maxlocation,$datelastseen);
133 while (my $row = $sth->fetchrow_hashref) {
134 $offset-- if ($offset);
135 if ((!$offset) && $size) {
143 =head2 getpatroninformation
145 ($borrower, $flags) = &getpatroninformation($env, $borrowernumber, $cardnumber);
147 Looks up a patron and returns information about him or her. If
148 C<$borrowernumber> is true (nonzero), C<&getpatroninformation> looks
149 up the borrower by number; otherwise, it looks up the borrower by card
152 C<$env> is effectively ignored, but should be a reference-to-hash.
154 C<$borrower> is a reference-to-hash whose keys are the fields of the
155 borrowers table in the Koha database. In addition,
156 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
157 about the patron. Its keys act as flags :
159 if $borrower->{flags}->{LOST} {
160 # Patron's card was reported lost
163 Each flag has a C<message> key, giving a human-readable explanation of
164 the flag. If the state of a flag means that the patron should not be
165 allowed to borrow any more books, then it will have a C<noissues> key
168 The possible flags are:
174 Shows the patron's credit or debt, if any.
182 (Gone, no address.) Set if the patron has left without giving a
191 Set if the patron's card has been reported as lost.
199 Set if the patron has been debarred.
207 Any additional notes about the patron.
215 Set if the patron has overdue items. This flag has several keys:
217 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
218 overdue items. Its elements are references-to-hash, each describing an
219 overdue item. The keys are selected fields from the issues, biblio,
220 biblioitems, and items tables of the Koha database.
222 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
223 the overdue items, one per line.
231 Set if any items that the patron has reserved are available.
233 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
234 available items. Each element is a reference-to-hash whose keys are
235 fields from the reserves table of the Koha database.
244 sub getpatroninformation {
246 my ($env, $borrowernumber,$cardnumber) = @_;
247 my $dbh = C4::Context->dbh;
250 if ($borrowernumber) {
251 $sth = $dbh->prepare("select * from borrowers where borrowernumber=?");
252 $sth->execute($borrowernumber);
253 } elsif ($cardnumber) {
254 $sth = $dbh->prepare("select * from borrowers where cardnumber=?");
255 $sth->execute($cardnumber);
257 $env->{'apierror'} = "invalid borrower information passed to getpatroninformation subroutine";
260 my $borrower = $sth->fetchrow_hashref;
261 my $amount = checkaccount($env, $borrowernumber, $dbh);
262 $borrower->{'amountoutstanding'} = $amount;
263 my $flags = patronflags($env, $borrower, $dbh);
266 $sth=$dbh->prepare("select bit,flag from userflags");
268 while (my ($bit, $flag) = $sth->fetchrow) {
269 if ($borrower->{'flags'} && $borrower->{'flags'} & 2**$bit) {
270 $accessflagshash->{$flag}=1;
274 $borrower->{'flags'}=$flags;
275 $borrower->{'authflags'} = $accessflagshash;
276 return ($borrower); #, $flags, $accessflagshash);
283 =head3 $str = &decode($chunk);
287 Decodes a segment of a string emitted by a CueCat barcode scanner and
296 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
299 my $seq = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
300 my @s = map { index($seq,$_); } split(//,$encoded);
315 my $n = (($s[0] << 6 | $s[1]) << 6 | $s[2]) << 6 | $s[3];
316 $r .=chr(($n >> 16) ^ 67) .
317 chr(($n >> 8 & 255) ^ 67) .
318 chr(($n & 255) ^ 67);
321 $r = substr($r,0,length($r)-$l);
325 =head2 getiteminformation
329 $item = &getiteminformation($env, $itemnumber, $barcode);
331 Looks up information about an item, given either its item number or
332 its barcode. If C<$itemnumber> is a nonzero value, it is used;
333 otherwise, C<$barcode> is used.
335 C<$env> is effectively ignored, but should be a reference-to-hash.
337 C<$item> is a reference-to-hash whose keys are fields from the biblio,
338 items, and biblioitems tables of the Koha database. It may also
339 contain the following keys:
345 The due date on this item, if it has been borrowed and not returned
346 yet. The date is in YYYY-MM-DD format.
354 True if the item may not be borrowed.
363 sub getiteminformation {
364 # returns a hash of item information given either the itemnumber or the barcode
365 my ($env, $itemnumber, $barcode) = @_;
366 my $dbh = C4::Context->dbh;
369 $sth=$dbh->prepare("select * from biblio,items,biblioitems where items.itemnumber=? and biblio.biblionumber=items.biblionumber and biblioitems.biblioitemnumber = items.biblioitemnumber");
370 $sth->execute($itemnumber);
372 $sth=$dbh->prepare("select * from biblio,items,biblioitems where items.barcode=? and biblio.biblionumber=items.biblionumber and biblioitems.biblioitemnumber = items.biblioitemnumber");
373 $sth->execute($barcode);
375 $env->{'apierror'}="getiteminformation() subroutine must be called with either an itemnumber or a barcode";
379 my $iteminformation=$sth->fetchrow_hashref;
381 if ($iteminformation) {
382 $sth=$dbh->prepare("select date_due from issues where itemnumber=? and isnull(returndate)");
383 $sth->execute($iteminformation->{'itemnumber'});
384 my ($date_due) = $sth->fetchrow;
385 $iteminformation->{'date_due'}=$date_due;
387 ($iteminformation->{'dewey'} == 0) && ($iteminformation->{'dewey'}='');
388 $sth=$dbh->prepare("select * from itemtypes where itemtype=?");
389 $sth->execute($iteminformation->{'itemtype'});
390 my $itemtype=$sth->fetchrow_hashref;
391 # if specific item notforloan, don't use itemtype notforloan field.
392 # otherwise, use itemtype notforloan value to see if item can be issued.
393 $iteminformation->{'notforloan'}=$itemtype->{'notforloan'} unless $iteminformation->{'notforloan'};
396 return($iteminformation);
403 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
405 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
407 C<$newbranch> is the code for the branch to which the item should be transferred.
409 C<$barcode> is the barcode of the item to be transferred.
411 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
412 Otherwise, if an item is reserved, the transfer fails.
414 Returns three values:
418 is true if the transfer was successful.
422 is a reference-to-hash which may have any of the following keys:
428 There is no item in the catalog with the given barcode. The value is C<$barcode>.
432 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.
434 C<DestinationEqualsHolding>
436 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.
440 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.
444 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>.
448 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
459 # FIXME - This function tries to do too much, and its API is clumsy.
460 # If it didn't also return books, it could be used to change the home
461 # branch of a book while the book is on loan.
463 # Is there any point in returning the item information? The caller can
464 # look that up elsewhere if ve cares.
466 # This leaves the ($dotransfer, $messages) tuple. This seems clumsy.
467 # If the transfer succeeds, that's all the caller should need to know.
468 # Thus, this function could simply return 1 or 0 to indicate success
469 # or failure, and set $C4::Circulation::Circ2::errmsg in case of
470 # failure. Or this function could return undef if successful, and an
471 # error message in case of failure (this would feel more like C than
474 # transfer book code....
475 my ($tbr, $barcode, $ignoreRs) = @_;
479 my $branches = getbranches();
480 my $iteminformation = getiteminformation(\%env, 0, $barcode);
482 if (not $iteminformation) {
483 $messages->{'BadBarcode'} = $barcode;
486 # get branches of book...
487 my $hbr = $iteminformation->{'homebranch'};
488 my $fbr = $iteminformation->{'holdingbranch'};
490 if ($hbr && $branches->{$hbr}->{'PE'}) {
491 $messages->{'IsPermanent'} = $hbr;
493 # can't transfer book if is already there....
494 # FIXME - Why not? Shouldn't it trivially succeed?
496 $messages->{'DestinationEqualsHolding'} = 1;
499 # check if it is still issued to someone, return it...
500 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
501 if ($currentborrower) {
502 returnbook($barcode, $fbr);
503 $messages->{'WasReturned'} = $currentborrower;
506 # FIXME - Don't call &CheckReserves unless $ignoreRs is true.
507 # That'll save a database query.
508 my ($resfound, $resrec) = CheckReserves($iteminformation->{'itemnumber'});
509 if ($resfound and not $ignoreRs) {
510 $resrec->{'ResFound'} = $resfound;
511 # $messages->{'ResFound'} = $resrec;
516 dotransfer($iteminformation->{'itemnumber'}, $fbr, $tbr);
517 $messages->{'WasTransfered'} = 1;
519 return ($dotransfer, $messages, $iteminformation);
523 # FIXME - This is only used in &transferbook. Why bother making it a
526 my ($itm, $fbr, $tbr) = @_;
527 my $dbh = C4::Context->dbh;
528 $itm = $dbh->quote($itm);
529 $fbr = $dbh->quote($fbr);
530 $tbr = $dbh->quote($tbr);
531 #new entry in branchtransfers....
532 $dbh->do("INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
533 VALUES ($itm, $fbr, now(), $tbr)");
534 #update holdingbranch in items .....
535 $dbh->do("UPDATE items set holdingbranch = $tbr WHERE items.itemnumber = $itm");
537 &domarctransfer($dbh,$itm);
541 ##New sub to dotransfer in marc tables as well. Not exported -TG 10/04/2006
544 my ($dbh,$itemnumber) = @_;
545 $itemnumber=~s /\'//g; ##itemnumber seems to come with quotes-TG
546 my $sth=$dbh->prepare("select biblionumber,holdingbranch from items where itemnumber=$itemnumber");
548 while (my ($biblionumber,$holdingbranch)=$sth->fetchrow ){
549 &MARCmoditemonefield($dbh,$biblionumber,$itemnumber,'items.holdingbranch',$holdingbranch,0);
554 =head2 canbookbeissued
556 Check if a book can be issued.
558 my ($issuingimpossible,$needsconfirmation) = canbookbeissued($env,$borrower,$barcode,$year,$month,$day);
562 C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
564 C<$borrower> hash with borrower informations (from getpatroninformation)
566 C<$barcode> is the bar code of the book being issued.
568 C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
576 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
577 Possible values are :
581 sticky due date is invalid
585 borrower gone with no address
589 borrower declared it's card lost
595 =head3 UNKNOWN_BARCODE
609 item is restricted (set by ??)
613 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
614 Possible values are :
622 renewing, not issuing
624 =head3 ISSUED_TO_ANOTHER
626 issued to someone else.
630 reserved for someone else.
634 sticky due date is invalid
638 if the borrower borrows to much things
642 # check if a book can be issued.
643 # returns an array with errors if any
646 my $borrower = shift;
647 my $iteminformation = shift;
648 my $cat_borrower = $borrower->{'categorycode'};
649 my $branch_borrower = $borrower->{'branchcode'};
650 my $dbh = C4::Context->dbh;
653 my $sth = $dbh->prepare('select itemtype from biblioitems where biblionumber = ?');
654 $sth->execute($iteminformation->{'biblionumber'});
655 my $type = $sth->fetchrow;
656 $sth = $dbh->prepare('select * from issuingrules where categorycode = ? and itemtype = ? and branchcode = ?');
657 # my $sth2 = $dbh->prepare("select COUNT(*) from issues i, biblioitems s where i.borrowernumber = ? and i.returndate is null and i.itemnumber = s.biblioitemnumber and s.itemtype like ?");
658 my $sth2 = $dbh->prepare("select COUNT(*) from issues i, biblioitems s1, items s2 where i.borrowernumber = ? and i.returndate is null and i.itemnumber = s2.itemnumber and s1.itemtype like ? and s1.biblioitemnumber = s2.biblioitemnumber");
659 my $sth3 = $dbh->prepare('select COUNT(*) from issues where borrowernumber = ? and returndate is null');
661 # check the 3 parameters
662 $sth->execute($cat_borrower, $type, $branch_borrower);
663 my $result = $sth->fetchrow_hashref;
664 # warn "==>".$result->{maxissueqty};
666 # Currently, using defined($result) ie on an entire hash reports whether memory
667 # for that aggregate has ever been allocated. As $result is used all over the place
668 # it would rarely return as undefined.
669 if (defined($result->{maxissueqty})) {
670 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
671 my $alreadyissued = $sth2->fetchrow;
672 if ($result->{'maxissueqty'} <= $alreadyissued){
673 return ("a $alreadyissued / ".($result->{maxissueqty}+0));
679 $sth->execute($cat_borrower, $type, "");
680 $result = $sth->fetchrow_hashref;
681 if (defined($result->{maxissueqty})) {
682 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
683 my $alreadyissued = $sth2->fetchrow;
684 if ($result->{'maxissueqty'} <= $alreadyissued){
685 return ("b $alreadyissued / ".($result->{maxissueqty}+0));
690 # check for itemtype=*
691 $sth->execute($cat_borrower, "*", $branch_borrower);
692 $result = $sth->fetchrow_hashref;
693 if (defined($result->{maxissueqty})) {
694 $sth3->execute($borrower->{'borrowernumber'});
695 my ($alreadyissued) = $sth3->fetchrow;
696 if ($result->{'maxissueqty'} <= $alreadyissued){
697 # warn "HERE : $alreadyissued / ($result->{maxissueqty} for $borrower->{'borrowernumber'}";
698 return ("c $alreadyissued / ".($result->{maxissueqty}+0));
703 # check for borrowertype=*
704 $sth->execute("*", $type, $branch_borrower);
705 $result = $sth->fetchrow_hashref;
706 if (defined($result->{maxissueqty})) {
707 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
708 my $alreadyissued = $sth2->fetchrow;
709 if ($result->{'maxissueqty'} <= $alreadyissued){
710 return ("d $alreadyissued / ".($result->{maxissueqty}+0));
716 $sth->execute("*", "*", $branch_borrower);
717 $result = $sth->fetchrow_hashref;
718 if (defined($result->{maxissueqty})) {
719 $sth3->execute($borrower->{'borrowernumber'});
720 my $alreadyissued = $sth3->fetchrow;
721 if ($result->{'maxissueqty'} <= $alreadyissued){
722 return ("e $alreadyissued / ".($result->{maxissueqty}+0));
728 $sth->execute("*", $type, "");
729 $result = $sth->fetchrow_hashref;
730 if (defined($result->{maxissueqty}) && $result->{maxissueqty}>=0) {
731 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
732 my $alreadyissued = $sth2->fetchrow;
733 if ($result->{'maxissueqty'} <= $alreadyissued){
734 return ("f $alreadyissued / ".($result->{maxissueqty}+0));
740 $sth->execute($cat_borrower, "*", "");
741 $result = $sth->fetchrow_hashref;
742 if (defined($result->{maxissueqty})) {
743 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
744 my $alreadyissued = $sth2->fetchrow;
745 if ($result->{'maxissueqty'} <= $alreadyissued){
746 return ("g $alreadyissued / ".($result->{maxissueqty}+0));
752 $sth->execute("*", "*", "");
753 $result = $sth->fetchrow_hashref;
754 if (defined($result->{maxissueqty})) {
755 $sth3->execute($borrower->{'borrowernumber'});
756 my $alreadyissued = $sth3->fetchrow;
757 if ($result->{'maxissueqty'} <= $alreadyissued){
758 return ("h $alreadyissued / ".($result->{maxissueqty}+0));
767 sub canbookbeissued {
768 my ($env,$borrower,$barcode,$year,$month,$day,$inprocess) = @_;
769 my %needsconfirmation; # filled with problems that needs confirmations
770 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
771 my $iteminformation = getiteminformation($env, 0, $barcode);
772 my $dbh = C4::Context->dbh;
776 my ($duedate, $invalidduedate) = fixdate($year, $month, $day);
777 $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
782 if ($borrower->{flags}->{GNA}) {
783 $issuingimpossible{GNA} = 1;
785 if ($borrower->{flags}->{'LOST'}) {
786 $issuingimpossible{CARD_LOST} = 1;
788 if ($borrower->{flags}->{'DBARRED'}) {
789 $issuingimpossible{DEBARRED} = 1;
791 if (&Date_Cmp(&ParseDate($borrower->{dateexpiry}),&ParseDate("today"))<0) {
792 $issuingimpossible{EXPIRED} = 1;
799 my $amount = checkaccount($env,$borrower->{'borrowernumber'}, $dbh,$duedate);
800 if(C4::Context->preference("IssuingInProcess")){
801 my $amountlimit = C4::Context->preference("noissuescharge");
802 if ($amount > $amountlimit && !$inprocess) {
803 $issuingimpossible{DEBT} = sprintf("%.2f",$amount);
804 } elsif ($amount <= $amountlimit && !$inprocess) {
805 $needsconfirmation{DEBT} = sprintf("%.2f",$amount);
809 $needsconfirmation{DEBT} = $amount;
814 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
816 my $toomany = TooMany($borrower, $iteminformation);
817 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
822 unless ($iteminformation->{barcode}) {
823 $issuingimpossible{UNKNOWN_BARCODE} = 1;
825 if ($iteminformation->{'notforloan'} && $iteminformation->{'notforloan'} > 0) {
826 $issuingimpossible{NOT_FOR_LOAN} = 1;
828 if ($iteminformation->{'itemtype'} &&$iteminformation->{'itemtype'} eq 'REF') {
829 $issuingimpossible{NOT_FOR_LOAN} = 1;
831 if ($iteminformation->{'wthdrawn'} && $iteminformation->{'wthdrawn'} == 1) {
832 $issuingimpossible{WTHDRAWN} = 1;
834 if ($iteminformation->{'restricted'} && $iteminformation->{'restricted'} == 1) {
835 $issuingimpossible{RESTRICTED} = 1;
841 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
843 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
844 if ($currentborrower && $currentborrower eq $borrower->{'borrowernumber'}) {
845 # Already issued to current borrower. Ask whether the loan should
847 my ($renewstatus) = renewstatus($env, $borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
848 if ($renewstatus == 0) { # no more renewals allowed
849 $issuingimpossible{NO_MORE_RENEWALS} = 1;
851 # $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'}); Doesn't belong in a checking subroutine.
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);
884 return(\%issuingimpossible,\%needsconfirmation);
887 return(\%issuingimpossible,\%needsconfirmation);
893 Issue a book. Does no check, they are done in canbookbeissued. If we reach this sub, it means the user confirmed if needed.
895 &issuebook($env,$borrower,$barcode,$date)
899 C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
901 C<$borrower> hash with borrower informations (from getpatroninformation)
903 C<$barcode> is the bar code of the book being issued.
905 C<$date> contains the max date of return. calculated if empty.
910 # issuing book. We already have checked it can be issued, so, just issue it !
913 my ($env,$borrower,$barcode,$date,$cancelreserve) = @_;
914 my $dbh = C4::Context->dbh;
915 # my ($borrower, $flags) = &getpatroninformation($env, $borrowernumber, 0);
916 my $iteminformation = getiteminformation($env, 0, $barcode);
917 # warn "B : ".$borrower->{borrowernumber}." / I : ".$iteminformation->{'itemnumber'};
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 renewbook($env, $borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
934 if ($currentborrower ne '') {
935 # This book is currently on loan, but not to the person
936 # who wants to borrow it now. mark it returned before issuing to the new borrower
937 returnbook($iteminformation->{'barcode'}, $env->{'branchcode'});
939 # See if the item is on reserve.
940 my ($restype, $res) = CheckReserves($iteminformation->{'itemnumber'});
942 my $resbor = $res->{'borrowernumber'};
943 if ($resbor eq $borrower->{'borrowernumber'}) {
944 # The item is on reserve to the current patron
947 } elsif ($restype eq "Waiting") {
949 # The item is on reserve and waiting, but has been
950 # reserved by some other patron.
951 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
952 my $branches = getbranches();
953 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
955 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
957 # set waiting reserve to first in reserve queue as book isn't waiting now
958 UpdateReserve(1, $res->{'biblionumber'}, $res->{'borrowernumber'}, $res->{'branchcode'});
960 } elsif ($restype eq "Reserved") {
962 # The item is on reserve for someone else.
963 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
964 my $branches = getbranches();
965 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
966 if ($cancelreserve) {
967 # cancel reserves on this item
968 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
969 # also cancel reserve on biblio related to this item
970 #my $st_Fbiblio = $dbh->prepare("select biblionumber from items where itemnumber=?");
971 #$st_Fbiblio->execute($res->{'itemnumber'});
972 #my $biblionumber = $st_Fbiblio->fetchrow;
973 #CancelReserve($biblionumber,0,$res->{'borrowernumber'});
974 #warn "CancelReserve $res->{'itemnumber'}, $res->{'borrowernumber'}";
976 # my $tobrcd = ReserveWaiting($res->{'itemnumber'}, $res->{'borrowernumber'});
977 # transferbook($tobrcd,$barcode, 1);
978 # warn "transferbook";
982 # Record in the database the fact that the book was issued.
983 my $sth=$dbh->prepare("insert into issues (borrowernumber, itemnumber, date_due, branchcode) values (?,?,?,?)");
984 my $loanlength = getLoanLength($borrower->{'categorycode'},$iteminformation->{'itemtype'},$borrower->{'branchcode'});
985 my $datedue=time+($loanlength)*86400;
986 my @datearr = localtime($datedue);
987 my $dateduef = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
991 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
992 if (C4::Context->preference('ReturnBeforeExpiry') && $dateduef gt $borrower->{expiry}) {
993 $dateduef=$borrower->{expiry};
995 $sth->execute($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'}, $dateduef, $env->{'branchcode'});
997 $iteminformation->{'issues'}++;
998 $sth=$dbh->prepare("update items set issues=?, holdingbranch=? where itemnumber=?");
999 $sth->execute($iteminformation->{'issues'},C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1001 &itemseen($iteminformation->{'itemnumber'});
1002 itemborrowed($iteminformation->{'itemnumber'});
1003 # If it costs to borrow this book, charge it to the patron's account.
1004 my ($charge,$itemtype)=calc_charges($env, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'});
1006 createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge);
1007 $iteminformation->{'charge'}=$charge;
1009 # Record the fact that this book was issued.
1010 &UpdateStats($env,$env->{'branchcode'},'issue',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
1014 =head2 getLoanLength
1016 Get loan length for an itemtype, a borrower type and a branch
1018 my $loanlength = &getLoanLength($borrowertype,$itemtype,branchcode)
1023 my ($borrowertype,$itemtype,$branchcode) = @_;
1024 my $dbh = C4::Context->dbh;
1025 my $sth = $dbh->prepare("select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=?");
1026 # try to find issuelength & return the 1st available.
1027 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1028 $sth->execute($borrowertype,$itemtype,$branchcode);
1029 my $loanlength = $sth->fetchrow_hashref;
1030 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1032 $sth->execute($borrowertype,$itemtype,"");
1033 $loanlength = $sth->fetchrow_hashref;
1034 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1036 $sth->execute($borrowertype,"*",$branchcode);
1037 $loanlength = $sth->fetchrow_hashref;
1038 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1040 $sth->execute("*",$itemtype,$branchcode);
1041 $loanlength = $sth->fetchrow_hashref;
1042 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1044 $sth->execute($borrowertype,"*","");
1045 $loanlength = $sth->fetchrow_hashref;
1046 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1048 $sth->execute("*","*",$branchcode);
1049 $loanlength = $sth->fetchrow_hashref;
1050 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1052 $sth->execute("*",$itemtype,"");
1053 $loanlength = $sth->fetchrow_hashref;
1054 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1056 $sth->execute("*","*","");
1057 $loanlength = $sth->fetchrow_hashref;
1058 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1060 # if no rule is set => 21 days (hardcoded)
1065 ($doreturn, $messages, $iteminformation, $borrower) =
1066 &returnbook($barcode, $branch);
1070 C<$barcode> is the bar code of the book being returned. C<$branch> is
1071 the code of the branch where the book is being returned.
1073 C<&returnbook> returns a list of four items:
1075 C<$doreturn> is true iff the return succeeded.
1077 C<$messages> is a reference-to-hash giving the reason for failure:
1083 No item with this barcode exists. The value is C<$barcode>.
1087 The book is not currently on loan. The value is C<$barcode>.
1089 =item C<IsPermanent>
1091 The book's home branch is a permanent collection. If you have borrowed
1092 this book, you are not allowed to return it. The value is the code for
1093 the book's home branch.
1097 This book has been withdrawn/cancelled. The value should be ignored.
1101 The item was reserved. The value is a reference-to-hash whose keys are
1102 fields from the reserves table of the Koha database, and
1103 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1104 either C<Waiting>, C<Reserved>, or 0.
1108 C<$borrower> is a reference-to-hash, giving information about the
1109 patron who last borrowed the book.
1113 # FIXME - This API is bogus. There's no need to return $borrower and
1114 # $iteminformation; the caller can ask about those separately, if it
1115 # cares (it'd be inefficient to make two database calls instead of
1116 # one, but &getpatroninformation and &getiteminformation can be
1117 # memoized if this is an issue).
1119 # The ($doreturn, $messages) tuple is redundant: if the return
1120 # succeeded, that's all the caller needs to know. So &returnbook can
1121 # return 1 and 0 on success and failure, and set
1122 # $C4::Circulation::Circ2::errmsg to indicate the error. Or it can
1123 # return undef for success, and an error message on error (though this
1124 # is more C-ish than Perl-ish).
1127 my ($barcode, $branch) = @_;
1130 my $dbh = C4::Context->dbh;
1132 die '$branch not defined' unless defined $branch; # just in case (bug 170)
1133 # get information on item
1134 my ($iteminformation) = getiteminformation(\%env, 0, $barcode);
1135 if (not $iteminformation) {
1136 $messages->{'BadBarcode'} = $barcode;
1140 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
1141 if ((not $currentborrower) && $doreturn) {
1142 $messages->{'NotIssued'} = $barcode;
1145 # check if the book is in a permanent collection....
1146 my $hbr = $iteminformation->{'homebranch'};
1147 my $branches = getbranches();
1148 if ($hbr && $branches->{$hbr}->{'PE'}) {
1149 $messages->{'IsPermanent'} = $hbr;
1151 # check that the book has been cancelled
1152 if ($iteminformation->{'wthdrawn'}) {
1153 $messages->{'wthdrawn'} = 1;
1156 # new op dev : if the book returned in an other branch update the holding branch
1158 # update issues, thereby returning book (should push this out into another subroutine
1159 my ($borrower) = getpatroninformation(\%env, $currentborrower, 0);
1161 my $sth = $dbh->prepare("update issues set returndate = now() where (borrowernumber = ?) and (itemnumber = ?) and (returndate is null)");
1162 $sth->execute($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
1164 # FIXME the holdingbranch is updated if the document is returned in an other location .
1165 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'}){
1166 my $sth_upd_location = $dbh->prepare("UPDATE items SET holdingbranch=? WHERE itemnumber=?");
1167 $sth_upd_location->execute(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1168 $sth_upd_location->finish;
1169 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1172 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1174 itemseen($iteminformation->{'itemnumber'});
1175 ($borrower) = getpatroninformation(\%env, $currentborrower, 0);
1176 # transfer book to the current branch
1178 # FIXME function transfered still always used ????
1179 # my ($transfered, $mess, $item) = transferbook($branch, $barcode, 1);
1180 # if ($transfered) {
1181 # $messages->{'WasTransfered'} = 1; # FIXME is the "= 1" right?
1184 # fix up the accounts.....
1185 if ($iteminformation->{'itemlost'}) {
1186 fixaccountforlostandreturned($iteminformation, $borrower);
1187 $messages->{'WasLost'} = 1; # FIXME is the "= 1" right?
1189 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1190 # check if we have a transfer for this document
1191 my $checktransfer = checktransferts($iteminformation->{'itemnumber'});
1192 # if we have a return, we update the line of transfers with the datearrived
1193 if ($checktransfer){
1194 my $sth = $dbh->prepare("update branchtransfers set datearrived = now() where itemnumber= ? AND datearrived IS NULL");
1195 $sth->execute($iteminformation->{'itemnumber'});
1197 # 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'
1198 my $updateWaiting = SetWaitingStatus($iteminformation->{'itemnumber'});
1200 # 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 .
1202 my $checkreserves = CheckReserves($iteminformation->{'itemnumber'});
1203 if (($iteminformation->{'homebranch'} ne $iteminformation->{'holdingbranch'}) and (not $checkreserves) and (C4::Context->preference("AutomaticItemReturn") == 1)){
1204 my $automatictransfer = dotransfer($iteminformation->{'itemnumber'},$iteminformation->{'holdingbranch'},$iteminformation->{'homebranch'});
1205 $messages->{'WasTransfered'} = 1;
1208 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1209 # fix up the overdues in accounts...
1210 fixoverduesonreturn($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
1211 # find reserves.....
1212 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1213 my ($resfound, $resrec) = CheckReserves($iteminformation->{'itemnumber'});
1215 # my $tobrcd = ReserveWaiting($resrec->{'itemnumber'}, $resrec->{'borrowernumber'});
1216 $resrec->{'ResFound'} = $resfound;
1217 $messages->{'ResFound'} = $resrec;
1220 # Record the fact that this book was returned.
1221 UpdateStats(\%env, $branch ,'return','0','',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
1222 return ($doreturn, $messages, $iteminformation, $borrower);
1225 =head2 fixaccountforlostandreturned
1227 &fixaccountforlostandreturned($iteminfo,$borrower);
1229 Calculates the charge for a book lost and returned (Not exported & used only once)
1231 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1233 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1237 sub fixaccountforlostandreturned {
1238 my ($iteminfo, $borrower) = @_;
1240 my $dbh = C4::Context->dbh;
1241 my $itm = $iteminfo->{'itemnumber'};
1242 # check for charge made for lost book
1243 my $sth = $dbh->prepare("select * from accountlines where (itemnumber = ?) and (accounttype='L' or accounttype='Rep') order by date desc");
1244 $sth->execute($itm);
1245 if (my $data = $sth->fetchrow_hashref) {
1246 # writeoff this amount
1248 my $amount = $data->{'amount'};
1249 my $acctno = $data->{'accountno'};
1251 if ($data->{'amountoutstanding'} == $amount) {
1252 $offset = $data->{'amount'};
1255 $offset = $amount - $data->{'amountoutstanding'};
1256 $amountleft = $data->{'amountoutstanding'} - $amount;
1258 my $usth = $dbh->prepare("update accountlines set accounttype = 'LR',amountoutstanding='0'
1259 where (borrowernumber = ?)
1260 and (itemnumber = ?) and (accountno = ?) ");
1261 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1263 #check if any credit is left if so writeoff other accounts
1264 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1265 if ($amountleft < 0){
1268 if ($amountleft > 0){
1269 my $msth = $dbh->prepare("select * from accountlines where (borrowernumber = ?)
1270 and (amountoutstanding >0) order by date");
1271 $msth->execute($data->{'borrowernumber'});
1272 # offset transactions
1275 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1276 if ($accdata->{'amountoutstanding'} < $amountleft) {
1278 $amountleft -= $accdata->{'amountoutstanding'};
1280 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1283 my $thisacct = $accdata->{'accountno'};
1284 my $usth = $dbh->prepare("update accountlines set amountoutstanding= ?
1285 where (borrowernumber = ?)
1286 and (accountno=?)");
1287 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1289 $usth = $dbh->prepare("insert into accountoffsets
1290 (borrowernumber, accountno, offsetaccount, offsetamount)
1293 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1298 if ($amountleft > 0){
1301 my $desc="Book Returned ".$iteminfo->{'barcode'};
1302 $usth = $dbh->prepare("insert into accountlines
1303 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1304 values (?,?,now(),?,?,'CR',?)");
1305 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1307 $usth = $dbh->prepare("insert into accountoffsets
1308 (borrowernumber, accountno, offsetaccount, offsetamount)
1310 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1312 $usth = $dbh->prepare("update items set paidfor='' where itemnumber=?");
1313 $usth->execute($itm);
1320 =head2 fixoverdueonreturn
1322 &fixoverdueonreturn($brn,$itm);
1326 C<$brn> borrowernumber
1332 sub fixoverduesonreturn {
1333 my ($brn, $itm) = @_;
1334 my $dbh = C4::Context->dbh;
1335 # check for overdue fine
1336 my $sth = $dbh->prepare("select * from accountlines where (borrowernumber = ?) and (itemnumber = ?) and (accounttype='FU' or accounttype='O')");
1337 $sth->execute($brn,$itm);
1338 # alter fine to show that the book has been returned
1339 if (my $data = $sth->fetchrow_hashref) {
1340 my $usth=$dbh->prepare("update accountlines set accounttype='F' where (borrowernumber = ?) and (itemnumber = ?) and (acccountno = ?)");
1341 $usth->execute($brn,$itm,$data->{'accountno'});
1350 # NOTE!: If you change this function, be sure to update the POD for
1351 # &getpatroninformation.
1353 # $flags = &patronflags($env, $patron, $dbh);
1356 # {message} Message showing patron's credit or debt
1357 # {noissues} Set if patron owes >$5.00
1358 # {GNA} Set if patron gone w/o address
1359 # {message} "Borrower has no valid address"
1361 # {LOST} Set if patron's card reported lost
1362 # {message} Message to this effect
1364 # {DBARRED} Set is patron is debarred
1365 # {message} Message to this effect
1367 # {NOTES} Set if patron has notes
1368 # {message} Notes about patron
1369 # {ODUES} Set if patron has overdue books
1371 # {itemlist} ref-to-array: list of overdue books
1372 # {itemlisttext} Text list of overdue items
1373 # {WAITING} Set if there are items available that the
1375 # {message} Message to this effect
1376 # {itemlist} ref-to-array: list of available items
1378 # Original subroutine for Circ2.pm
1380 my ($env, $patroninformation, $dbh) = @_;
1381 my $amount = checkaccount($env, $patroninformation->{'borrowernumber'}, $dbh);
1384 my $noissuescharge = C4::Context->preference("noissuescharge");
1385 $flaginfo{'message'}= sprintf "Patron owes \$%.02f", $amount;
1386 if ($amount > $noissuescharge) {
1387 $flaginfo{'noissues'} = 1;
1389 $flags{'CHARGES'} = \%flaginfo;
1390 } elsif ($amount < 0){
1392 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
1393 $flags{'CHARGES'} = \%flaginfo;
1395 if ($patroninformation->{'gonenoaddress'} && $patroninformation->{'gonenoaddress'} == 1) {
1397 $flaginfo{'message'} = 'Borrower has no valid address.';
1398 $flaginfo{'noissues'} = 1;
1399 $flags{'GNA'} = \%flaginfo;
1401 if ($patroninformation->{'lost'} && $patroninformation->{'lost'} == 1) {
1403 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
1404 $flaginfo{'noissues'} = 1;
1405 $flags{'LOST'} = \%flaginfo;
1407 if ($patroninformation->{'debarred'} && $patroninformation->{'debarred'} == 1) {
1409 $flaginfo{'message'} = 'Borrower is Debarred.';
1410 $flaginfo{'noissues'} = 1;
1411 $flags{'DBARRED'} = \%flaginfo;
1413 if ($patroninformation->{'borrowernotes'} && $patroninformation->{'borrowernotes'}) {
1415 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
1416 $flags{'NOTES'} = \%flaginfo;
1418 my ($odues, $itemsoverdue)
1419 = checkoverdues($env, $patroninformation->{'borrowernumber'}, $dbh);
1422 $flaginfo{'message'} = "Yes";
1423 $flaginfo{'itemlist'} = $itemsoverdue;
1424 foreach (sort {$a->{'date_due'} cmp $b->{'date_due'}} @$itemsoverdue) {
1425 $flaginfo{'itemlisttext'}.="$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
1427 $flags{'ODUES'} = \%flaginfo;
1429 my ($nowaiting, $itemswaiting)
1430 = CheckWaiting($patroninformation->{'borrowernumber'});
1431 if ($nowaiting > 0) {
1433 $flaginfo{'message'} = "Reserved items available";
1434 $flaginfo{'itemlist'} = $itemswaiting;
1435 $flags{'WAITING'} = \%flaginfo;
1443 # From Main.pm, modified to return a list of overdueitems, in addition to a count
1444 #checks whether a borrower has overdue items
1445 my ($env, $bornum, $dbh)=@_;
1446 my @datearr = localtime;
1447 my $today = ($datearr[5] + 1900)."-".($datearr[4]+1)."-".$datearr[3];
1450 my $sth = $dbh->prepare("SELECT * FROM issues,biblio,biblioitems,items
1451 WHERE items.biblioitemnumber = biblioitems.biblioitemnumber
1452 AND items.biblionumber = biblio.biblionumber
1453 AND issues.itemnumber = items.itemnumber
1454 AND issues.borrowernumber = ?
1455 AND issues.returndate is NULL
1456 AND issues.date_due < ?");
1457 $sth->execute($bornum,$today);
1458 while (my $data = $sth->fetchrow_hashref) {
1459 push (@overdueitems, $data);
1463 return ($count, \@overdueitems);
1467 sub currentborrower {
1468 # Original subroutine for Circ2.pm
1469 my ($itemnumber) = @_;
1470 my $dbh = C4::Context->dbh;
1471 my $q_itemnumber = $dbh->quote($itemnumber);
1472 my $sth=$dbh->prepare("select borrowers.borrowernumber from
1473 issues,borrowers where issues.itemnumber=$q_itemnumber and
1474 issues.borrowernumber=borrowers.borrowernumber and issues.returndate is
1477 my ($borrower) = $sth->fetchrow;
1481 # FIXME - Not exported, but used in 'updateitem.pl' anyway.
1482 sub checkreserve_to_delete {
1483 # Stolen from Main.pm
1484 # Check for reserves for biblio
1485 my ($env,$dbh,$itemnum)=@_;
1487 my $sth = $dbh->prepare("select * from reserves,items
1488 where (items.itemnumber = ?)
1489 and (reserves.cancellationdate is NULL)
1490 and (items.biblionumber = reserves.biblionumber)
1491 and ((reserves.found = 'W')
1492 or (reserves.found is null))
1493 order by priority");
1494 $sth->execute($itemnum);
1496 my $data=$sth->fetchrow_hashref;
1497 while ($data && $resbor eq '') {
1499 my $const = $data->{'constrainttype'};
1500 if ($const eq "a") {
1501 $resbor = $data->{'borrowernumber'};
1504 my $csth = $dbh->prepare("select * from reserveconstraints,items
1505 where (borrowernumber=?)
1507 and reserveconstraints.biblionumber=?
1508 and (items.itemnumber=? and
1509 items.biblioitemnumber = reserveconstraints.biblioitemnumber)");
1510 $csth->execute($data->{'borrowernumber'},$data->{'biblionumber'},$data->{'reservedate'},$itemnum);
1511 if (my $cdata=$csth->fetchrow_hashref) {$found = 1;}
1512 if ($const eq 'o') {
1513 if ($found eq 1) {$resbor = $data->{'borrowernumber'};}
1515 if ($found eq 0) {$resbor = $data->{'borrowernumber'};}
1519 $data=$sth->fetchrow_hashref;
1522 return ($resbor,$resrec);
1525 =head2 currentissues
1527 $issues = ¤tissues($env, $borrower);
1529 Returns a list of books currently on loan to a patron.
1531 If C<$env-E<gt>{todaysissues}> is set and true, C<¤tissues> only
1532 returns information about books issued today. If
1533 C<$env-E<gt>{nottodaysissues}> is set and true, C<¤tissues> only
1534 returns information about books issued before today. If both are
1535 specified, C<$env-E<gt>{todaysissues}> is ignored. If neither is
1536 specified, C<¤tissues> returns all of the patron's issues.
1538 C<$borrower->{borrowernumber}> is the borrower number of the patron
1539 whose issues we want to list.
1541 C<¤tissues> returns a PHP-style array: C<$issues> is a
1542 reference-to-hash whose keys are integers in the range 1...I<n>, where
1543 I<n> is the number of items on issue (either today or before today).
1544 C<$issues-E<gt>{I<n>}> is a reference-to-hash whose keys are all of
1545 the fields of the biblio, biblioitems, items, and issues fields of the
1546 Koha database for that particular item.
1552 # New subroutine for Circ2.pm
1553 my ($env, $borrower) = @_;
1554 my $dbh = C4::Context->dbh;
1557 my $borrowernumber = $borrower->{'borrowernumber'};
1560 # Figure out whether to get the books issued today, or earlier.
1561 # FIXME - $env->{todaysissues} and $env->{nottodaysissues} can
1562 # both be specified, but are mutually-exclusive. This is bogus.
1563 # Make this a flag. Or better yet, return everything in (reverse)
1564 # chronological order and let the caller figure out which books
1565 # were issued today.
1566 if ($env->{'todaysissues'}) {
1568 # $today = POSIX::strftime("%Y%m%d", localtime);
1569 # FIXME - Since $today will be used in either case, move it
1570 # out of the two if-blocks.
1571 my @datearr = localtime(time());
1572 my $today = (1900+$datearr[5]).sprintf "%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
1573 # FIXME - MySQL knows about dates. Just use
1574 # and issues.timestamp = curdate();
1575 $crit=" and issues.timestamp like '$today%' ";
1577 if ($env->{'nottodaysissues'}) {
1579 # $today = POSIX::strftime("%Y%m%d", localtime);
1580 # FIXME - Since $today will be used in either case, move it
1581 # out of the two if-blocks.
1582 my @datearr = localtime(time());
1583 my $today = (1900+$datearr[5]).sprintf "%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
1584 # FIXME - MySQL knows about dates. Just use
1585 # and issues.timestamp < curdate();
1586 $crit=" and !(issues.timestamp like '$today%') ";
1589 # FIXME - Does the caller really need every single field from all
1591 my $sth=$dbh->prepare("select * from issues,items,biblioitems,biblio where
1592 borrowernumber=? and issues.itemnumber=items.itemnumber and
1593 items.biblionumber=biblio.biblionumber and
1594 items.biblioitemnumber=biblioitems.biblioitemnumber and returndate is null
1595 $crit order by issues.date_due");
1596 $sth->execute($borrowernumber);
1597 while (my $data = $sth->fetchrow_hashref) {
1598 # FIXME - The Dewey code is a string, not a number.
1599 $data->{'dewey'}=~s/0*$//;
1600 ($data->{'dewey'} == 0) && ($data->{'dewey'}='');
1602 # $todaysdate = POSIX::strftime("%Y%m%d", localtime)
1603 # or better yet, just reuse $today which was calculated above.
1604 # This function isn't going to run until midnight, is it?
1606 # $todaysdate = POSIX::strftime("%Y-%m-%d", localtime)
1607 # if ($data->{'date_due'} lt $todaysdate)
1609 # Either way, the date should be be formatted outside of the
1611 my @datearr = localtime(time());
1612 my $todaysdate = (1900+$datearr[5]).sprintf ("%0.2d", ($datearr[4]+1)).sprintf ("%0.2d", $datearr[3]);
1613 my $datedue=$data->{'date_due'};
1615 if ($datedue < $todaysdate) {
1616 $data->{'overdue'}=1;
1618 my $itemnumber=$data->{'itemnumber'};
1619 # FIXME - Consecutive integers as hash keys? You have GOT to
1620 # be kidding me! Use an array, fercrissakes!
1621 $currentissues{$counter}=$data;
1625 return(\%currentissues);
1630 $issues = &getissues($borrowernumber);
1632 Returns the set of books currently on loan to a patron.
1634 C<$borrowernumber> is the patron's borrower number.
1636 C<&getissues> returns a PHP-style array: C<$issues> is a
1637 reference-to-hash whose keys are integers in the range 0..I<n>-1,
1638 where I<n> is the number of books the patron currently has on loan.
1640 The values of C<$issues> are references-to-hash whose keys are
1641 selected fields from the issues, items, biblio, and biblioitems tables
1642 of the Koha database.
1647 # New subroutine for Circ2.pm
1648 my ($borrower) = @_;
1649 my $dbh = C4::Context->dbh;
1650 my $borrowernumber = $borrower->{'borrowernumber'};
1652 my $select = "SELECT items.*,issues.timestamp AS timestamp,
1653 issues.date_due AS date_due,
1654 items.barcode AS barcode,
1655 biblio.title AS title,
1656 biblio.author AS author,
1657 biblioitems.dewey AS dewey,
1658 itemtypes.description AS itemtype,
1659 biblioitems.subclass AS subclass,
1660 biblioitems.classification AS classification
1661 FROM issues,items,biblioitems,biblio, itemtypes
1662 WHERE issues.borrowernumber = ?
1663 AND issues.itemnumber = items.itemnumber
1664 AND items.biblionumber = biblio.biblionumber
1665 AND items.biblioitemnumber = biblioitems.biblioitemnumber
1666 AND itemtypes.itemtype = biblioitems.itemtype
1667 AND issues.returndate IS NULL
1668 ORDER BY issues.date_due DESC";
1670 my $sth=$dbh->prepare($select);
1671 $sth->execute($borrowernumber);
1673 while (my $data = $sth->fetchrow_hashref) {
1674 $data->{'dewey'} =~ s/0*$//;
1675 ($data->{'dewey'} == 0) && ($data->{'dewey'} = '');
1676 # FIXME - The Dewey code is a string, not a number.
1677 # FIXME - Use POSIX::strftime to get a text version of today's
1678 # date. That's what it's for.
1679 # FIXME - Move the date calculation outside of the loop.
1680 my @datearr = localtime(time());
1681 my $todaysdate = (1900+$datearr[5]).sprintf ("%0.2d", ($datearr[4]+1)).sprintf ("%0.2d", $datearr[3]);
1683 # FIXME - Instead of converting the due date to YYYYMMDD, just
1685 # $todaysdate = POSIX::strftime("%Y-%m-%d", localtime);
1687 # if ($date->{date_due} lt $todaysdate)
1688 my $datedue = $data->{'date_due'};
1690 if ($datedue < $todaysdate) {
1691 $data->{'overdue'} = 1;
1693 $currentissues{$counter} = $data;
1695 # FIXME - This is ludicrous. If you want to return an
1696 # array of values, just use an array. That's what
1697 # they're there for.
1700 return(\%currentissues);
1705 #Stolen from Main.pm
1706 # check for reserves waiting
1707 my ($env,$dbh,$bornum)=@_;
1709 my $sth = $dbh->prepare("select * from reserves where (borrowernumber = ?) and (reserves.found='W') and cancellationdate is NULL");
1710 $sth->execute($bornum);
1712 if (my $data=$sth->fetchrow_hashref) {
1713 $itemswaiting[$cnt] =$data;
1717 return ($cnt,\@itemswaiting);
1722 $ok = &renewstatus($env, $dbh, $borrowernumber, $itemnumber);
1724 Find out whether a borrowed item may be renewed.
1728 C<$dbh> is a DBI handle to the Koha database.
1730 C<$borrowernumber> is the borrower number of the patron who currently
1731 has the item on loan.
1733 C<$itemnumber> is the number of the item to renew.
1735 C<$renewstatus> returns a true value iff the item may be renewed. The
1736 item must currently be on loan to the specified borrower; renewals
1737 must be allowed for the item's type; and the borrower must not have
1738 already renewed the loan.
1743 # check renewal status
1744 my ($env,$bornum,$itemno)=@_;
1745 my $dbh = C4::Context->dbh;
1748 # Look in the issues table for this item, lent to this borrower,
1749 # and not yet returned.
1751 # FIXME - I think this function could be redone to use only one SQL call.
1752 my $sth1 = $dbh->prepare("select * from issues
1753 where (borrowernumber = ?)
1754 and (itemnumber = ?)
1755 and returndate is null");
1756 $sth1->execute($bornum,$itemno);
1757 if (my $data1 = $sth1->fetchrow_hashref) {
1758 # Found a matching item
1760 # See if this item may be renewed. This query is convoluted
1761 # because it's a bit messy: given the item number, we need to find
1762 # the biblioitem, which gives us the itemtype, which tells us
1763 # whether it may be renewed.
1764 my $sth2 = $dbh->prepare("SELECT renewalsallowed from items,biblioitems,itemtypes
1765 where (items.itemnumber = ?)
1766 and (items.biblioitemnumber = biblioitems.biblioitemnumber)
1767 and (biblioitems.itemtype = itemtypes.itemtype)");
1768 $sth2->execute($itemno);
1769 if (my $data2=$sth2->fetchrow_hashref) {
1770 $renews = $data2->{'renewalsallowed'};
1772 if ($renews && $renews > $data1->{'renewals'}) {
1776 my ($resfound, $resrec) = CheckReserves($itemno);
1780 ($resfound, $resrec) = CheckReserves($itemno);
1792 &renewbook($env, $borrowernumber, $itemnumber, $datedue);
1796 C<$env-E<gt>{branchcode}> is the code of the branch where the
1797 renewal is taking place.
1799 C<$env-E<gt>{usercode}> is the value to log in C<statistics.usercode>
1800 in the Koha database.
1802 C<$borrowernumber> is the borrower number of the patron who currently
1805 C<$itemnumber> is the number of the item to renew.
1807 C<$datedue> can be used to set the due date. If C<$datedue> is the
1808 empty string, C<&renewbook> will calculate the due date automatically
1809 from the book's item type. If you wish to set the due date manually,
1810 C<$datedue> should be in the form YYYY-MM-DD.
1815 # mark book as renewed
1816 my ($env,$bornum,$itemno,$datedue)=@_;
1817 my $dbh = C4::Context->dbh;
1819 # If the due date wasn't specified, calculate it by adding the
1820 # book's loan length to today's date.
1821 if ($datedue eq "" ) {
1822 #debug_msg($env, "getting date");
1823 my $iteminformation = getiteminformation($env, $itemno,0);
1824 my $borrower = getpatroninformation($env,$bornum,0);
1825 my $loanlength = getLoanLength($borrower->{'categorycode'},$iteminformation->{'itemtype'},$borrower->{'branchcode'});
1826 $datedue = UnixDate(DateCalc("today","$loanlength days"),"%Y-%m-%d");
1829 # Find the issues record for this book
1830 my $sth=$dbh->prepare("select * from issues where borrowernumber=? and itemnumber=? and returndate is null");
1831 $sth->execute($bornum,$itemno);
1832 my $issuedata=$sth->fetchrow_hashref;
1835 # Update the issues record to have the new due date, and a new count
1836 # of how many times it has been renewed.
1837 my $renews = $issuedata->{'renewals'} +1;
1838 $sth=$dbh->prepare("update issues set date_due = ?, renewals = ?
1839 where borrowernumber=? and itemnumber=? and returndate is null");
1840 $sth->execute($datedue,$renews,$bornum,$itemno);
1844 UpdateStats($env,$env->{'branchcode'},'renew','','',$itemno);
1846 # Charge a new rental fee, if applicable?
1847 my ($charge,$type)=calc_charges($env, $itemno, $bornum);
1849 my $accountno=getnextacctno($env,$bornum,$dbh);
1850 my $item=getiteminformation($env, $itemno);
1851 $sth=$dbh->prepare("Insert into accountlines (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding,itemnumber)
1852 values (?,?,now(),?,?,?,?,?)");
1853 $sth->execute($bornum,$accountno,$charge,"Renewal of Rental Item $item->{'title'} $item->{'barcode'}",'Rent',$charge,$itemno);
1865 ($charge, $item_type) = &calc_charges($env, $itemnumber, $borrowernumber);
1867 Calculate how much it would cost for a given patron to borrow a given
1868 item, including any applicable discounts.
1872 C<$itemnumber> is the item number of item the patron wishes to borrow.
1874 C<$borrowernumber> is the patron's borrower number.
1876 C<&calc_charges> returns two values: C<$charge> is the rental charge,
1877 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1883 # calculate charges due
1884 my ($env, $itemno, $bornum)=@_;
1886 my $dbh = C4::Context->dbh;
1889 # Get the book's item type and rental charge (via its biblioitem).
1890 my $sth1= $dbh->prepare("select itemtypes.itemtype,rentalcharge from items,biblioitems,itemtypes
1891 where (items.itemnumber =?)
1892 and (biblioitems.biblioitemnumber = items.biblioitemnumber)
1893 and (biblioitems.itemtype = itemtypes.itemtype)");
1894 $sth1->execute($itemno);
1895 if (my $data1=$sth1->fetchrow_hashref) {
1896 $item_type = $data1->{'itemtype'};
1897 $charge = $data1->{'rentalcharge'};
1898 my $q2 = "select rentaldiscount from issuingrules,borrowers
1899 where (borrowers.borrowernumber = ?)
1900 and (borrowers.categorycode = issuingrules.categorycode)
1901 and (issuingrules.itemtype = ?)";
1902 my $sth2=$dbh->prepare($q2);
1903 $sth2->execute($bornum,$item_type);
1904 if (my $data2=$sth2->fetchrow_hashref) {
1905 my $discount = $data2->{'rentaldiscount'};
1906 if ($discount eq 'NULL') {
1909 $charge = ($charge *(100 - $discount)) / 100;
1910 # warn "discount is $discount";
1916 return ($charge,$item_type);
1920 # FIXME - A virtually identical function appears in
1921 # C4::Circulation::Issues. Pick one and stick with it.
1923 #Stolen from Issues.pm
1924 my ($env,$dbh,$itemno,$bornum,$charge) = @_;
1925 my $nextaccntno = getnextacctno($env,$bornum,$dbh);
1926 my $sth = $dbh->prepare(<<EOT);
1927 INSERT INTO accountlines
1928 (borrowernumber, itemnumber, accountno,
1929 date, amount, description, accounttype,
1932 now(), ?, 'Rental', 'Rent',
1935 $sth->execute($bornum, $itemno, $nextaccntno, $charge, $charge);
1942 ($status, $record) = &find_reserves($itemnumber);
1944 Looks up an item in the reserves.
1946 C<$itemnumber> is the itemnumber to look up.
1948 C<$status> is true iff the search was successful.
1950 C<$record> is a reference-to-hash describing the reserve. Its keys are
1951 the fields from the reserves table of the Koha database.
1955 # FIXME - This API is bogus: just return the record, or undef if none
1957 # FIXME - There's also a &C4::Circulation::Returns::find_reserves, but
1958 # that one looks rather different.
1960 # Stolen from Returns.pm
1963 my $dbh = C4::Context->dbh;
1964 my ($itemdata) = getiteminformation(\%env, $itemno,0);
1965 my $bibno = $dbh->quote($itemdata->{'biblionumber'});
1966 my $bibitm = $dbh->quote($itemdata->{'biblioitemnumber'});
1967 my $sth = $dbh->prepare("select * from reserves where ((found = 'W') or (found is null)) and biblionumber = ? and cancellationdate is NULL order by priority, reservedate");
1968 $sth->execute($bibno);
1974 # FIXME - I'm not really sure what's going on here, but since we
1975 # only want one result, wouldn't it be possible (and far more
1976 # efficient) to do something clever in SQL that only returns one
1978 while (($resrec = $sth->fetchrow_hashref) && (not $resfound)) {
1979 # FIXME - Unlike Pascal, Perl allows you to exit loops
1980 # early. Take out the "&& (not $resfound)" and just
1981 # use "last" at the appropriate point in the loop.
1982 # (Oh, and just in passing: if you'd used "!" instead
1983 # of "not", you wouldn't have needed the parentheses.)
1985 my $brn = $dbh->quote($resrec->{'borrowernumber'});
1986 my $rdate = $dbh->quote($resrec->{'reservedate'});
1987 my $bibno = $dbh->quote($resrec->{'biblionumber'});
1988 if ($resrec->{'found'} eq "W") {
1989 if ($resrec->{'itemnumber'} eq $itemno) {
1993 # FIXME - Use 'elsif' to avoid unnecessary indentation.
1994 if ($resrec->{'constrainttype'} eq "a") {
1997 my $consth = $dbh->prepare("select * from reserveconstraints where borrowernumber = ? and reservedate = ? and biblionumber = ? and biblioitemnumber = ?");
1998 $consth->execute($brn,$rdate,$bibno,$bibitm);
1999 if (my $conrec = $consth->fetchrow_hashref) {
2000 if ($resrec->{'constrainttype'} eq "o") {
2008 my $updsth = $dbh->prepare("update reserves set found = 'W', itemnumber = ? where borrowernumber = ? and reservedate = ? and biblionumber = ?");
2009 $updsth->execute($itemno,$brn,$rdate,$bibno);
2011 # FIXME - "last;" here to break out of the loop early.
2015 return ($resfound,$lastrec);
2019 my ($year, $month, $day) = @_;
2022 if ($year && $month && $day){
2023 if (($year eq 0 ) && ($month eq 0) && ($year eq 0)) {
2024 # $env{'datedue'}='';
2026 if (($year eq 0) || ($month eq 0) || ($year eq 0)) {
2029 if (($day>30) && (($month==4) || ($month==6) || ($month==9) || ($month==11))) {
2030 $invalidduedate = 1;
2032 elsif (($day > 29) && ($month == 2)) {
2035 elsif (($month == 2) && ($day > 28) && (($year%4) && ((!($year%100) || ($year%400))))) {
2039 $date="$year-$month-$day";
2044 return ($date, $invalidduedate);
2048 sub get_current_return_date_of {
2049 my (@itemnumbers) = @_;
2055 WHERE itemnumber IN ('.join(',', @itemnumbers).') AND returndate IS NULL
2057 return get_infos_of($query, 'itemnumber', 'date_due');
2060 sub get_transfert_infos {
2061 my ($itemnumber) = @_;
2063 my $dbh = C4::Context->dbh;
2069 FROM branchtransfers
2070 WHERE itemnumber = ?
2071 AND datearrived IS NULL
2073 my $sth = $dbh->prepare($query);
2074 $sth->execute($itemnumber);
2076 my @row = $sth->fetchrow_array();
2084 sub DeleteTransfer {
2085 my($itemnumber) = @_;
2086 my $dbh = C4::Context->dbh;
2087 my $sth=$dbh->prepare("DELETE FROM branchtransfers
2089 AND datearrived is null ");
2090 $sth->execute($itemnumber);
2094 sub GetTransfersFromBib {
2095 my($frombranch,$tobranch) = @_;
2096 my $dbh = C4::Context->dbh;
2097 my $sth=$dbh->prepare("SELECT itemnumber,datesent,frombranch FROM
2101 AND datearrived is null ");
2102 $sth->execute($frombranch,$tobranch);
2105 while (my $data=$sth->fetchrow_hashref){
2106 $gettransfers[$i]=$data;
2110 return(@gettransfers);
2113 sub GetReservesToBranch {
2114 my($frombranch,$default) = @_;
2115 my $dbh = C4::Context->dbh;
2116 my $sth=$dbh->prepare("SELECT borrowernumber,reservedate,itemnumber,timestamp FROM
2118 where priority='0' AND cancellationdate is null
2121 AND found is null ");
2122 $sth->execute($frombranch,$default);
2125 while (my $data=$sth->fetchrow_hashref){
2126 $transreserv[$i]=$data;
2130 return(@transreserv);
2133 sub GetReservesForBranch {
2134 my($frombranch) = @_;
2135 my $dbh = C4::Context->dbh;
2136 my $sth=$dbh->prepare("SELECT borrowernumber,reservedate,itemnumber,waitingdate FROM
2138 where priority='0' AND cancellationdate is null
2140 AND branchcode=? order by reservedate");
2141 $sth->execute($frombranch);
2144 while (my $data=$sth->fetchrow_hashref){
2145 $transreserv[$i]=$data;
2149 return(@transreserv);
2152 sub checktransferts{
2153 my($itemnumber) = @_;
2154 my $dbh = C4::Context->dbh;
2155 my $sth=$dbh->prepare("SELECT datesent,frombranch,tobranch FROM branchtransfers
2156 WHERE itemnumber = ? AND datearrived IS NULL");
2157 $sth->execute($itemnumber);
2158 my @tranferts = $sth->fetchrow_array;
2161 return (@tranferts);
2171 Koha Developement team <info@koha.org>