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
40 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
42 # set the version for version checking
47 C4::Circulation::Circ2 - Koha circulation module
51 use C4::Circulation::Circ2;
55 The functions in this module deal with circulation, issues, and
56 returns, as well as general information about the library.
57 Also deals with stocktaking.
66 @EXPORT = qw(&getpatroninformation
67 ¤tissues &getissues &getiteminformation &renewstatus &renewbook
68 &canbookbeissued &issuebook &returnbook &find_reserves &transferbook &decode
69 &calc_charges &listitemsforinventory &itemseen &fixdate);
71 # &getbranches &getprinters &getbranch &getprinter => moved to C4::Koha.pm
76 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
77 C<$itemnum> is the item number
83 my $dbh = C4::Context->dbh;
84 my $sth = $dbh->prepare("update items set itemlost=0, datelastseen = now() where items.itemnumber = ?");
85 $sth->execute($itemnum);
92 Mark item as borrowed. Is called when an item is issued.
93 C<$itemnum> is the item number
99 my $dbh = C4::Context->dbh;
100 my $sth = $dbh->prepare("update items set itemlost=0, datelastborrowed = now() where items.itemnumber = ?");
101 $sth->execute($itemnum);
105 sub listitemsforinventory {
106 my ($minlocation,$maxlocation,$datelastseen,$offset,$size) = @_;
107 my $dbh = C4::Context->dbh;
108 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");
109 $sth->execute($minlocation,$maxlocation,$datelastseen);
111 while (my $row = $sth->fetchrow_hashref) {
112 $offset-- if ($offset);
113 if ((!$offset) && $size) {
121 =head2 getpatroninformation
123 ($borrower, $flags) = &getpatroninformation($env, $borrowernumber, $cardnumber);
125 Looks up a patron and returns information about him or her. If
126 C<$borrowernumber> is true (nonzero), C<&getpatroninformation> looks
127 up the borrower by number; otherwise, it looks up the borrower by card
130 C<$env> is effectively ignored, but should be a reference-to-hash.
132 C<$borrower> is a reference-to-hash whose keys are the fields of the
133 borrowers table in the Koha database. In addition,
134 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
135 about the patron. Its keys act as flags :
137 if $borrower->{flags}->{LOST} {
138 # Patron's card was reported lost
141 Each flag has a C<message> key, giving a human-readable explanation of
142 the flag. If the state of a flag means that the patron should not be
143 allowed to borrow any more books, then it will have a C<noissues> key
146 The possible flags are:
152 Shows the patron's credit or debt, if any.
160 (Gone, no address.) Set if the patron has left without giving a
169 Set if the patron's card has been reported as lost.
177 Set if the patron has been debarred.
185 Any additional notes about the patron.
193 Set if the patron has overdue items. This flag has several keys:
195 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
196 overdue items. Its elements are references-to-hash, each describing an
197 overdue item. The keys are selected fields from the issues, biblio,
198 biblioitems, and items tables of the Koha database.
200 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
201 the overdue items, one per line.
209 Set if any items that the patron has reserved are available.
211 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
212 available items. Each element is a reference-to-hash whose keys are
213 fields from the reserves table of the Koha database.
222 sub getpatroninformation {
224 my ($env, $borrowernumber,$cardnumber) = @_;
225 my $dbh = C4::Context->dbh;
228 if ($borrowernumber) {
229 $sth = $dbh->prepare("select * from borrowers where borrowernumber=?");
230 $sth->execute($borrowernumber);
231 } elsif ($cardnumber) {
232 $sth = $dbh->prepare("select * from borrowers where cardnumber=?");
233 $sth->execute($cardnumber);
235 $env->{'apierror'} = "invalid borrower information passed to getpatroninformation subroutine";
238 my $borrower = $sth->fetchrow_hashref;
239 my $amount = checkaccount($env, $borrowernumber, $dbh);
240 $borrower->{'amountoutstanding'} = $amount;
241 my $flags = patronflags($env, $borrower, $dbh);
244 $sth=$dbh->prepare("select bit,flag from userflags");
246 while (my ($bit, $flag) = $sth->fetchrow) {
247 if ($borrower->{'flags'} && $borrower->{'flags'} & 2**$bit) {
248 $accessflagshash->{$flag}=1;
252 $borrower->{'flags'}=$flags;
253 $borrower->{'authflags'} = $accessflagshash;
254 return ($borrower); #, $flags, $accessflagshash);
261 =head3 $str = &decode($chunk);
265 Decodes a segment of a string emitted by a CueCat barcode scanner and
274 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
277 my $seq = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
278 my @s = map { index($seq,$_); } split(//,$encoded);
293 my $n = (($s[0] << 6 | $s[1]) << 6 | $s[2]) << 6 | $s[3];
294 $r .=chr(($n >> 16) ^ 67) .
295 chr(($n >> 8 & 255) ^ 67) .
296 chr(($n & 255) ^ 67);
299 $r = substr($r,0,length($r)-$l);
303 =head2 getiteminformation
307 $item = &getiteminformation($env, $itemnumber, $barcode);
309 Looks up information about an item, given either its item number or
310 its barcode. If C<$itemnumber> is a nonzero value, it is used;
311 otherwise, C<$barcode> is used.
313 C<$env> is effectively ignored, but should be a reference-to-hash.
315 C<$item> is a reference-to-hash whose keys are fields from the biblio,
316 items, and biblioitems tables of the Koha database. It may also
317 contain the following keys:
323 The due date on this item, if it has been borrowed and not returned
324 yet. The date is in YYYY-MM-DD format.
332 True if the item may not be borrowed.
341 sub getiteminformation {
342 # returns a hash of item information given either the itemnumber or the barcode
343 my ($env, $itemnumber, $barcode) = @_;
344 my $dbh = C4::Context->dbh;
347 $sth=$dbh->prepare("select * from biblio,items,biblioitems where items.itemnumber=? and biblio.biblionumber=items.biblionumber and biblioitems.biblioitemnumber = items.biblioitemnumber");
348 $sth->execute($itemnumber);
350 $sth=$dbh->prepare("select * from biblio,items,biblioitems where items.barcode=? and biblio.biblionumber=items.biblionumber and biblioitems.biblioitemnumber = items.biblioitemnumber");
351 $sth->execute($barcode);
353 $env->{'apierror'}="getiteminformation() subroutine must be called with either an itemnumber or a barcode";
357 my $iteminformation=$sth->fetchrow_hashref;
359 if ($iteminformation) {
360 $sth=$dbh->prepare("select date_due from issues where itemnumber=? and isnull(returndate)");
361 $sth->execute($iteminformation->{'itemnumber'});
362 my ($date_due) = $sth->fetchrow;
363 $iteminformation->{'date_due'}=$date_due;
365 ($iteminformation->{'dewey'} == 0) && ($iteminformation->{'dewey'}='');
366 $sth=$dbh->prepare("select * from itemtypes where itemtype=?");
367 $sth->execute($iteminformation->{'itemtype'});
368 my $itemtype=$sth->fetchrow_hashref;
369 # if specific item notforloan, don't use itemtype notforloan field.
370 # otherwise, use itemtype notforloan value to see if item can be issued.
371 $iteminformation->{'notforloan'}=$itemtype->{'notforloan'} unless $iteminformation->{'notforloan'};
374 return($iteminformation);
381 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
383 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
385 C<$newbranch> is the code for the branch to which the item should be transferred.
387 C<$barcode> is the barcode of the item to be transferred.
389 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
390 Otherwise, if an item is reserved, the transfer fails.
392 Returns three values:
396 is true if the transfer was successful.
400 is a reference-to-hash which may have any of the following keys:
406 There is no item in the catalog with the given barcode. The value is C<$barcode>.
410 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.
412 C<DestinationEqualsHolding>
414 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.
418 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.
422 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>.
426 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
437 # FIXME - This function tries to do too much, and its API is clumsy.
438 # If it didn't also return books, it could be used to change the home
439 # branch of a book while the book is on loan.
441 # Is there any point in returning the item information? The caller can
442 # look that up elsewhere if ve cares.
444 # This leaves the ($dotransfer, $messages) tuple. This seems clumsy.
445 # If the transfer succeeds, that's all the caller should need to know.
446 # Thus, this function could simply return 1 or 0 to indicate success
447 # or failure, and set $C4::Circulation::Circ2::errmsg in case of
448 # failure. Or this function could return undef if successful, and an
449 # error message in case of failure (this would feel more like C than
452 # transfer book code....
453 my ($tbr, $barcode, $ignoreRs) = @_;
457 my $branches = getbranches();
458 my $iteminformation = getiteminformation(\%env, 0, $barcode);
460 if (not $iteminformation) {
461 $messages->{'BadBarcode'} = $barcode;
464 # get branches of book...
465 my $hbr = $iteminformation->{'homebranch'};
466 my $fbr = $iteminformation->{'holdingbranch'};
468 if ($hbr && $branches->{$hbr}->{'PE'}) {
469 $messages->{'IsPermanent'} = $hbr;
471 # can't transfer book if is already there....
472 # FIXME - Why not? Shouldn't it trivially succeed?
474 $messages->{'DestinationEqualsHolding'} = 1;
477 # check if it is still issued to someone, return it...
478 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
479 if ($currentborrower) {
480 returnbook($barcode, $fbr);
481 $messages->{'WasReturned'} = $currentborrower;
484 # FIXME - Don't call &CheckReserves unless $ignoreRs is true.
485 # That'll save a database query.
486 my ($resfound, $resrec) = CheckReserves($iteminformation->{'itemnumber'});
487 if ($resfound and not $ignoreRs) {
488 $resrec->{'ResFound'} = $resfound;
489 $messages->{'ResFound'} = $resrec;
492 #actually do the transfer....
494 dotransfer($iteminformation->{'itemnumber'}, $fbr, $tbr);
495 $messages->{'WasTransfered'} = 1;
497 return ($dotransfer, $messages, $iteminformation);
501 # FIXME - This is only used in &transferbook. Why bother making it a
504 my ($itm, $fbr, $tbr) = @_;
505 my $dbh = C4::Context->dbh;
506 $itm = $dbh->quote($itm);
507 $fbr = $dbh->quote($fbr);
508 $tbr = $dbh->quote($tbr);
509 #new entry in branchtransfers....
510 $dbh->do("INSERT INTO branchtransfers (itemnumber, frombranch, datearrived, tobranch)
511 VALUES ($itm, $fbr, now(), $tbr)");
512 #update holdingbranch in items .....
513 $dbh->do("UPDATE items set holdingbranch = $tbr WHERE items.itemnumber = $itm");
518 =head2 canbookbeissued
520 Check if a book can be issued.
522 my ($issuingimpossible,$needsconfirmation) = canbookbeissued($env,$borrower,$barcode,$year,$month,$day);
526 C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
528 C<$borrower> hash with borrower informations (from getpatroninformation)
530 C<$barcode> is the bar code of the book being issued.
532 C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
540 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
541 Possible values are :
545 sticky due date is invalid
549 borrower gone with no address
553 borrower declared it's card lost
559 =head3 UNKNOWN_BARCODE
573 item is restricted (set by ??)
577 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
578 Possible values are :
586 renewing, not issuing
588 =head3 ISSUED_TO_ANOTHER
590 issued to someone else.
594 reserved for someone else.
598 sticky due date is invalid
602 if the borrower borrows to much things
606 # check if a book can be issued.
607 # returns an array with errors if any
610 my $borrower = shift;
611 my $iteminformation = shift;
612 my $cat_borrower = $borrower->{'categorycode'};
613 my $branch_borrower = $borrower->{'branchcode'};
614 my $dbh = C4::Context->dbh;
617 my $sth = $dbh->prepare('select itemtype from biblioitems where biblionumber = ?');
618 $sth->execute($iteminformation->{'biblionumber'});
619 my $type = $sth->fetchrow;
620 $sth = $dbh->prepare('select * from issuingrules where categorycode = ? and itemtype = ? and branchcode = ?');
621 # 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 ?");
622 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");
623 my $sth3 = $dbh->prepare('select COUNT(*) from issues where borrowernumber = ? and returndate is null');
625 # check the 3 parameters
626 $sth->execute($cat_borrower, $type, $branch_borrower);
627 my $result = $sth->fetchrow_hashref;
628 # warn "==>".$result->{maxissueqty};
629 if (defined($result)) {
630 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
631 my $alreadyissued = $sth2->fetchrow;
632 return ("a $alreadyissued / ".($result->{maxissueqty}+0)) if ($result->{'maxissueqty'} <= $alreadyissued);
635 $sth->execute($cat_borrower, $type, "");
636 $result = $sth->fetchrow_hashref;
637 if (defined($result)) {
638 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
639 my $alreadyissued = $sth2->fetchrow;
640 return ("b $alreadyissued / ".($result->{maxissueqty}+0)) if ($result->{'maxissueqty'} <= $alreadyissued);
642 # check for itemtype=*
643 $sth->execute($cat_borrower, "*", $branch_borrower);
644 $result = $sth->fetchrow_hashref;
645 if (defined($result)) {
646 $sth3->execute($borrower->{'borrowernumber'});
647 my ($alreadyissued) = $sth3->fetchrow;
648 warn "HERE : $alreadyissued / ($result->{maxissueqty} for $borrower->{'borrowernumber'}";
649 return ("c $alreadyissued / ".($result->{maxissueqty}+0)) if ($result->{'maxissueqty'} <= $alreadyissued);
651 #check for borrowertype=*
652 $sth->execute("*", $type, $branch_borrower);
653 $result = $sth->fetchrow_hashref;
654 if (defined($result)) {
655 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
656 my $alreadyissued = $sth2->fetchrow;
657 return ("d $alreadyissued / ".($result->{maxissueqty}+0)) if ($result->{'maxissueqty'} <= $alreadyissued);
660 $sth->execute("*", "*", $branch_borrower);
661 $result = $sth->fetchrow_hashref;
662 if (defined($result)) {
663 $sth3->execute($borrower->{'borrowernumber'});
664 my $alreadyissued = $sth3->fetchrow;
665 return ("e $alreadyissued / ".($result->{maxissueqty}+0)) if ($result->{'maxissueqty'} <= $alreadyissued);
668 $sth->execute("*", $type, "");
669 $result = $sth->fetchrow_hashref;
670 if (defined($result) && $result->{maxissueqty}>=0) {
671 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
672 my $alreadyissued = $sth2->fetchrow;
673 return ("f $alreadyissued / ".($result->{maxissueqty}+0)) if ($result->{'maxissueqty'} <= $alreadyissued);
676 $sth->execute($cat_borrower, "*", "");
677 $result = $sth->fetchrow_hashref;
678 if (defined($result)) {
679 $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
680 my $alreadyissued = $sth2->fetchrow;
681 return ("g $alreadyissued / ".($result->{maxissueqty}+0)) if ($result->{'maxissueqty'} <= $alreadyissued);
684 $sth->execute("*", "*", "");
685 $result = $sth->fetchrow_hashref;
686 if (defined($result)) {
687 $sth3->execute($borrower->{'borrowernumber'});
688 my $alreadyissued = $sth3->fetchrow;
689 return ("h $alreadyissued / ".($result->{maxissueqty}+0)) if ($result->{'maxissueqty'} <= $alreadyissued);
695 sub canbookbeissued {
696 my ($env,$borrower,$barcode,$year,$month,$day) = @_;
697 my %needsconfirmation; # filled with problems that needs confirmations
698 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
699 my $iteminformation = getiteminformation($env, 0, $barcode);
700 my $dbh = C4::Context->dbh;
704 my ($duedate, $invalidduedate) = fixdate($year, $month, $day);
705 $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
710 if ($borrower->{flags}->{GNA}) {
711 $issuingimpossible{GNA} = 1;
713 if ($borrower->{flags}->{'LOST'}) {
714 $issuingimpossible{CARD_LOST} = 1;
716 if ($borrower->{flags}->{'DBARRED'}) {
717 $issuingimpossible{DEBARRED} = 1;
719 if (&Date_Cmp(&ParseDate($borrower->{expiry}),&ParseDate("today"))<0) {
720 $issuingimpossible{EXPIRED} = 1;
727 my $amount = checkaccount($env,$borrower->{'borrowernumber'}, $dbh,$duedate);
729 $needsconfirmation{DEBT} = $amount;
734 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
736 my $toomany = TooMany($borrower, $iteminformation);
737 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
742 unless ($iteminformation->{barcode}) {
743 $issuingimpossible{UNKNOWN_BARCODE} = 1;
745 if ($iteminformation->{'notforloan'} > 0) {
746 $issuingimpossible{NOT_FOR_LOAN} = 1;
748 if ($iteminformation->{'itemtype'} &&$iteminformation->{'itemtype'} eq 'REF') {
749 $issuingimpossible{NOT_FOR_LOAN} = 1;
751 if ($iteminformation->{'wthdrawn'} && $iteminformation->{'wthdrawn'} == 1) {
752 $issuingimpossible{WTHDRAWN} = 1;
754 if ($iteminformation->{'restricted'} && $iteminformation->{'restricted'} == 1) {
755 $issuingimpossible{RESTRICTED} = 1;
761 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
763 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
764 if ($currentborrower && $currentborrower eq $borrower->{'borrowernumber'}) {
765 # Already issued to current borrower. Ask whether the loan should
767 my ($renewstatus) = renewstatus($env, $borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
768 if ($renewstatus == 0) { # no more renewals allowed
769 $issuingimpossible{NO_MORE_RENEWALS} = 1;
771 $needsconfirmation{RENEW_ISSUE} = 1;
773 } elsif ($currentborrower) {
774 # issued to someone else
775 my $currborinfo = getpatroninformation(0,$currentborrower);
776 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
777 $needsconfirmation{ISSUED_TO_ANOTHER} = "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
779 # See if the item is on reserve.
780 my ($restype, $res) = CheckReserves($iteminformation->{'itemnumber'});
782 my $resbor = $res->{'borrowernumber'};
783 if ($resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting") {
784 # The item is on reserve and waiting, but has been
785 # reserved by some other patron.
786 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
787 my $branches = getbranches();
788 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
789 $needsconfirmation{RESERVE_WAITING} = "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
790 # CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'}); Doesn't belong in a checking subroutine.
791 } elsif ($restype eq "Reserved") {
792 # The item is on reserve for someone else.
793 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
794 my $branches = getbranches();
795 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
796 $needsconfirmation{RESERVED} = "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
799 return(\%issuingimpossible,\%needsconfirmation);
804 Issue a book. Does no check, they are done in canbookbeissued. If we reach this sub, it means the user confirmed if needed.
806 &issuebook($env,$borrower,$barcode,$date)
810 C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
812 C<$borrower> hash with borrower informations (from getpatroninformation)
814 C<$barcode> is the bar code of the book being issued.
816 C<$date> contains the max date of return. calculated if empty.
821 # issuing book. We already have checked it can be issued, so, just issue it !
824 my ($env,$borrower,$barcode,$date,$cancelreserve) = @_;
825 my $dbh = C4::Context->dbh;
826 # my ($borrower, $flags) = &getpatroninformation($env, $borrowernumber, 0);
827 my $iteminformation = getiteminformation($env, 0, $barcode);
828 # warn "B : ".$borrower->{borrowernumber}." / I : ".$iteminformation->{'itemnumber'};
830 # check if we just renew the issue.
832 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
833 if ($currentborrower eq $borrower->{'borrowernumber'}) {
834 my ($charge,$itemtype) = calc_charges($env, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'});
836 createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge);
837 $iteminformation->{'charge'} = $charge;
839 &UpdateStats($env,$env->{'branchcode'},'renew',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
840 renewbook($env, $borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
845 if ($currentborrower ne '') {
846 # This book is currently on loan, but not to the person
847 # who wants to borrow it now. mark it returned before issuing to the new borrower
848 returnbook($iteminformation->{'barcode'}, $env->{'branchcode'});
850 # See if the item is on reserve.
851 my ($restype, $res) = CheckReserves($iteminformation->{'itemnumber'});
853 my $resbor = $res->{'borrowernumber'};
854 if ($resbor eq $borrower->{'borrowernumber'}) {
855 # The item is on reserve to the current patron
858 } elsif ($restype eq "Waiting") {
860 # The item is on reserve and waiting, but has been
861 # reserved by some other patron.
862 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
863 my $branches = getbranches();
864 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
866 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
868 } elsif ($restype eq "Reserved") {
870 # The item is on reserve for someone else.
871 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
872 my $branches = getbranches();
873 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
874 if ($cancelreserve) {
875 # cancel reserves on this item
876 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
877 # also cancel reserve on biblio related to this item
878 #my $st_Fbiblio = $dbh->prepare("select biblionumber from items where itemnumber=?");
879 #$st_Fbiblio->execute($res->{'itemnumber'});
880 #my $biblionumber = $st_Fbiblio->fetchrow;
881 #CancelReserve($biblionumber,0,$res->{'borrowernumber'});
882 #warn "CancelReserve $res->{'itemnumber'}, $res->{'borrowernumber'}";
884 # my $tobrcd = ReserveWaiting($res->{'itemnumber'}, $res->{'borrowernumber'});
885 # transferbook($tobrcd,$barcode, 1);
890 # Record in the database the fact that the book was issued.
891 my $sth=$dbh->prepare("insert into issues (borrowernumber, itemnumber, date_due, branchcode) values (?,?,?,?)");
892 my $loanlength = getLoanLength($borrower->{'categorycode'},$iteminformation->{'itemtype'},$borrower->{'branchcode'});
893 my $datedue=time+($loanlength)*86400;
894 my @datearr = localtime($datedue);
895 my $dateduef = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
899 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
900 if (C4::Context->preference('ReturnBeforeExpiry') && $dateduef gt $borrower->{expiry}) {
901 $dateduef=$borrower->{expiry};
903 $sth->execute($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'}, $dateduef, $env->{'branchcode'});
905 $iteminformation->{'issues'}++;
906 $sth=$dbh->prepare("update items set issues=? where itemnumber=?");
907 $sth->execute($iteminformation->{'issues'},$iteminformation->{'itemnumber'});
909 &itemseen($iteminformation->{'itemnumber'});
910 itemborrowed($iteminformation->{'itemnumber'});
911 # If it costs to borrow this book, charge it to the patron's account.
912 my ($charge,$itemtype)=calc_charges($env, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'});
914 createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge);
915 $iteminformation->{'charge'}=$charge;
917 # Record the fact that this book was issued.
918 &UpdateStats($env,$env->{'branchcode'},'issue',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
924 Get loan length for an itemtype, a borrower type and a branch
926 my $loanlength = &getLoanLength($borrowertype,$itemtype,branchcode)
931 my ($borrowertype,$itemtype,$branchcode) = @_;
932 my $dbh = C4::Context->dbh;
933 my $sth = $dbh->prepare("select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=?");
934 # try to find issuelength & return the 1st available.
935 # check with borrowertype, itemtype and branchcode, then without one of those parameters
936 $sth->execute($borrowertype,$itemtype,$branchcode);
937 my $loanlength = $sth->fetchrow_hashref;
938 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
940 $sth->execute($borrowertype,$itemtype,"");
941 $loanlength = $sth->fetchrow_hashref;
942 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
944 $sth->execute($borrowertype,"*",$branchcode);
945 $loanlength = $sth->fetchrow_hashref;
946 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
948 $sth->execute("*",$itemtype,$branchcode);
949 $loanlength = $sth->fetchrow_hashref;
950 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
952 $sth->execute($borrowertype,"*","");
953 $loanlength = $sth->fetchrow_hashref;
954 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
956 $sth->execute("*","*",$branchcode);
957 $loanlength = $sth->fetchrow_hashref;
958 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
960 $sth->execute("*",$itemtype,"");
961 $loanlength = $sth->fetchrow_hashref;
962 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
964 $sth->execute("*","*","");
965 $loanlength = $sth->fetchrow_hashref;
966 return $loanlength->{issuelength} if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
968 # if no rule is set => 21 days (hardcoded)
973 ($doreturn, $messages, $iteminformation, $borrower) =
974 &returnbook($barcode, $branch);
978 C<$barcode> is the bar code of the book being returned. C<$branch> is
979 the code of the branch where the book is being returned.
981 C<&returnbook> returns a list of four items:
983 C<$doreturn> is true iff the return succeeded.
985 C<$messages> is a reference-to-hash giving the reason for failure:
991 No item with this barcode exists. The value is C<$barcode>.
995 The book is not currently on loan. The value is C<$barcode>.
999 The book's home branch is a permanent collection. If you have borrowed
1000 this book, you are not allowed to return it. The value is the code for
1001 the book's home branch.
1005 This book has been withdrawn/cancelled. The value should be ignored.
1009 The item was reserved. The value is a reference-to-hash whose keys are
1010 fields from the reserves table of the Koha database, and
1011 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1012 either C<Waiting>, C<Reserved>, or 0.
1016 C<$borrower> is a reference-to-hash, giving information about the
1017 patron who last borrowed the book.
1021 # FIXME - This API is bogus. There's no need to return $borrower and
1022 # $iteminformation; the caller can ask about those separately, if it
1023 # cares (it'd be inefficient to make two database calls instead of
1024 # one, but &getpatroninformation and &getiteminformation can be
1025 # memoized if this is an issue).
1027 # The ($doreturn, $messages) tuple is redundant: if the return
1028 # succeeded, that's all the caller needs to know. So &returnbook can
1029 # return 1 and 0 on success and failure, and set
1030 # $C4::Circulation::Circ2::errmsg to indicate the error. Or it can
1031 # return undef for success, and an error message on error (though this
1032 # is more C-ish than Perl-ish).
1035 my ($barcode, $branch) = @_;
1038 my $dbh = C4::Context->dbh;
1040 die '$branch not defined' unless defined $branch; # just in case (bug 170)
1041 # get information on item
1042 my ($iteminformation) = getiteminformation(\%env, 0, $barcode);
1043 if (not $iteminformation) {
1044 $messages->{'BadBarcode'} = $barcode;
1048 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
1049 if ((not $currentborrower) && $doreturn) {
1050 $messages->{'NotIssued'} = $barcode;
1053 # check if the book is in a permanent collection....
1054 my $hbr = $iteminformation->{'homebranch'};
1055 my $branches = getbranches();
1056 if ($hbr && $branches->{$hbr}->{'PE'}) {
1057 $messages->{'IsPermanent'} = $hbr;
1059 # check that the book has been cancelled
1060 if ($iteminformation->{'wthdrawn'}) {
1061 $messages->{'wthdrawn'} = 1;
1064 # update issues, thereby returning book (should push this out into another subroutine
1065 my ($borrower) = getpatroninformation(\%env, $currentborrower, 0);
1067 my $sth = $dbh->prepare("update issues set returndate = now() where (borrowernumber = ?) and (itemnumber = ?) and (returndate is null)");
1068 $sth->execute($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
1069 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1071 itemseen($iteminformation->{'itemnumber'});
1072 ($borrower) = getpatroninformation(\%env, $currentborrower, 0);
1073 # transfer book to the current branch
1074 my ($transfered, $mess, $item) = transferbook($branch, $barcode, 1);
1076 $messages->{'WasTransfered'} = 1; # FIXME is the "= 1" right?
1078 # fix up the accounts.....
1079 if ($iteminformation->{'itemlost'}) {
1080 fixaccountforlostandreturned($iteminformation, $borrower);
1081 $messages->{'WasLost'} = 1; # FIXME is the "= 1" right?
1083 # fix up the overdues in accounts...
1084 fixoverduesonreturn($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
1085 # find reserves.....
1086 my ($resfound, $resrec) = CheckReserves($iteminformation->{'itemnumber'});
1088 # my $tobrcd = ReserveWaiting($resrec->{'itemnumber'}, $resrec->{'borrowernumber'});
1089 $resrec->{'ResFound'} = $resfound;
1090 $messages->{'ResFound'} = $resrec;
1093 # Record the fact that this book was returned.
1094 UpdateStats(\%env, $branch ,'return','0','',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
1095 return ($doreturn, $messages, $iteminformation, $borrower);
1098 =head2 fixaccountforlostandreturned
1100 &fixaccountforlostandreturned($iteminfo,$borrower);
1102 Calculates the charge for a book lost and returned (Not exported & used only once)
1104 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1106 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1110 sub fixaccountforlostandreturned {
1111 my ($iteminfo, $borrower) = @_;
1113 my $dbh = C4::Context->dbh;
1114 my $itm = $iteminfo->{'itemnumber'};
1115 # check for charge made for lost book
1116 my $sth = $dbh->prepare("select * from accountlines where (itemnumber = ?) and (accounttype='L' or accounttype='Rep') order by date desc");
1117 $sth->execute($itm);
1118 if (my $data = $sth->fetchrow_hashref) {
1119 # writeoff this amount
1121 my $amount = $data->{'amount'};
1122 my $acctno = $data->{'accountno'};
1124 if ($data->{'amountoutstanding'} == $amount) {
1125 $offset = $data->{'amount'};
1128 $offset = $amount - $data->{'amountoutstanding'};
1129 $amountleft = $data->{'amountoutstanding'} - $amount;
1131 my $usth = $dbh->prepare("update accountlines set accounttype = 'LR',amountoutstanding='0'
1132 where (borrowernumber = ?)
1133 and (itemnumber = ?) and (accountno = ?) ");
1134 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1136 #check if any credit is left if so writeoff other accounts
1137 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1138 if ($amountleft < 0){
1141 if ($amountleft > 0){
1142 my $msth = $dbh->prepare("select * from accountlines where (borrowernumber = ?)
1143 and (amountoutstanding >0) order by date");
1144 $msth->execute($data->{'borrowernumber'});
1145 # offset transactions
1148 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1149 if ($accdata->{'amountoutstanding'} < $amountleft) {
1151 $amountleft -= $accdata->{'amountoutstanding'};
1153 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1156 my $thisacct = $accdata->{'accountno'};
1157 my $usth = $dbh->prepare("update accountlines set amountoutstanding= ?
1158 where (borrowernumber = ?)
1159 and (accountno=?)");
1160 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1162 $usth = $dbh->prepare("insert into accountoffsets
1163 (borrowernumber, accountno, offsetaccount, offsetamount)
1166 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1171 if ($amountleft > 0){
1174 my $desc="Book Returned ".$iteminfo->{'barcode'};
1175 $usth = $dbh->prepare("insert into accountlines
1176 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1177 values (?,?,now(),?,?,'CR',?)");
1178 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1180 $usth = $dbh->prepare("insert into accountoffsets
1181 (borrowernumber, accountno, offsetaccount, offsetamount)
1183 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1185 $usth = $dbh->prepare("update items set paidfor='' where itemnumber=?");
1186 $usth->execute($itm);
1193 =head2 fixoverdueonreturn
1195 &fixoverdueonreturn($brn,$itm);
1199 C<$brn> borrowernumber
1205 sub fixoverduesonreturn {
1206 my ($brn, $itm) = @_;
1207 my $dbh = C4::Context->dbh;
1208 # check for overdue fine
1209 my $sth = $dbh->prepare("select * from accountlines where (borrowernumber = ?) and (itemnumber = ?) and (accounttype='FU' or accounttype='O')");
1210 $sth->execute($brn,$itm);
1211 # alter fine to show that the book has been returned
1212 if (my $data = $sth->fetchrow_hashref) {
1213 my $usth=$dbh->prepare("update accountlines set accounttype='F' where (borrowernumber = ?) and (itemnumber = ?) and (acccountno = ?)");
1214 $usth->execute($brn,$itm,$data->{'accountno'});
1223 # NOTE!: If you change this function, be sure to update the POD for
1224 # &getpatroninformation.
1226 # $flags = &patronflags($env, $patron, $dbh);
1229 # {message} Message showing patron's credit or debt
1230 # {noissues} Set if patron owes >$5.00
1231 # {GNA} Set if patron gone w/o address
1232 # {message} "Borrower has no valid address"
1234 # {LOST} Set if patron's card reported lost
1235 # {message} Message to this effect
1237 # {DBARRED} Set is patron is debarred
1238 # {message} Message to this effect
1240 # {NOTES} Set if patron has notes
1241 # {message} Notes about patron
1242 # {ODUES} Set if patron has overdue books
1244 # {itemlist} ref-to-array: list of overdue books
1245 # {itemlisttext} Text list of overdue items
1246 # {WAITING} Set if there are items available that the
1248 # {message} Message to this effect
1249 # {itemlist} ref-to-array: list of available items
1251 # Original subroutine for Circ2.pm
1253 my ($env, $patroninformation, $dbh) = @_;
1254 my $amount = checkaccount($env, $patroninformation->{'borrowernumber'}, $dbh);
1257 my $noissuescharge = C4::Context->preference("noissuescharge");
1258 $flaginfo{'message'}= sprintf "Patron owes \$%.02f", $amount;
1259 if ($amount > $noissuescharge) {
1260 $flaginfo{'noissues'} = 1;
1262 $flags{'CHARGES'} = \%flaginfo;
1263 } elsif ($amount < 0){
1265 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
1266 $flags{'CHARGES'} = \%flaginfo;
1268 if ($patroninformation->{'gonenoaddress'} == 1) {
1270 $flaginfo{'message'} = 'Borrower has no valid address.';
1271 $flaginfo{'noissues'} = 1;
1272 $flags{'GNA'} = \%flaginfo;
1274 if ($patroninformation->{'lost'} == 1) {
1276 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
1277 $flaginfo{'noissues'} = 1;
1278 $flags{'LOST'} = \%flaginfo;
1280 if ($patroninformation->{'debarred'} == 1) {
1282 $flaginfo{'message'} = 'Borrower is Debarred.';
1283 $flaginfo{'noissues'} = 1;
1284 $flags{'DBARRED'} = \%flaginfo;
1286 if ($patroninformation->{'borrowernotes'}) {
1288 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
1289 $flags{'NOTES'} = \%flaginfo;
1291 my ($odues, $itemsoverdue)
1292 = checkoverdues($env, $patroninformation->{'borrowernumber'}, $dbh);
1295 $flaginfo{'message'} = "Yes";
1296 $flaginfo{'itemlist'} = $itemsoverdue;
1297 foreach (sort {$a->{'date_due'} cmp $b->{'date_due'}} @$itemsoverdue) {
1298 $flaginfo{'itemlisttext'}.="$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
1300 $flags{'ODUES'} = \%flaginfo;
1302 my ($nowaiting, $itemswaiting)
1303 = CheckWaiting($patroninformation->{'borrowernumber'});
1304 if ($nowaiting > 0) {
1306 $flaginfo{'message'} = "Reserved items available";
1307 $flaginfo{'itemlist'} = $itemswaiting;
1308 $flags{'WAITING'} = \%flaginfo;
1316 # From Main.pm, modified to return a list of overdueitems, in addition to a count
1317 #checks whether a borrower has overdue items
1318 my ($env, $bornum, $dbh)=@_;
1319 my @datearr = localtime;
1320 my $today = ($datearr[5] + 1900)."-".($datearr[4]+1)."-".$datearr[3];
1323 my $sth = $dbh->prepare("SELECT * FROM issues,biblio,biblioitems,items
1324 WHERE items.biblioitemnumber = biblioitems.biblioitemnumber
1325 AND items.biblionumber = biblio.biblionumber
1326 AND issues.itemnumber = items.itemnumber
1327 AND issues.borrowernumber = ?
1328 AND issues.returndate is NULL
1329 AND issues.date_due < ?");
1330 $sth->execute($bornum,$today);
1331 while (my $data = $sth->fetchrow_hashref) {
1332 push (@overdueitems, $data);
1336 return ($count, \@overdueitems);
1340 sub currentborrower {
1341 # Original subroutine for Circ2.pm
1342 my ($itemnumber) = @_;
1343 my $dbh = C4::Context->dbh;
1344 my $q_itemnumber = $dbh->quote($itemnumber);
1345 my $sth=$dbh->prepare("select borrowers.borrowernumber from
1346 issues,borrowers where issues.itemnumber=$q_itemnumber and
1347 issues.borrowernumber=borrowers.borrowernumber and issues.returndate is
1350 my ($borrower) = $sth->fetchrow;
1354 # FIXME - Not exported, but used in 'updateitem.pl' anyway.
1355 sub checkreserve_to_delete {
1356 # Stolen from Main.pm
1357 # Check for reserves for biblio
1358 my ($env,$dbh,$itemnum)=@_;
1360 my $sth = $dbh->prepare("select * from reserves,items
1361 where (items.itemnumber = ?)
1362 and (reserves.cancellationdate is NULL)
1363 and (items.biblionumber = reserves.biblionumber)
1364 and ((reserves.found = 'W')
1365 or (reserves.found is null))
1366 order by priority");
1367 $sth->execute($itemnum);
1369 my $data=$sth->fetchrow_hashref;
1370 while ($data && $resbor eq '') {
1372 my $const = $data->{'constrainttype'};
1373 if ($const eq "a") {
1374 $resbor = $data->{'borrowernumber'};
1377 my $csth = $dbh->prepare("select * from reserveconstraints,items
1378 where (borrowernumber=?)
1380 and reserveconstraints.biblionumber=?
1381 and (items.itemnumber=? and
1382 items.biblioitemnumber = reserveconstraints.biblioitemnumber)");
1383 $csth->execute($data->{'borrowernumber'},$data->{'biblionumber'},$data->{'reservedate'},$itemnum);
1384 if (my $cdata=$csth->fetchrow_hashref) {$found = 1;}
1385 if ($const eq 'o') {
1386 if ($found eq 1) {$resbor = $data->{'borrowernumber'};}
1388 if ($found eq 0) {$resbor = $data->{'borrowernumber'};}
1392 $data=$sth->fetchrow_hashref;
1395 return ($resbor,$resrec);
1398 =head2 currentissues
1400 $issues = ¤tissues($env, $borrower);
1402 Returns a list of books currently on loan to a patron.
1404 If C<$env-E<gt>{todaysissues}> is set and true, C<¤tissues> only
1405 returns information about books issued today. If
1406 C<$env-E<gt>{nottodaysissues}> is set and true, C<¤tissues> only
1407 returns information about books issued before today. If both are
1408 specified, C<$env-E<gt>{todaysissues}> is ignored. If neither is
1409 specified, C<¤tissues> returns all of the patron's issues.
1411 C<$borrower->{borrowernumber}> is the borrower number of the patron
1412 whose issues we want to list.
1414 C<¤tissues> returns a PHP-style array: C<$issues> is a
1415 reference-to-hash whose keys are integers in the range 1...I<n>, where
1416 I<n> is the number of items on issue (either today or before today).
1417 C<$issues-E<gt>{I<n>}> is a reference-to-hash whose keys are all of
1418 the fields of the biblio, biblioitems, items, and issues fields of the
1419 Koha database for that particular item.
1425 # New subroutine for Circ2.pm
1426 my ($env, $borrower) = @_;
1427 my $dbh = C4::Context->dbh;
1430 my $borrowernumber = $borrower->{'borrowernumber'};
1433 # Figure out whether to get the books issued today, or earlier.
1434 # FIXME - $env->{todaysissues} and $env->{nottodaysissues} can
1435 # both be specified, but are mutually-exclusive. This is bogus.
1436 # Make this a flag. Or better yet, return everything in (reverse)
1437 # chronological order and let the caller figure out which books
1438 # were issued today.
1439 if ($env->{'todaysissues'}) {
1441 # $today = POSIX::strftime("%Y%m%d", localtime);
1442 # FIXME - Since $today will be used in either case, move it
1443 # out of the two if-blocks.
1444 my @datearr = localtime(time());
1445 my $today = (1900+$datearr[5]).sprintf "%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
1446 # FIXME - MySQL knows about dates. Just use
1447 # and issues.timestamp = curdate();
1448 $crit=" and issues.timestamp like '$today%' ";
1450 if ($env->{'nottodaysissues'}) {
1452 # $today = POSIX::strftime("%Y%m%d", localtime);
1453 # FIXME - Since $today will be used in either case, move it
1454 # out of the two if-blocks.
1455 my @datearr = localtime(time());
1456 my $today = (1900+$datearr[5]).sprintf "%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
1457 # FIXME - MySQL knows about dates. Just use
1458 # and issues.timestamp < curdate();
1459 $crit=" and !(issues.timestamp like '$today%') ";
1462 # FIXME - Does the caller really need every single field from all
1464 my $sth=$dbh->prepare("select * from issues,items,biblioitems,biblio where
1465 borrowernumber=? and issues.itemnumber=items.itemnumber and
1466 items.biblionumber=biblio.biblionumber and
1467 items.biblioitemnumber=biblioitems.biblioitemnumber and returndate is null
1468 $crit order by issues.date_due");
1469 $sth->execute($borrowernumber);
1470 while (my $data = $sth->fetchrow_hashref) {
1471 # FIXME - The Dewey code is a string, not a number.
1472 $data->{'dewey'}=~s/0*$//;
1473 ($data->{'dewey'} == 0) && ($data->{'dewey'}='');
1475 # $todaysdate = POSIX::strftime("%Y%m%d", localtime)
1476 # or better yet, just reuse $today which was calculated above.
1477 # This function isn't going to run until midnight, is it?
1479 # $todaysdate = POSIX::strftime("%Y-%m-%d", localtime)
1480 # if ($data->{'date_due'} lt $todaysdate)
1482 # Either way, the date should be be formatted outside of the
1484 my @datearr = localtime(time());
1485 my $todaysdate = (1900+$datearr[5]).sprintf ("%0.2d", ($datearr[4]+1)).sprintf ("%0.2d", $datearr[3]);
1486 my $datedue=$data->{'date_due'};
1488 if ($datedue < $todaysdate) {
1489 $data->{'overdue'}=1;
1491 my $itemnumber=$data->{'itemnumber'};
1492 # FIXME - Consecutive integers as hash keys? You have GOT to
1493 # be kidding me! Use an array, fercrissakes!
1494 $currentissues{$counter}=$data;
1498 return(\%currentissues);
1503 $issues = &getissues($borrowernumber);
1505 Returns the set of books currently on loan to a patron.
1507 C<$borrowernumber> is the patron's borrower number.
1509 C<&getissues> returns a PHP-style array: C<$issues> is a
1510 reference-to-hash whose keys are integers in the range 0..I<n>-1,
1511 where I<n> is the number of books the patron currently has on loan.
1513 The values of C<$issues> are references-to-hash whose keys are
1514 selected fields from the issues, items, biblio, and biblioitems tables
1515 of the Koha database.
1520 # New subroutine for Circ2.pm
1521 my ($borrower) = @_;
1522 my $dbh = C4::Context->dbh;
1523 my $borrowernumber = $borrower->{'borrowernumber'};
1525 my $select = "SELECT items.*,issues.timestamp AS timestamp,
1526 issues.date_due AS date_due,
1527 items.barcode AS barcode,
1528 biblio.title AS title,
1529 biblio.author AS author,
1530 biblioitems.dewey AS dewey,
1531 itemtypes.description AS itemtype,
1532 biblioitems.subclass AS subclass,
1533 biblioitems.classification AS classification
1534 FROM issues,items,biblioitems,biblio, itemtypes
1535 WHERE issues.borrowernumber = ?
1536 AND issues.itemnumber = items.itemnumber
1537 AND items.biblionumber = biblio.biblionumber
1538 AND items.biblioitemnumber = biblioitems.biblioitemnumber
1539 AND itemtypes.itemtype = biblioitems.itemtype
1540 AND issues.returndate IS NULL
1541 ORDER BY issues.date_due";
1543 my $sth=$dbh->prepare($select);
1544 $sth->execute($borrowernumber);
1546 while (my $data = $sth->fetchrow_hashref) {
1547 $data->{'dewey'} =~ s/0*$//;
1548 ($data->{'dewey'} == 0) && ($data->{'dewey'} = '');
1549 # FIXME - The Dewey code is a string, not a number.
1550 # FIXME - Use POSIX::strftime to get a text version of today's
1551 # date. That's what it's for.
1552 # FIXME - Move the date calculation outside of the loop.
1553 my @datearr = localtime(time());
1554 my $todaysdate = (1900+$datearr[5]).sprintf ("%0.2d", ($datearr[4]+1)).sprintf ("%0.2d", $datearr[3]);
1556 # FIXME - Instead of converting the due date to YYYYMMDD, just
1558 # $todaysdate = POSIX::strftime("%Y-%m-%d", localtime);
1560 # if ($date->{date_due} lt $todaysdate)
1561 my $datedue = $data->{'date_due'};
1563 if ($datedue < $todaysdate) {
1564 $data->{'overdue'} = 1;
1566 $currentissues{$counter} = $data;
1568 # FIXME - This is ludicrous. If you want to return an
1569 # array of values, just use an array. That's what
1570 # they're there for.
1573 return(\%currentissues);
1578 #Stolen from Main.pm
1579 # check for reserves waiting
1580 my ($env,$dbh,$bornum)=@_;
1582 my $sth = $dbh->prepare("select * from reserves where (borrowernumber = ?) and (reserves.found='W') and cancellationdate is NULL");
1583 $sth->execute($bornum);
1585 if (my $data=$sth->fetchrow_hashref) {
1586 $itemswaiting[$cnt] =$data;
1590 return ($cnt,\@itemswaiting);
1595 $ok = &renewstatus($env, $dbh, $borrowernumber, $itemnumber);
1597 Find out whether a borrowed item may be renewed.
1601 C<$dbh> is a DBI handle to the Koha database.
1603 C<$borrowernumber> is the borrower number of the patron who currently
1604 has the item on loan.
1606 C<$itemnumber> is the number of the item to renew.
1608 C<$renewstatus> returns a true value iff the item may be renewed. The
1609 item must currently be on loan to the specified borrower; renewals
1610 must be allowed for the item's type; and the borrower must not have
1611 already renewed the loan.
1616 # check renewal status
1617 my ($env,$bornum,$itemno)=@_;
1618 my $dbh = C4::Context->dbh;
1621 # Look in the issues table for this item, lent to this borrower,
1622 # and not yet returned.
1624 # FIXME - I think this function could be redone to use only one SQL call.
1625 my $sth1 = $dbh->prepare("select * from issues
1626 where (borrowernumber = ?)
1627 and (itemnumber = ?)
1628 and returndate is null");
1629 $sth1->execute($bornum,$itemno);
1630 if (my $data1 = $sth1->fetchrow_hashref) {
1631 # Found a matching item
1633 # See if this item may be renewed. This query is convoluted
1634 # because it's a bit messy: given the item number, we need to find
1635 # the biblioitem, which gives us the itemtype, which tells us
1636 # whether it may be renewed.
1637 my $sth2 = $dbh->prepare("select renewalsallowed from items,biblioitems,itemtypes
1638 where (items.itemnumber = ?)
1639 and (items.biblioitemnumber = biblioitems.biblioitemnumber)
1640 and (biblioitems.itemtype = itemtypes.itemtype)");
1641 $sth2->execute($itemno);
1642 if (my $data2=$sth2->fetchrow_hashref) {
1643 $renews = $data2->{'renewalsallowed'};
1645 if ($renews && $renews > $data1->{'renewals'}) {
1649 my ($resfound, $resrec) = CheckReserves($itemno);
1653 ($resfound, $resrec) = CheckReserves($itemno);
1665 &renewbook($env, $borrowernumber, $itemnumber, $datedue);
1669 C<$env-E<gt>{branchcode}> is the code of the branch where the
1670 renewal is taking place.
1672 C<$env-E<gt>{usercode}> is the value to log in C<statistics.usercode>
1673 in the Koha database.
1675 C<$borrowernumber> is the borrower number of the patron who currently
1678 C<$itemnumber> is the number of the item to renew.
1680 C<$datedue> can be used to set the due date. If C<$datedue> is the
1681 empty string, C<&renewbook> will calculate the due date automatically
1682 from the book's item type. If you wish to set the due date manually,
1683 C<$datedue> should be in the form YYYY-MM-DD.
1688 # mark book as renewed
1689 my ($env,$bornum,$itemno,$datedue)=@_;
1690 my $dbh = C4::Context->dbh;
1692 # If the due date wasn't specified, calculate it by adding the
1693 # book's loan length to today's date.
1694 if ($datedue eq "" ) {
1695 #debug_msg($env, "getting date");
1696 my $iteminformation = getiteminformation($env, $itemno,0);
1697 my $borrower = getpatroninformation($env,$bornum,0);
1698 my $loanlength = getLoanLength($borrower->{'categorycode'},$iteminformation->{'itemtype'},$borrower->{'branchcode'});
1699 $datedue = UnixDate(DateCalc("today","$loanlength days"),"%Y-%m-%d");
1702 # Find the issues record for this book
1703 my $sth=$dbh->prepare("select * from issues where borrowernumber=? and itemnumber=? and returndate is null");
1704 $sth->execute($bornum,$itemno);
1705 my $issuedata=$sth->fetchrow_hashref;
1708 # Update the issues record to have the new due date, and a new count
1709 # of how many times it has been renewed.
1710 my $renews = $issuedata->{'renewals'} +1;
1711 $sth=$dbh->prepare("update issues set date_due = ?, renewals = ?
1712 where borrowernumber=? and itemnumber=? and returndate is null");
1713 $sth->execute($datedue,$renews,$bornum,$itemno);
1717 UpdateStats($env,$env->{'branchcode'},'renew','','',$itemno);
1719 # Charge a new rental fee, if applicable?
1720 my ($charge,$type)=calc_charges($env, $itemno, $bornum);
1722 my $accountno=getnextacctno($env,$bornum,$dbh);
1723 my $item=getiteminformation($env, $itemno);
1724 $sth=$dbh->prepare("Insert into accountlines (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding,itemnumber)
1725 values (?,?,now(),?,?,?,?,?)");
1726 $sth->execute($bornum,$accountno,$charge,"Renewal of Rental Item $item->{'title'} $item->{'barcode'}",'Rent',$charge,$itemno);
1738 ($charge, $item_type) = &calc_charges($env, $itemnumber, $borrowernumber);
1740 Calculate how much it would cost for a given patron to borrow a given
1741 item, including any applicable discounts.
1745 C<$itemnumber> is the item number of item the patron wishes to borrow.
1747 C<$borrowernumber> is the patron's borrower number.
1749 C<&calc_charges> returns two values: C<$charge> is the rental charge,
1750 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1756 # calculate charges due
1757 my ($env, $itemno, $bornum)=@_;
1759 my $dbh = C4::Context->dbh;
1762 # Get the book's item type and rental charge (via its biblioitem).
1763 my $sth1= $dbh->prepare("select itemtypes.itemtype,rentalcharge from items,biblioitems,itemtypes
1764 where (items.itemnumber =?)
1765 and (biblioitems.biblioitemnumber = items.biblioitemnumber)
1766 and (biblioitems.itemtype = itemtypes.itemtype)");
1767 $sth1->execute($itemno);
1768 my $data1=$sth1->fetchrow_hashref;
1769 $item_type = $data1->{'itemtype'};
1770 $charge = $data1->{'rentalcharge'};
1772 return ($charge,$item_type);
1776 # FIXME - A virtually identical function appears in
1777 # C4::Circulation::Issues. Pick one and stick with it.
1779 #Stolen from Issues.pm
1780 my ($env,$dbh,$itemno,$bornum,$charge) = @_;
1781 my $nextaccntno = getnextacctno($env,$bornum,$dbh);
1782 my $sth = $dbh->prepare(<<EOT);
1783 INSERT INTO accountlines
1784 (borrowernumber, itemnumber, accountno,
1785 date, amount, description, accounttype,
1788 now(), ?, 'Rental', 'Rent',
1791 $sth->execute($bornum, $itemno, $nextaccntno, $charge, $charge);
1798 ($status, $record) = &find_reserves($itemnumber);
1800 Looks up an item in the reserves.
1802 C<$itemnumber> is the itemnumber to look up.
1804 C<$status> is true iff the search was successful.
1806 C<$record> is a reference-to-hash describing the reserve. Its keys are
1807 the fields from the reserves table of the Koha database.
1811 # FIXME - This API is bogus: just return the record, or undef if none
1813 # FIXME - There's also a &C4::Circulation::Returns::find_reserves, but
1814 # that one looks rather different.
1816 # Stolen from Returns.pm
1819 my $dbh = C4::Context->dbh;
1820 my ($itemdata) = getiteminformation(\%env, $itemno,0);
1821 my $bibno = $dbh->quote($itemdata->{'biblionumber'});
1822 my $bibitm = $dbh->quote($itemdata->{'biblioitemnumber'});
1823 my $sth = $dbh->prepare("select * from reserves where ((found = 'W') or (found is null)) and biblionumber = ? and cancellationdate is NULL order by priority, reservedate");
1824 $sth->execute($bibno);
1830 # FIXME - I'm not really sure what's going on here, but since we
1831 # only want one result, wouldn't it be possible (and far more
1832 # efficient) to do something clever in SQL that only returns one
1834 while (($resrec = $sth->fetchrow_hashref) && (not $resfound)) {
1835 # FIXME - Unlike Pascal, Perl allows you to exit loops
1836 # early. Take out the "&& (not $resfound)" and just
1837 # use "last" at the appropriate point in the loop.
1838 # (Oh, and just in passing: if you'd used "!" instead
1839 # of "not", you wouldn't have needed the parentheses.)
1841 my $brn = $dbh->quote($resrec->{'borrowernumber'});
1842 my $rdate = $dbh->quote($resrec->{'reservedate'});
1843 my $bibno = $dbh->quote($resrec->{'biblionumber'});
1844 if ($resrec->{'found'} eq "W") {
1845 if ($resrec->{'itemnumber'} eq $itemno) {
1849 # FIXME - Use 'elsif' to avoid unnecessary indentation.
1850 if ($resrec->{'constrainttype'} eq "a") {
1853 my $consth = $dbh->prepare("select * from reserveconstraints where borrowernumber = ? and reservedate = ? and biblionumber = ? and biblioitemnumber = ?");
1854 $consth->execute($brn,$rdate,$bibno,$bibitm);
1855 if (my $conrec = $consth->fetchrow_hashref) {
1856 if ($resrec->{'constrainttype'} eq "o") {
1864 my $updsth = $dbh->prepare("update reserves set found = 'W', itemnumber = ? where borrowernumber = ? and reservedate = ? and biblionumber = ?");
1865 $updsth->execute($itemno,$brn,$rdate,$bibno);
1867 # FIXME - "last;" here to break out of the loop early.
1871 return ($resfound,$lastrec);
1875 my ($year, $month, $day) = @_;
1878 if ($year && $month && $day){
1879 if (($year eq 0 ) && ($month eq 0) && ($year eq 0)) {
1880 # $env{'datedue'}='';
1882 if (($year eq 0) || ($month eq 0) || ($year eq 0)) {
1885 if (($day>30) && (($month==4) || ($month==6) || ($month==9) || ($month==11))) {
1886 $invalidduedate = 1;
1888 elsif (($day > 29) && ($month == 2)) {
1891 elsif (($month == 2) && ($day > 28) && (($year%4) && ((!($year%100) || ($year%400))))) {
1895 $date="$year-$month-$day";
1900 return ($date, $invalidduedate);
1911 Koha Developement team <info@koha.org>