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
39 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
41 # set the version for version checking
46 C4::Circulation::Circ2 - Koha circulation module
50 use C4::Circulation::Circ2;
54 The functions in this module deal with circulation, issues, and
55 returns, as well as general information about the library.
56 Also deals with stocktaking.
65 @EXPORT = qw(&getpatroninformation
66 ¤tissues &getissues &getiteminformation
67 &canbookbeissued &issuebook &returnbook &find_reserves &transferbook &decode
68 &calc_charges &listitemsforinventory &itemseen &fixdate);
70 # &getbranches &getprinters &getbranch &getprinter => moved to C4::Koha.pm
75 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
76 C<$itemnum> is the item number
82 my $dbh = C4::Context->dbh;
83 my $sth = $dbh->prepare("update items set itemlost=0, datelastseen = now() where items.itemnumber = ?");
84 $sth->execute($itemnum);
88 sub listitemsforinventory {
89 my ($minlocation,$maxlocation,$datelastseen,$offset,$size) = @_;
90 my $dbh = C4::Context->dbh;
91 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");
92 $sth->execute($minlocation,$maxlocation,$datelastseen);
94 while (my $row = $sth->fetchrow_hashref) {
95 $offset-- if ($offset);
96 if ((!$offset) && $size) {
104 =head2 getpatroninformation
106 ($borrower, $flags) = &getpatroninformation($env, $borrowernumber, $cardnumber);
108 Looks up a patron and returns information about him or her. If
109 C<$borrowernumber> is true (nonzero), C<&getpatroninformation> looks
110 up the borrower by number; otherwise, it looks up the borrower by card
113 C<$env> is effectively ignored, but should be a reference-to-hash.
115 C<$borrower> is a reference-to-hash whose keys are the fields of the
116 borrowers table in the Koha database. In addition,
117 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
118 about the patron. Its keys act as flags :
120 if $borrower->{flags}->{LOST} {
121 # Patron's card was reported lost
124 Each flag has a C<message> key, giving a human-readable explanation of
125 the flag. If the state of a flag means that the patron should not be
126 allowed to borrow any more books, then it will have a C<noissues> key
129 The possible flags are:
135 Shows the patron's credit or debt, if any.
143 (Gone, no address.) Set if the patron has left without giving a
152 Set if the patron's card has been reported as lost.
160 Set if the patron has been debarred.
168 Any additional notes about the patron.
176 Set if the patron has overdue items. This flag has several keys:
178 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
179 overdue items. Its elements are references-to-hash, each describing an
180 overdue item. The keys are selected fields from the issues, biblio,
181 biblioitems, and items tables of the Koha database.
183 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
184 the overdue items, one per line.
192 Set if any items that the patron has reserved are available.
194 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
195 available items. Each element is a reference-to-hash whose keys are
196 fields from the reserves table of the Koha database.
205 sub getpatroninformation {
207 my ($env, $borrowernumber,$cardnumber) = @_;
208 my $dbh = C4::Context->dbh;
211 if ($borrowernumber) {
212 $sth = $dbh->prepare("select * from borrowers where borrowernumber=?");
213 $sth->execute($borrowernumber);
214 } elsif ($cardnumber) {
215 $sth = $dbh->prepare("select * from borrowers where cardnumber=?");
216 $sth->execute($cardnumber);
218 $env->{'apierror'} = "invalid borrower information passed to getpatroninformation subroutine";
221 my $borrower = $sth->fetchrow_hashref;
222 my $amount = checkaccount($env, $borrowernumber, $dbh);
223 $borrower->{'amountoutstanding'} = $amount;
224 my $flags = patronflags($env, $borrower, $dbh);
227 $sth=$dbh->prepare("select bit,flag from userflags");
229 while (my ($bit, $flag) = $sth->fetchrow) {
230 if ($borrower->{'flags'} & 2**$bit) {
231 $accessflagshash->{$flag}=1;
235 $borrower->{'flags'}=$flags;
236 $borrower->{'authflags'} = $accessflagshash;
237 return ($borrower); #, $flags, $accessflagshash);
244 =head3 $str = &decode($chunk);
248 Decodes a segment of a string emitted by a CueCat barcode scanner and
257 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
260 my $seq = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
261 my @s = map { index($seq,$_); } split(//,$encoded);
276 my $n = (($s[0] << 6 | $s[1]) << 6 | $s[2]) << 6 | $s[3];
277 $r .=chr(($n >> 16) ^ 67) .
278 chr(($n >> 8 & 255) ^ 67) .
279 chr(($n & 255) ^ 67);
282 $r = substr($r,0,length($r)-$l);
286 =head2 getiteminformation
290 $item = &getiteminformation($env, $itemnumber, $barcode);
292 Looks up information about an item, given either its item number or
293 its barcode. If C<$itemnumber> is a nonzero value, it is used;
294 otherwise, C<$barcode> is used.
296 C<$env> is effectively ignored, but should be a reference-to-hash.
298 C<$item> is a reference-to-hash whose keys are fields from the biblio,
299 items, and biblioitems tables of the Koha database. It may also
300 contain the following keys:
306 The due date on this item, if it has been borrowed and not returned
307 yet. The date is in YYYY-MM-DD format.
315 The length of time for which the item can be borrowed, in days.
323 True if the item may not be borrowed.
332 sub getiteminformation {
333 # returns a hash of item information given either the itemnumber or the barcode
334 my ($env, $itemnumber, $barcode) = @_;
335 my $dbh = C4::Context->dbh;
338 $sth=$dbh->prepare("select * from biblio,items,biblioitems where items.itemnumber=? and biblio.biblionumber=items.biblionumber and biblioitems.biblioitemnumber = items.biblioitemnumber");
339 $sth->execute($itemnumber);
341 $sth=$dbh->prepare("select * from biblio,items,biblioitems where items.barcode=? and biblio.biblionumber=items.biblionumber and biblioitems.biblioitemnumber = items.biblioitemnumber");
342 $sth->execute($barcode);
344 $env->{'apierror'}="getiteminformation() subroutine must be called with either an itemnumber or a barcode";
348 my $iteminformation=$sth->fetchrow_hashref;
350 if ($iteminformation) {
351 $sth=$dbh->prepare("select date_due from issues where itemnumber=? and isnull(returndate)");
352 $sth->execute($iteminformation->{'itemnumber'});
353 my ($date_due) = $sth->fetchrow;
354 $iteminformation->{'date_due'}=$date_due;
356 ($iteminformation->{'dewey'} == 0) && ($iteminformation->{'dewey'}='');
357 $sth=$dbh->prepare("select * from itemtypes where itemtype=?");
358 $sth->execute($iteminformation->{'itemtype'});
359 my $itemtype=$sth->fetchrow_hashref;
360 $iteminformation->{'loanlength'}=$itemtype->{'loanlength'};
361 # if specific item notforloan, don't use itemtype notforloan field.
362 # otherwise, use itemtype notforloan value to see if item can be issued.
363 $iteminformation->{'notforloan'}=$itemtype->{'notforloan'} unless $iteminformation->{'notforloan'};
366 return($iteminformation);
373 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
375 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
377 C<$newbranch> is the code for the branch to which the item should be transferred.
379 C<$barcode> is the barcode of the item to be transferred.
381 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
382 Otherwise, if an item is reserved, the transfer fails.
384 Returns three values:
388 is true if the transfer was successful.
392 is a reference-to-hash which may have any of the following keys:
398 There is no item in the catalog with the given barcode. The value is C<$barcode>.
402 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.
404 C<DestinationEqualsHolding>
406 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.
410 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.
414 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>.
418 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
429 # FIXME - This function tries to do too much, and its API is clumsy.
430 # If it didn't also return books, it could be used to change the home
431 # branch of a book while the book is on loan.
433 # Is there any point in returning the item information? The caller can
434 # look that up elsewhere if ve cares.
436 # This leaves the ($dotransfer, $messages) tuple. This seems clumsy.
437 # If the transfer succeeds, that's all the caller should need to know.
438 # Thus, this function could simply return 1 or 0 to indicate success
439 # or failure, and set $C4::Circulation::Circ2::errmsg in case of
440 # failure. Or this function could return undef if successful, and an
441 # error message in case of failure (this would feel more like C than
444 # transfer book code....
445 my ($tbr, $barcode, $ignoreRs) = @_;
449 my $branches = getbranches();
450 my $iteminformation = getiteminformation(\%env, 0, $barcode);
452 if (not $iteminformation) {
453 $messages->{'BadBarcode'} = $barcode;
456 # get branches of book...
457 my $hbr = $iteminformation->{'homebranch'};
458 my $fbr = $iteminformation->{'holdingbranch'};
460 if ($branches->{$hbr}->{'PE'}) {
461 $messages->{'IsPermanent'} = $hbr;
463 # can't transfer book if is already there....
464 # FIXME - Why not? Shouldn't it trivially succeed?
466 $messages->{'DestinationEqualsHolding'} = 1;
469 # check if it is still issued to someone, return it...
470 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
471 if ($currentborrower) {
472 returnbook($barcode, $fbr);
473 $messages->{'WasReturned'} = $currentborrower;
476 # FIXME - Don't call &CheckReserves unless $ignoreRs is true.
477 # That'll save a database query.
478 my ($resfound, $resrec) = CheckReserves($iteminformation->{'itemnumber'});
479 if ($resfound and not $ignoreRs) {
480 $resrec->{'ResFound'} = $resfound;
481 $messages->{'ResFound'} = $resrec;
484 #actually do the transfer....
486 dotransfer($iteminformation->{'itemnumber'}, $fbr, $tbr);
487 $messages->{'WasTransfered'} = 1;
489 return ($dotransfer, $messages, $iteminformation);
493 # FIXME - This is only used in &transferbook. Why bother making it a
496 my ($itm, $fbr, $tbr) = @_;
497 my $dbh = C4::Context->dbh;
498 $itm = $dbh->quote($itm);
499 $fbr = $dbh->quote($fbr);
500 $tbr = $dbh->quote($tbr);
501 #new entry in branchtransfers....
502 $dbh->do("INSERT INTO branchtransfers (itemnumber, frombranch, datearrived, tobranch)
503 VALUES ($itm, $fbr, now(), $tbr)");
504 #update holdingbranch in items .....
505 $dbh->do("UPDATE items set holdingbranch = $tbr WHERE items.itemnumber = $itm");
510 =head2 canbookbeissued
512 Check if a book can be issued.
514 my ($issuingimpossible,$needsconfirmation) = canbookbeissued($env,$borrower,$barcode,$year,$month,$day);
518 C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
520 C<$borrower> hash with borrower informations (from getpatroninformation)
522 C<$barcode> is the bar code of the book being issued.
524 C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
532 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
533 Possible values are :
537 sticky due date is invalid
541 borrower gone with no address
545 borrower declared it's card lost
551 =head3 UNKNOWN_BARCODE
565 item is restricted (set by ??)
569 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
570 Possible values are :
578 renewing, not issuing
580 =head3 ISSUED_TO_ANOTHER
582 issued to someone else.
586 reserved for someone else.
590 sticky due date is invalid
594 if the borrower borrows to much things
598 # check if a book can be issued.
599 # returns an array with errors if any
601 sub HowManyBurrows ($){
602 my $borrower = shift;
603 my $dbh = C4::Context->dbh;
605 my $sth = $dbh->prepare('select COUNT(borrowernumber) nombre_livre_emprunte from issues where borrowernumber = ?');
606 $sth->execute($borrower->{'borrowernumber'});
607 my $data = $sth->fetchrow;
611 sub NumberBurrowsOk(@)
613 (my $biblionbr, my $cat) = @_;
614 my $dbh = C4::Context->dbh;
616 my $sth = $dbh->prepare('select itemtype from biblioitems where biblionumber = ?');
617 $sth->execute($biblionbr);
618 my $data = $sth->fetchrow;
619 $sth = $dbh->prepare('select maxissueqty from issuingrules where categorycode = ? and itemtype = ?');
620 $sth->execute($cat, $data);
621 my $value = $sth->fetchrow;
622 return $value if (defined($value));
623 $sth = $dbh->prepare('select maxissueqty from issuingrules where categorycode = "*" and itemtype = ?');
624 $sth->execute($data);
625 $value = $sth->fetchrow;
626 return $value if (defined($value));
627 $sth = $dbh->prepare('select maxissueqty from issuingrules where categorycode = ? and itemtype = "*"');
629 $value = $sth->fetchrow;
630 return $value if (defined($value));
631 $sth = $dbh->prepare('select maxissueqty from issuingrules where categorycode = "*" and itemtype = "*"');
633 $value = $sth->fetchrow;
634 return $value if (defined($value));
635 return 5; # valeur max par default si la base est endommagee
638 sub canbookbeissued {
639 my ($env,$borrower,$barcode,$year,$month,$day) = @_;
640 warn "CHECKING CANBEISSUED for $borrower->{'borrowernumber'}, $barcode";
641 my %needsconfirmation; # filled with problems that needs confirmations
642 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
643 my $iteminformation = getiteminformation($env, 0, $barcode);
644 my $dbh = C4::Context->dbh;
648 my ($duedate, $invalidduedate) = fixdate($year, $month, $day);
649 $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
654 if ($borrower->{flags}->{'gonenoaddress'}) {
655 $issuingimpossible{GNA} = 1;
657 if ($borrower->{flags}->{'lost'}) {
658 $issuingimpossible{CARD_LOST} = 1;
660 if ($borrower->{flags}->{'debarred'}) {
661 $issuingimpossible{DEBARRED} = 1;
668 my $amount = checkaccount($env,$borrower->{'borrowernumber'}, $dbh,$duedate);
670 $needsconfirmation{DEBT} = $amount;
675 # JB34 CHECK IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
678 $needsconfirmation{TOO_MUCH} = 1
679 if (HowManyBurrows($borrower) > NumberBurrowsOk($iteminformation->{'biblionumber'},
680 $borrower->{'categorycode'}));
685 unless ($iteminformation) {
686 $issuingimpossible{UNKNOWN_BARCODE} = 1;
688 if ($iteminformation->{'notforloan'} == 1) {
689 $issuingimpossible{NOT_FOR_LOAN} = 1;
691 if ($iteminformation->{'itemtype'} eq 'REF') {
692 $issuingimpossible{NOT_FOR_LOAN} = 1;
694 if ($iteminformation->{'wthdrawn'} == 1) {
695 $issuingimpossible{WTHDRAWN} = 1;
697 if ($iteminformation->{'restricted'} == 1) {
698 $issuingimpossible{RESTRICTED} = 1;
704 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
706 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
707 if ($currentborrower eq $borrower->{'borrowernumber'}) {
708 # Already issued to current borrower. Ask whether the loan should
710 my ($renewstatus) = renewstatus($env,$dbh,$borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
711 if ($renewstatus == 0) { # no more renewals allowed
712 $issuingimpossible{NO_MORE_RENEWALS} = 1;
714 $needsconfirmation{RENEW_ISSUE} = 1;
716 } elsif ($currentborrower) {
717 # issued to someone else
718 my $currborinfo = getpatroninformation(0,$currentborrower);
719 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
720 $needsconfirmation{ISSUED_TO_ANOTHER} = "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
722 # See if the item is on reserve.
723 my ($restype, $res) = CheckReserves($iteminformation->{'itemnumber'});
725 my $resbor = $res->{'borrowernumber'};
726 if ($resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting") {
727 # The item is on reserve and waiting, but has been
728 # reserved by some other patron.
729 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
730 my $branches = getbranches();
731 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
732 $needsconfirmation{RESERVE_WAITING} = "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
733 } elsif ($restype eq "Reserved") {
734 # The item is on reserve for someone else.
735 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
736 my $branches = getbranches();
737 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
738 $needsconfirmation{RESERVED} = "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
741 return(\%issuingimpossible,\%needsconfirmation);
746 Issue a book. Does no check, they are done in canbookbeissued. If we reach this sub, it means the user confirmed if needed.
748 &issuebook($env,$borrower,$barcode,$date)
752 C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
754 C<$borrower> hash with borrower informations (from getpatroninformation)
756 C<$barcode> is the bar code of the book being issued.
758 C<$date> contains the max date of return. calculated if empty.
763 # issuing book. We already have checked it can be issued, so, just issue it !
766 my ($env,$borrower,$barcode,$date) = @_;
767 my $dbh = C4::Context->dbh;
768 # my ($borrower, $flags) = &getpatroninformation($env, $borrowernumber, 0);
769 my $iteminformation = getiteminformation($env, 0, $barcode);
770 # warn "B : ".$borrower->{borrowernumber}." / I : ".$iteminformation->{'itemnumber'};
772 # check if we just renew the issue.
774 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
775 if ($currentborrower eq $borrower->{'borrowernumber'}) {
776 my ($charge,$itemtype) = calc_charges($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'});
778 createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge);
779 $iteminformation->{'charge'} = $charge;
781 &UpdateStats($env,$env->{'branchcode'},'renew',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
782 renewbook($env,$dbh, $borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
787 if ($currentborrower ne '') {
788 # This book is currently on loan, but not to the person
789 # who wants to borrow it now. mark it returned before issuing to the new borrower
790 returnbook($iteminformation->{'barcode'}, $env->{'branchcode'});
792 # See if the item is on reserve.
793 my ($restype, $res) = CheckReserves($iteminformation->{'itemnumber'});
795 my $resbor = $res->{'borrowernumber'};
796 if ($resbor eq $borrower->{'borrowernumber'}) {
797 # The item is on reserve to the current patron
799 } elsif ($restype eq "Waiting") {
800 # The item is on reserve and waiting, but has been
801 # reserved by some other patron.
802 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
803 my $branches = getbranches();
804 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
805 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
806 } elsif ($restype eq "Reserved") {
807 # The item is on reserve for someone else.
808 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
809 my $branches = getbranches();
810 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
811 my $tobrcd = ReserveWaiting($res->{'itemnumber'}, $res->{'borrowernumber'});
812 transferbook($tobrcd,$barcode, 1);
815 # Record in the database the fact that the book was issued.
816 my $sth=$dbh->prepare("insert into issues (borrowernumber, itemnumber, date_due, branchcode) values (?,?,?,?)");
817 my $loanlength = $iteminformation->{loanlength} || 21;
818 my $datedue=time+($loanlength)*86400;
819 my @datearr = localtime($datedue);
820 my $dateduef = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
821 if ($env->{'datedue'}) {
822 $dateduef=$env->{'datedue'};
824 $sth->execute($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'}, $dateduef, $env->{'branchcode'});
826 $iteminformation->{'issues'}++;
827 $sth=$dbh->prepare("update items set issues=? where itemnumber=?");
828 $sth->execute($iteminformation->{'issues'},$iteminformation->{'itemnumber'});
830 &itemseen($iteminformation->{'itemnumber'});
831 # If it costs to borrow this book, charge it to the patron's account.
832 my ($charge,$itemtype)=calc_charges($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'});
834 createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge);
835 $iteminformation->{'charge'}=$charge;
837 # Record the fact that this book was issued.
838 &UpdateStats($env,$env->{'branchcode'},'issue',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
844 ($doreturn, $messages, $iteminformation, $borrower) =
845 &returnbook($barcode, $branch);
849 C<$barcode> is the bar code of the book being returned. C<$branch> is
850 the code of the branch where the book is being returned.
852 C<&returnbook> returns a list of four items:
854 C<$doreturn> is true iff the return succeeded.
856 C<$messages> is a reference-to-hash giving the reason for failure:
862 No item with this barcode exists. The value is C<$barcode>.
866 The book is not currently on loan. The value is C<$barcode>.
870 The book's home branch is a permanent collection. If you have borrowed
871 this book, you are not allowed to return it. The value is the code for
872 the book's home branch.
876 This book has been withdrawn/cancelled. The value should be ignored.
880 The item was reserved. The value is a reference-to-hash whose keys are
881 fields from the reserves table of the Koha database, and
882 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
883 either C<Waiting>, C<Reserved>, or 0.
887 C<$borrower> is a reference-to-hash, giving information about the
888 patron who last borrowed the book.
892 # FIXME - This API is bogus. There's no need to return $borrower and
893 # $iteminformation; the caller can ask about those separately, if it
894 # cares (it'd be inefficient to make two database calls instead of
895 # one, but &getpatroninformation and &getiteminformation can be
896 # memoized if this is an issue).
898 # The ($doreturn, $messages) tuple is redundant: if the return
899 # succeeded, that's all the caller needs to know. So &returnbook can
900 # return 1 and 0 on success and failure, and set
901 # $C4::Circulation::Circ2::errmsg to indicate the error. Or it can
902 # return undef for success, and an error message on error (though this
903 # is more C-ish than Perl-ish).
906 my ($barcode, $branch) = @_;
909 my $dbh = C4::Context->dbh;
911 die '$branch not defined' unless defined $branch; # just in case (bug 170)
912 # get information on item
913 my ($iteminformation) = getiteminformation(\%env, 0, $barcode);
914 if (not $iteminformation) {
915 $messages->{'BadBarcode'} = $barcode;
919 my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
920 if ((not $currentborrower) && $doreturn) {
921 $messages->{'NotIssued'} = $barcode;
924 # check if the book is in a permanent collection....
925 my $hbr = $iteminformation->{'homebranch'};
926 my $branches = getbranches();
927 if ($branches->{$hbr}->{'PE'}) {
928 $messages->{'IsPermanent'} = $hbr;
930 # check that the book has been cancelled
931 if ($iteminformation->{'wthdrawn'}) {
932 $messages->{'wthdrawn'} = 1;
935 # update issues, thereby returning book (should push this out into another subroutine
936 my ($borrower) = getpatroninformation(\%env, $currentborrower, 0);
938 my $sth = $dbh->prepare("update issues set returndate = now() where (borrowernumber = ?) and (itemnumber = ?) and (returndate is null)");
939 $sth->execute($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
940 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
942 ($borrower) = getpatroninformation(\%env, $currentborrower, 0);
943 # transfer book to the current branch
944 my ($transfered, $mess, $item) = transferbook($branch, $barcode, 1);
946 $messages->{'WasTransfered'} = 1; # FIXME is the "= 1" right?
948 # fix up the accounts.....
949 if ($iteminformation->{'itemlost'}) {
950 fixaccountforlostandreturned($iteminformation, $borrower);
951 $messages->{'WasLost'} = 1; # FIXME is the "= 1" right?
953 # fix up the overdues in accounts...
954 fixoverduesonreturn($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
956 my ($resfound, $resrec) = CheckReserves($iteminformation->{'itemnumber'});
958 # my $tobrcd = ReserveWaiting($resrec->{'itemnumber'}, $resrec->{'borrowernumber'});
959 $resrec->{'ResFound'} = $resfound;
960 $messages->{'ResFound'} = $resrec;
963 # Record the fact that this book was returned.
964 UpdateStats(\%env, $branch ,'return','0','',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
965 return ($doreturn, $messages, $iteminformation, $borrower);
968 =head2 fixaccountforlostandreturned
970 &fixaccountforlostandreturned($iteminfo,$borrower);
972 Calculates the charge for a book lost and returned (Not exported & used only once)
974 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
976 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
980 sub fixaccountforlostandreturned {
981 my ($iteminfo, $borrower) = @_;
983 my $dbh = C4::Context->dbh;
984 my $itm = $iteminfo->{'itemnumber'};
985 # check for charge made for lost book
986 my $sth = $dbh->prepare("select * from accountlines where (itemnumber = ?) and (accounttype='L' or accounttype='Rep') order by date desc");
988 if (my $data = $sth->fetchrow_hashref) {
989 # writeoff this amount
991 my $amount = $data->{'amount'};
992 my $acctno = $data->{'accountno'};
994 if ($data->{'amountoutstanding'} == $amount) {
995 $offset = $data->{'amount'};
998 $offset = $amount - $data->{'amountoutstanding'};
999 $amountleft = $data->{'amountoutstanding'} - $amount;
1001 my $usth = $dbh->prepare("update accountlines set accounttype = 'LR',amountoutstanding='0'
1002 where (borrowernumber = ?)
1003 and (itemnumber = ?) and (accountno = ?) ");
1004 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1006 #check if any credit is left if so writeoff other accounts
1007 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1008 if ($amountleft < 0){
1011 if ($amountleft > 0){
1012 my $msth = $dbh->prepare("select * from accountlines where (borrowernumber = ?)
1013 and (amountoutstanding >0) order by date");
1014 $msth->execute($data->{'borrowernumber'});
1015 # offset transactions
1018 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1019 if ($accdata->{'amountoutstanding'} < $amountleft) {
1021 $amountleft -= $accdata->{'amountoutstanding'};
1023 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1026 my $thisacct = $accdata->{'accountno'};
1027 my $usth = $dbh->prepare("update accountlines set amountoutstanding= ?
1028 where (borrowernumber = ?)
1029 and (accountno=?)");
1030 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1032 $usth = $dbh->prepare("insert into accountoffsets
1033 (borrowernumber, accountno, offsetaccount, offsetamount)
1036 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1041 if ($amountleft > 0){
1044 my $desc="Book Returned ".$iteminfo->{'barcode'};
1045 $usth = $dbh->prepare("insert into accountlines
1046 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1047 values (?,?,now(),?,?,'CR',?)");
1048 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1050 $usth = $dbh->prepare("insert into accountoffsets
1051 (borrowernumber, accountno, offsetaccount, offsetamount)
1053 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1055 $usth = $dbh->prepare("update items set paidfor='' where itemnumber=?");
1056 $usth->execute($itm);
1063 =head2 fixoverdueonreturn
1065 &fixoverdueonreturn($brn,$itm);
1069 C<$brn> borrowernumber
1075 sub fixoverduesonreturn {
1076 my ($brn, $itm) = @_;
1077 my $dbh = C4::Context->dbh;
1078 # check for overdue fine
1079 my $sth = $dbh->prepare("select * from accountlines where (borrowernumber = ?) and (itemnumber = ?) and (accounttype='FU' or accounttype='O')");
1080 $sth->execute($brn,$itm);
1081 # alter fine to show that the book has been returned
1082 if (my $data = $sth->fetchrow_hashref) {
1083 my $usth=$dbh->prepare("update accountlines set accounttype='F' where (borrowernumber = ?) and (itemnumber = ?) and (acccountno = ?)");
1084 $usth->execute($brn,$itm,$data->{'accountno'});
1093 # NOTE!: If you change this function, be sure to update the POD for
1094 # &getpatroninformation.
1096 # $flags = &patronflags($env, $patron, $dbh);
1099 # {message} Message showing patron's credit or debt
1100 # {noissues} Set if patron owes >$5.00
1101 # {GNA} Set if patron gone w/o address
1102 # {message} "Borrower has no valid address"
1104 # {LOST} Set if patron's card reported lost
1105 # {message} Message to this effect
1107 # {DBARRED} Set is patron is debarred
1108 # {message} Message to this effect
1110 # {NOTES} Set if patron has notes
1111 # {message} Notes about patron
1112 # {ODUES} Set if patron has overdue books
1114 # {itemlist} ref-to-array: list of overdue books
1115 # {itemlisttext} Text list of overdue items
1116 # {WAITING} Set if there are items available that the
1118 # {message} Message to this effect
1119 # {itemlist} ref-to-array: list of available items
1121 # Original subroutine for Circ2.pm
1123 my ($env, $patroninformation, $dbh) = @_;
1124 my $amount = checkaccount($env, $patroninformation->{'borrowernumber'}, $dbh);
1127 my $noissuescharge = C4::Context->preference("noissuescharge");
1128 $flaginfo{'message'}= sprintf "Patron owes \$%.02f", $amount;
1129 if ($amount > $noissuescharge) {
1130 $flaginfo{'noissues'} = 1;
1132 $flags{'CHARGES'} = \%flaginfo;
1133 } elsif ($amount < 0){
1135 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
1136 $flags{'CHARGES'} = \%flaginfo;
1138 if ($patroninformation->{'gonenoaddress'} == 1) {
1140 $flaginfo{'message'} = 'Borrower has no valid address.';
1141 $flaginfo{'noissues'} = 1;
1142 $flags{'GNA'} = \%flaginfo;
1144 if ($patroninformation->{'lost'} == 1) {
1146 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
1147 $flaginfo{'noissues'} = 1;
1148 $flags{'LOST'} = \%flaginfo;
1150 if ($patroninformation->{'debarred'} == 1) {
1152 $flaginfo{'message'} = 'Borrower is Debarred.';
1153 $flaginfo{'noissues'} = 1;
1154 $flags{'DBARRED'} = \%flaginfo;
1156 if ($patroninformation->{'borrowernotes'}) {
1158 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
1159 $flags{'NOTES'} = \%flaginfo;
1161 my ($odues, $itemsoverdue)
1162 = checkoverdues($env, $patroninformation->{'borrowernumber'}, $dbh);
1165 $flaginfo{'message'} = "Yes";
1166 $flaginfo{'itemlist'} = $itemsoverdue;
1167 foreach (sort {$a->{'date_due'} cmp $b->{'date_due'}} @$itemsoverdue) {
1168 $flaginfo{'itemlisttext'}.="$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
1170 $flags{'ODUES'} = \%flaginfo;
1172 my ($nowaiting, $itemswaiting)
1173 = CheckWaiting($patroninformation->{'borrowernumber'});
1174 if ($nowaiting > 0) {
1176 $flaginfo{'message'} = "Reserved items available";
1177 $flaginfo{'itemlist'} = $itemswaiting;
1178 $flags{'WAITING'} = \%flaginfo;
1186 # From Main.pm, modified to return a list of overdueitems, in addition to a count
1187 #checks whether a borrower has overdue items
1188 my ($env, $bornum, $dbh)=@_;
1189 my @datearr = localtime;
1190 my $today = ($datearr[5] + 1900)."-".($datearr[4]+1)."-".$datearr[3];
1193 my $sth = $dbh->prepare("SELECT * FROM issues,biblio,biblioitems,items
1194 WHERE items.biblioitemnumber = biblioitems.biblioitemnumber
1195 AND items.biblionumber = biblio.biblionumber
1196 AND issues.itemnumber = items.itemnumber
1197 AND issues.borrowernumber = ?
1198 AND issues.returndate is NULL
1199 AND issues.date_due < ?");
1200 $sth->execute($bornum,$today);
1201 while (my $data = $sth->fetchrow_hashref) {
1202 push (@overdueitems, $data);
1206 return ($count, \@overdueitems);
1210 sub currentborrower {
1211 # Original subroutine for Circ2.pm
1212 my ($itemnumber) = @_;
1213 my $dbh = C4::Context->dbh;
1214 my $q_itemnumber = $dbh->quote($itemnumber);
1215 my $sth=$dbh->prepare("select borrowers.borrowernumber from
1216 issues,borrowers where issues.itemnumber=$q_itemnumber and
1217 issues.borrowernumber=borrowers.borrowernumber and issues.returndate is
1220 my ($borrower) = $sth->fetchrow;
1224 # FIXME - Not exported, but used in 'updateitem.pl' anyway.
1226 # Stolen from Main.pm
1227 # Check for reserves for biblio
1228 my ($env,$dbh,$itemnum)=@_;
1230 my $sth = $dbh->prepare("select * from reserves,items
1231 where (items.itemnumber = ?)
1232 and (reserves.cancellationdate is NULL)
1233 and (items.biblionumber = reserves.biblionumber)
1234 and ((reserves.found = 'W')
1235 or (reserves.found is null))
1236 order by priority");
1237 $sth->execute($itemnum);
1239 my $data=$sth->fetchrow_hashref;
1240 while ($data && $resbor eq '') {
1242 my $const = $data->{'constrainttype'};
1243 if ($const eq "a") {
1244 $resbor = $data->{'borrowernumber'};
1247 my $csth = $dbh->prepare("select * from reserveconstraints,items
1248 where (borrowernumber=?)
1250 and reserveconstraints.biblionumber=?
1251 and (items.itemnumber=? and
1252 items.biblioitemnumber = reserveconstraints.biblioitemnumber)");
1253 $csth->execute($data->{'borrowernumber'},$data->{'biblionumber'},$data->{'reservedate'},$itemnum);
1254 if (my $cdata=$csth->fetchrow_hashref) {$found = 1;}
1255 if ($const eq 'o') {
1256 if ($found eq 1) {$resbor = $data->{'borrowernumber'};}
1258 if ($found eq 0) {$resbor = $data->{'borrowernumber'};}
1262 $data=$sth->fetchrow_hashref;
1265 return ($resbor,$resrec);
1268 =head2 currentissues
1270 $issues = ¤tissues($env, $borrower);
1272 Returns a list of books currently on loan to a patron.
1274 If C<$env-E<gt>{todaysissues}> is set and true, C<¤tissues> only
1275 returns information about books issued today. If
1276 C<$env-E<gt>{nottodaysissues}> is set and true, C<¤tissues> only
1277 returns information about books issued before today. If both are
1278 specified, C<$env-E<gt>{todaysissues}> is ignored. If neither is
1279 specified, C<¤tissues> returns all of the patron's issues.
1281 C<$borrower->{borrowernumber}> is the borrower number of the patron
1282 whose issues we want to list.
1284 C<¤tissues> returns a PHP-style array: C<$issues> is a
1285 reference-to-hash whose keys are integers in the range 1...I<n>, where
1286 I<n> is the number of items on issue (either today or before today).
1287 C<$issues-E<gt>{I<n>}> is a reference-to-hash whose keys are all of
1288 the fields of the biblio, biblioitems, items, and issues fields of the
1289 Koha database for that particular item.
1295 # New subroutine for Circ2.pm
1296 my ($env, $borrower) = @_;
1297 my $dbh = C4::Context->dbh;
1300 my $borrowernumber = $borrower->{'borrowernumber'};
1303 # Figure out whether to get the books issued today, or earlier.
1304 # FIXME - $env->{todaysissues} and $env->{nottodaysissues} can
1305 # both be specified, but are mutually-exclusive. This is bogus.
1306 # Make this a flag. Or better yet, return everything in (reverse)
1307 # chronological order and let the caller figure out which books
1308 # were issued today.
1309 if ($env->{'todaysissues'}) {
1311 # $today = POSIX::strftime("%Y%m%d", localtime);
1312 # FIXME - Since $today will be used in either case, move it
1313 # out of the two if-blocks.
1314 my @datearr = localtime(time());
1315 my $today = (1900+$datearr[5]).sprintf "%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
1316 # FIXME - MySQL knows about dates. Just use
1317 # and issues.timestamp = curdate();
1318 $crit=" and issues.timestamp like '$today%' ";
1320 if ($env->{'nottodaysissues'}) {
1322 # $today = POSIX::strftime("%Y%m%d", localtime);
1323 # FIXME - Since $today will be used in either case, move it
1324 # out of the two if-blocks.
1325 my @datearr = localtime(time());
1326 my $today = (1900+$datearr[5]).sprintf "%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
1327 # FIXME - MySQL knows about dates. Just use
1328 # and issues.timestamp < curdate();
1329 $crit=" and !(issues.timestamp like '$today%') ";
1332 # FIXME - Does the caller really need every single field from all
1334 my $sth=$dbh->prepare("select * from issues,items,biblioitems,biblio where
1335 borrowernumber=? and issues.itemnumber=items.itemnumber and
1336 items.biblionumber=biblio.biblionumber and
1337 items.biblioitemnumber=biblioitems.biblioitemnumber and returndate is null
1338 $crit order by issues.date_due");
1339 $sth->execute($borrowernumber);
1340 while (my $data = $sth->fetchrow_hashref) {
1341 # FIXME - The Dewey code is a string, not a number.
1342 $data->{'dewey'}=~s/0*$//;
1343 ($data->{'dewey'} == 0) && ($data->{'dewey'}='');
1345 # $todaysdate = POSIX::strftime("%Y%m%d", localtime)
1346 # or better yet, just reuse $today which was calculated above.
1347 # This function isn't going to run until midnight, is it?
1349 # $todaysdate = POSIX::strftime("%Y-%m-%d", localtime)
1350 # if ($data->{'date_due'} lt $todaysdate)
1352 # Either way, the date should be be formatted outside of the
1354 my @datearr = localtime(time());
1355 my $todaysdate = (1900+$datearr[5]).sprintf ("%0.2d", ($datearr[4]+1)).sprintf ("%0.2d", $datearr[3]);
1356 my $datedue=$data->{'date_due'};
1358 if ($datedue < $todaysdate) {
1359 $data->{'overdue'}=1;
1361 my $itemnumber=$data->{'itemnumber'};
1362 # FIXME - Consecutive integers as hash keys? You have GOT to
1363 # be kidding me! Use an array, fercrissakes!
1364 $currentissues{$counter}=$data;
1368 return(\%currentissues);
1373 $issues = &getissues($borrowernumber);
1375 Returns the set of books currently on loan to a patron.
1377 C<$borrowernumber> is the patron's borrower number.
1379 C<&getissues> returns a PHP-style array: C<$issues> is a
1380 reference-to-hash whose keys are integers in the range 0..I<n>-1,
1381 where I<n> is the number of books the patron currently has on loan.
1383 The values of C<$issues> are references-to-hash whose keys are
1384 selected fields from the issues, items, biblio, and biblioitems tables
1385 of the Koha database.
1390 # New subroutine for Circ2.pm
1391 my ($borrower) = @_;
1392 my $dbh = C4::Context->dbh;
1393 my $borrowernumber = $borrower->{'borrowernumber'};
1395 my $select = "SELECT issues.timestamp AS timestamp,
1396 issues.date_due AS date_due,
1397 items.biblionumber AS biblionumber,
1398 items.itemnumber AS itemnumber,
1399 items.barcode AS barcode,
1400 biblio.title AS title,
1401 biblio.author AS author,
1402 biblioitems.dewey AS dewey,
1403 itemtypes.description AS itemtype,
1404 biblioitems.subclass AS subclass,
1405 biblioitems.classification AS classification
1406 FROM issues,items,biblioitems,biblio, itemtypes
1407 WHERE issues.borrowernumber = ?
1408 AND issues.itemnumber = items.itemnumber
1409 AND items.biblionumber = biblio.biblionumber
1410 AND items.biblioitemnumber = biblioitems.biblioitemnumber
1411 AND itemtypes.itemtype = biblioitems.itemtype
1412 AND issues.returndate IS NULL
1413 ORDER BY issues.date_due";
1415 my $sth=$dbh->prepare($select);
1416 $sth->execute($borrowernumber);
1418 while (my $data = $sth->fetchrow_hashref) {
1419 $data->{'dewey'} =~ s/0*$//;
1420 ($data->{'dewey'} == 0) && ($data->{'dewey'} = '');
1421 # FIXME - The Dewey code is a string, not a number.
1422 # FIXME - Use POSIX::strftime to get a text version of today's
1423 # date. That's what it's for.
1424 # FIXME - Move the date calculation outside of the loop.
1425 my @datearr = localtime(time());
1426 my $todaysdate = (1900+$datearr[5]).sprintf ("%0.2d", ($datearr[4]+1)).sprintf ("%0.2d", $datearr[3]);
1428 # FIXME - Instead of converting the due date to YYYYMMDD, just
1430 # $todaysdate = POSIX::strftime("%Y-%m-%d", localtime);
1432 # if ($date->{date_due} lt $todaysdate)
1433 my $datedue = $data->{'date_due'};
1435 if ($datedue < $todaysdate) {
1436 $data->{'overdue'} = 1;
1438 $currentissues{$counter} = $data;
1440 # FIXME - This is ludicrous. If you want to return an
1441 # array of values, just use an array. That's what
1442 # they're there for.
1445 return(\%currentissues);
1450 #Stolen from Main.pm
1451 # check for reserves waiting
1452 my ($env,$dbh,$bornum)=@_;
1454 my $sth = $dbh->prepare("select * from reserves where (borrowernumber = ?) and (reserves.found='W') and cancellationdate is NULL");
1455 $sth->execute($bornum);
1457 if (my $data=$sth->fetchrow_hashref) {
1458 $itemswaiting[$cnt] =$data;
1462 return ($cnt,\@itemswaiting);
1467 $ok = &renewstatus($env, $dbh, $borrowernumber, $itemnumber);
1469 Find out whether a borrowed item may be renewed.
1473 C<$dbh> is a DBI handle to the Koha database.
1475 C<$borrowernumber> is the borrower number of the patron who currently
1476 has the item on loan.
1478 C<$itemnumber> is the number of the item to renew.
1480 C<$renewstatus> returns a true value iff the item may be renewed. The
1481 item must currently be on loan to the specified borrower; renewals
1482 must be allowed for the item's type; and the borrower must not have
1483 already renewed the loan.
1488 # check renewal status
1489 # FIXME - Two people can't borrow the same book at once, so
1490 # presumably we can get $bornum from $itemno.
1491 my ($env,$bornum,$itemno)=@_;
1492 my $dbh = C4::Context->dbh;
1495 # Look in the issues table for this item, lent to this borrower,
1496 # and not yet returned.
1498 # FIXME - I think this function could be redone to use only one SQL
1500 my $sth1 = $dbh->prepare("select * from issues
1501 where (borrowernumber = ?)
1502 and (itemnumber = ?')
1503 and returndate is null");
1504 $sth1->execute($bornum,$itemno);
1505 if (my $data1 = $sth1->fetchrow_hashref) {
1506 # Found a matching item
1508 # See if this item may be renewed. This query is convoluted
1509 # because it's a bit messy: given the item number, we need to find
1510 # the biblioitem, which gives us the itemtype, which tells us
1511 # whether it may be renewed.
1512 my $sth2 = $dbh->prepare("select renewalsallowed from items,biblioitems,itemtypes
1513 where (items.itemnumber = ?)
1514 and (items.biblioitemnumber = biblioitems.biblioitemnumber)
1515 and (biblioitems.itemtype = itemtypes.itemtype)");
1516 $sth2->execute($itemno);
1517 if (my $data2=$sth2->fetchrow_hashref) {
1518 $renews = $data2->{'renewalsallowed'};
1520 if ($renews > $data1->{'renewals'}) {
1531 &renewbook($env, $borrowernumber, $itemnumber, $datedue);
1535 C<$env-E<gt>{branchcode}> is the code of the branch where the
1536 renewal is taking place.
1538 C<$env-E<gt>{usercode}> is the value to log in C<statistics.usercode>
1539 in the Koha database.
1541 C<$borrowernumber> is the borrower number of the patron who currently
1544 C<$itemnumber> is the number of the item to renew.
1546 C<$datedue> can be used to set the due date. If C<$datedue> is the
1547 empty string, C<&renewbook> will calculate the due date automatically
1548 from the book's item type. If you wish to set the due date manually,
1549 C<$datedue> should be in the form YYYY-MM-DD.
1554 # mark book as renewed
1555 # FIXME - A book can't be on loan to two people at once, so
1556 # presumably we can get $bornum from $itemno.
1557 my ($env,$bornum,$itemno,$datedue)=@_;
1558 my $dbh = C4::Context->dbh;
1560 # If the due date wasn't specified, calculate it by adding the
1561 # book's loan length to today's date.
1562 if ($datedue eq "" ) {
1563 #debug_msg($env, "getting date");
1564 my $loanlength=21; # Default loan length?
1565 # FIXME - This is bogus. If there's no
1566 # loan length defined for some book
1567 # type or whatever, then that should
1569 # Find this item's item type, via its biblioitem.
1570 my $sth=$dbh->prepare("Select * from biblioitems,items,itemtypes
1571 where (items.itemnumber = ?)
1572 and (biblioitems.biblioitemnumber = items.biblioitemnumber)
1573 and (biblioitems.itemtype = itemtypes.itemtype)");
1574 $sth->execute($itemno);
1575 if (my $data=$sth->fetchrow_hashref) {
1576 $loanlength = $data->{'loanlength'}
1579 my $ti = time; # FIXME - Unused
1581 # POSIX::strftime("%Y-%m-%d", localtime(time + ...));
1582 my $datedu = time + ($loanlength * 86400);
1583 my @datearr = localtime($datedu);
1584 $datedue = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
1587 # Find the issues record for this book
1588 my $sth=$dbh->prepare("select * from issues where borrowernumber=? and
1589 itemnumber=? and returndate is null");
1590 $sth->execute($bornum,$itemno);
1591 my $issuedata=$sth->fetchrow_hashref;
1592 # FIXME - Error-checking
1595 # Update the issues record to have the new due date, and a new count
1596 # of how many times it has been renewed.
1597 my $renews = $issuedata->{'renewals'} +1;
1598 $sth=$dbh->prepare("update issues
1599 set date_due = ?, renewals = ?
1600 where borrowernumber=? and
1601 itemnumber=? and returndate is null");
1602 $sth->execute($datedue,$renews,$bornum,$itemno);
1606 UpdateStats($env,$env->{'branchcode'},'renew','','',$itemno);
1608 # Charge a new rental fee, if applicable?
1609 my ($charge,$type)=calc_charges($env, $itemno, $bornum);
1611 my $accountno=getnextacctno($env,$bornum,$dbh);
1612 my $item=getiteminformation($env, $itemno);
1613 $sth=$dbh->prepare("Insert into accountlines (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding,itemnumber)
1614 values (?,?,now(),?,?,?,?,?)");
1615 $sth->execute($bornum,$accountno,$charge,"Renewal of Rental Item $item->{'title'} $item->{'barcode'}",'Rent',$charge,$itemno);
1627 ($charge, $item_type) = &calc_charges($env, $itemnumber, $borrowernumber);
1629 Calculate how much it would cost for a given patron to borrow a given
1630 item, including any applicable discounts.
1634 C<$itemnumber> is the item number of item the patron wishes to borrow.
1636 C<$borrowernumber> is the patron's borrower number.
1638 C<&calc_charges> returns two values: C<$charge> is the rental charge,
1639 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1645 # calculate charges due
1646 my ($env, $itemno, $bornum)=@_;
1648 my $dbh = C4::Context->dbh;
1651 # Get the book's item type and rental charge (via its biblioitem).
1652 my $sth1= $dbh->prepare("select itemtypes.itemtype,rentalcharge from items,biblioitems,itemtypes
1653 where (items.itemnumber =?)
1654 and (biblioitems.biblioitemnumber = items.biblioitemnumber)
1655 and (biblioitems.itemtype = itemtypes.itemtype)");
1656 $sth1->execute($itemno);
1657 # FIXME - Why not just use fetchrow_array?
1658 if (my $data1=$sth1->fetchrow_hashref) {
1659 $item_type = $data1->{'itemtype'};
1660 $charge = $data1->{'rentalcharge'};
1662 # Figure out the applicable rental discount
1663 my $sth2=$dbh->prepare("select rentaldiscount from
1664 borrowers,categoryitem
1665 where (borrowers.borrowernumber = ?)
1666 and (borrowers.categorycode = categoryitem.categorycode)
1667 and (categoryitem.itemtype = ?)");
1668 $sth2->execute($bornum,$item_type);
1669 if (my$data2=$sth2->fetchrow_hashref) {
1670 my $discount = $data2->{'rentaldiscount'};
1671 $charge *= (100 - $discount) / 100;
1676 # print "item $item_type";
1677 return ($charge,$item_type);
1681 # FIXME - A virtually identical function appears in
1682 # C4::Circulation::Issues. Pick one and stick with it.
1684 #Stolen from Issues.pm
1685 my ($env,$dbh,$itemno,$bornum,$charge) = @_;
1686 my $nextaccntno = getnextacctno($env,$bornum,$dbh);
1687 my $sth = $dbh->prepare(<<EOT);
1688 INSERT INTO accountlines
1689 (borrowernumber, itemnumber, accountno,
1690 date, amount, description, accounttype,
1693 now(), ?, 'Rental', 'Rent',
1696 $sth->execute($bornum, $itemno, $nextaccntno, $charge, $charge);
1702 # Stolen from Accounts.pm
1703 my ($env,$bornumber,$dbh)=@_;
1704 my $nextaccntno = 1;
1705 my $sth = $dbh->prepare("select * from accountlines where (borrowernumber = ?) order by accountno desc");
1706 $sth->execute($bornumber);
1707 if (my $accdata=$sth->fetchrow_hashref){
1708 $nextaccntno = $accdata->{'accountno'} + 1;
1711 return($nextaccntno);
1716 ($status, $record) = &find_reserves($itemnumber);
1718 Looks up an item in the reserves.
1720 C<$itemnumber> is the itemnumber to look up.
1722 C<$status> is true iff the search was successful.
1724 C<$record> is a reference-to-hash describing the reserve. Its keys are
1725 the fields from the reserves table of the Koha database.
1729 # FIXME - This API is bogus: just return the record, or undef if none
1731 # FIXME - There's also a &C4::Circulation::Returns::find_reserves, but
1732 # that one looks rather different.
1734 # Stolen from Returns.pm
1737 my $dbh = C4::Context->dbh;
1738 my ($itemdata) = getiteminformation(\%env, $itemno,0);
1739 my $bibno = $dbh->quote($itemdata->{'biblionumber'});
1740 my $bibitm = $dbh->quote($itemdata->{'biblioitemnumber'});
1741 my $sth = $dbh->prepare("select * from reserves where ((found = 'W') or (found is null)) and biblionumber = ? and cancellationdate is NULL order by priority, reservedate");
1742 $sth->execute($bibno);
1748 # FIXME - I'm not really sure what's going on here, but since we
1749 # only want one result, wouldn't it be possible (and far more
1750 # efficient) to do something clever in SQL that only returns one
1752 while (($resrec = $sth->fetchrow_hashref) && (not $resfound)) {
1753 # FIXME - Unlike Pascal, Perl allows you to exit loops
1754 # early. Take out the "&& (not $resfound)" and just
1755 # use "last" at the appropriate point in the loop.
1756 # (Oh, and just in passing: if you'd used "!" instead
1757 # of "not", you wouldn't have needed the parentheses.)
1759 my $brn = $dbh->quote($resrec->{'borrowernumber'});
1760 my $rdate = $dbh->quote($resrec->{'reservedate'});
1761 my $bibno = $dbh->quote($resrec->{'biblionumber'});
1762 if ($resrec->{'found'} eq "W") {
1763 if ($resrec->{'itemnumber'} eq $itemno) {
1767 # FIXME - Use 'elsif' to avoid unnecessary indentation.
1768 if ($resrec->{'constrainttype'} eq "a") {
1771 my $consth = $dbh->prepare("select * from reserveconstraints where borrowernumber = ? and reservedate = ? and biblionumber = ? and biblioitemnumber = ?");
1772 $consth->execute($brn,$rdate,$bibno,$bibitm);
1773 if (my $conrec = $consth->fetchrow_hashref) {
1774 if ($resrec->{'constrainttype'} eq "o") {
1782 my $updsth = $dbh->prepare("update reserves set found = 'W', itemnumber = ? where borrowernumber = ? and reservedate = ? and biblionumber = ?");
1783 $updsth->execute($itemno,$brn,$rdate,$bibno);
1785 # FIXME - "last;" here to break out of the loop early.
1789 return ($resfound,$lastrec);
1793 my ($year, $month, $day) = @_;
1796 if (($year eq 0) && ($month eq 0) && ($year eq 0)) {
1797 # $env{'datedue'}='';
1799 if (($year eq 0) || ($month eq 0) || ($year eq 0)) {
1802 if (($day>30) && (($month==4) || ($month==6) || ($month==9) || ($month==11))) {
1803 $invalidduedate = 1;
1804 } elsif (($day > 29) && ($month == 2)) {
1806 } elsif (($month == 2) && ($day > 28) && (($year%4) && ((!($year%100) || ($year%400))))) {
1809 $date="$year-$month-$day";
1813 return ($date, $invalidduedate);
1823 Koha Developement team <info@koha.org>