1 package C4::Circulation;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
39 use POSIX qw(strftime);
40 use C4::Branch; # GetBranches
41 use C4::Log; # logaction
43 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
45 # set the version for version checking
46 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v).".".join( "_", map { sprintf "%03d", $_ } @v ); };
50 C4::Circulation::Circ2 - Koha circulation module
58 The functions in this module deal with circulation, issues, and
59 returns, as well as general information about the library.
60 Also deals with stocktaking.
68 # FIXME subs that should probably be elsewhere
73 # subs to deal with issuing a book
84 &AnonymiseIssueHistory
86 # subs to deal with returns
91 # subs to deal with transfers
108 =head3 $str = &decode($chunk);
112 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
119 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
121 # FIXME From Paul : i don't understand what this sub does & why it has to be called on every circ. Speak of this with chris maybe ?
125 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
126 my @s = map { index( $seq, $_ ); } split( //, $encoded );
127 my $l = ( $#s + 1 ) % 4;
138 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
140 chr( ( $n >> 16 ) ^ 67 )
141 .chr( ( $n >> 8 & 255 ) ^ 67 )
142 .chr( ( $n & 255 ) ^ 67 );
145 $r = substr( $r, 0, length($r) - $l );
151 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
153 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
155 C<$newbranch> is the code for the branch to which the item should be transferred.
157 C<$barcode> is the barcode of the item to be transferred.
159 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
160 Otherwise, if an item is reserved, the transfer fails.
162 Returns three values:
166 is true if the transfer was successful.
170 is a reference-to-hash which may have any of the following keys:
176 There is no item in the catalog with the given barcode. The value is C<$barcode>.
180 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.
182 =item C<DestinationEqualsHolding>
184 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.
188 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.
192 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>.
194 =item C<WasTransferred>
196 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
203 my ( $tbr, $barcode, $ignoreRs ) = @_;
206 my $branches = GetBranches();
207 my $itemnumber = GetItemnumberFromBarcode( $barcode );
208 my $issue = GetItemIssue($itemnumber);
209 my $biblio = GetBiblioFromItemNumber($itemnumber);
212 if ( not $itemnumber ) {
213 $messages->{'BadBarcode'} = $barcode;
217 # get branches of book...
218 my $hbr = $biblio->{'homebranch'};
219 my $fbr = $biblio->{'holdingbranch'};
222 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
223 $messages->{'IsPermanent'} = $hbr;
226 # can't transfer book if is already there....
227 if ( $fbr eq $tbr ) {
228 $messages->{'DestinationEqualsHolding'} = 1;
232 # check if it is still issued to someone, return it...
233 if ($issue->{borrowernumber}) {
234 AddReturn( $barcode, $fbr );
235 $messages->{'WasReturned'} = $issue->{borrowernumber};
239 # That'll save a database query.
240 my ( $resfound, $resrec ) =
241 CheckReserves( $itemnumber );
242 if ( $resfound and not $ignoreRs ) {
243 $resrec->{'ResFound'} = $resfound;
245 # $messages->{'ResFound'} = $resrec;
249 #actually do the transfer....
251 dotransfer( $itemnumber, $fbr, $tbr );
253 # don't need to update MARC anymore, we do it in batch now
254 $messages->{'WasTransfered'} = 1;
256 return ( $dotransfer, $messages, $biblio );
260 # FIXME - This is only used in &transferbook. Why bother making it a
263 my ( $itm, $fbr, $tbr ) = @_;
265 my $dbh = C4::Context->dbh;
266 $itm = $dbh->quote($itm);
267 $fbr = $dbh->quote($fbr);
268 $tbr = $dbh->quote($tbr);
270 #new entry in branchtransfers....
272 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
273 VALUES ($itm, $fbr, now(), $tbr)"
276 #update holdingbranch in items .....
278 "UPDATE items set holdingbranch = $tbr WHERE items.itemnumber = $itm");
279 &ModDateLastSeen($itm);
280 &domarctransfer( $dbh, $itm );
284 ##New sub to dotransfer in marc tables as well. Not exported -TG 10/04/2006
286 my ( $dbh, $itemnumber ) = @_;
287 $itemnumber =~ s /\'//g; ##itemnumber seems to come with quotes-TG
290 "select biblionumber,holdingbranch from items where itemnumber=$itemnumber"
293 while ( my ( $biblionumber, $holdingbranch ) = $sth->fetchrow ) {
294 &ModItemInMarconefield( $biblionumber, $itemnumber,
295 'items.holdingbranch', $holdingbranch );
300 =head2 CanBookBeIssued
302 Check if a book can be issued.
304 my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($borrower,$barcode,$year,$month,$day);
308 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
310 =item C<$barcode> is the bar code of the book being issued.
312 =item C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
320 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
321 Possible values are :
327 sticky due date is invalid
331 borrower gone with no address
335 borrower declared it's card lost
341 =head3 UNKNOWN_BARCODE
355 item is restricted (set by ??)
357 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
358 Possible values are :
366 renewing, not issuing
368 =head3 ISSUED_TO_ANOTHER
370 issued to someone else.
374 reserved for someone else.
378 sticky due date is invalid
382 if the borrower borrows to much things
386 # check if a book can be issued.
387 # returns an array with errors if any
390 my $borrower = shift;
391 my $biblionumber = shift;
392 my $cat_borrower = $borrower->{'categorycode'};
393 my $branch_borrower = $borrower->{'branchcode'};
394 my $dbh = C4::Context->dbh;
397 $dbh->prepare('select itemtype from biblioitems where biblionumber = ?');
398 $sth->execute($biblionumber);
399 my $type = $sth->fetchrow;
402 'select * from issuingrules where categorycode = ? and itemtype = ? and branchcode = ?'
405 # 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 ?");
408 "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"
412 'select COUNT(*) from issues where borrowernumber = ? and returndate is null'
416 # check the 3 parameters
417 $sth->execute( $cat_borrower, $type, $branch_borrower );
418 my $result = $sth->fetchrow_hashref;
420 # warn "==>".$result->{maxissueqty};
422 # Currently, using defined($result) ie on an entire hash reports whether memory
423 # for that aggregate has ever been allocated. As $result is used all over the place
424 # it would rarely return as undefined.
425 if ( defined( $result->{maxissueqty} ) ) {
426 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
427 my $alreadyissued = $sth2->fetchrow;
428 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
429 return ( "a $alreadyissued / ".( $result->{maxissueqty} + 0 ) );
437 $sth->execute( $cat_borrower, $type, "" );
438 $result = $sth->fetchrow_hashref;
439 if ( defined( $result->{maxissueqty} ) ) {
440 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
441 my $alreadyissued = $sth2->fetchrow;
442 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
443 return ( "b $alreadyissued / ".( $result->{maxissueqty} + 0 ) );
450 # check for itemtype=*
451 $sth->execute( $cat_borrower, "*", $branch_borrower );
452 $result = $sth->fetchrow_hashref;
453 if ( defined( $result->{maxissueqty} ) ) {
454 $sth3->execute( $borrower->{'borrowernumber'} );
455 my ($alreadyissued) = $sth3->fetchrow;
456 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
458 # warn "HERE : $alreadyissued / ($result->{maxissueqty} for $borrower->{'borrowernumber'}";
459 return ( "c $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
466 # check for borrowertype=*
467 $sth->execute( "*", $type, $branch_borrower );
468 $result = $sth->fetchrow_hashref;
469 if ( defined( $result->{maxissueqty} ) ) {
470 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
471 my $alreadyissued = $sth2->fetchrow;
472 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
473 return ( "d $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
480 $sth->execute( "*", "*", $branch_borrower );
481 $result = $sth->fetchrow_hashref;
482 if ( defined( $result->{maxissueqty} ) ) {
483 $sth3->execute( $borrower->{'borrowernumber'} );
484 my $alreadyissued = $sth3->fetchrow;
485 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
486 return ( "e $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
493 $sth->execute( "*", $type, "" );
494 $result = $sth->fetchrow_hashref;
495 if ( defined( $result->{maxissueqty} ) && $result->{maxissueqty} >= 0 ) {
496 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
497 my $alreadyissued = $sth2->fetchrow;
498 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
499 return ( "f $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
506 $sth->execute( $cat_borrower, "*", "" );
507 $result = $sth->fetchrow_hashref;
508 if ( defined( $result->{maxissueqty} ) ) {
509 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
510 my $alreadyissued = $sth2->fetchrow;
511 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
512 return ( "g $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
519 $sth->execute( "*", "*", "" );
520 $result = $sth->fetchrow_hashref;
521 if ( defined( $result->{maxissueqty} ) ) {
522 $sth3->execute( $borrower->{'borrowernumber'} );
523 my $alreadyissued = $sth3->fetchrow;
524 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
525 return ( "h $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
536 @issues = &itemissues($biblioitemnumber, $biblio);
538 Looks up information about who has borrowed the bookZ<>(s) with the
539 given biblioitemnumber.
541 C<$biblio> is ignored.
543 C<&itemissues> returns an array of references-to-hash. The keys
544 include the fields from the C<items> table in the Koha database.
545 Additional keys include:
551 If the item is currently on loan, this gives the due date.
553 If the item is not on loan, then this is either "Available" or
554 "Cancelled", if the item has been withdrawn.
558 If the item is currently on loan, this gives the card number of the
559 patron who currently has the item.
561 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
563 These give the timestamp for the last three times the item was
566 =item C<card0>, C<card1>, C<card2>
568 The card number of the last three patrons who borrowed this item.
570 =item C<borrower0>, C<borrower1>, C<borrower2>
572 The borrower number of the last three patrons who borrowed this item.
580 my ( $bibitem, $biblio ) = @_;
581 my $dbh = C4::Context->dbh;
583 # FIXME - If this function die()s, the script will abort, and the
584 # user won't get anything; depending on how far the script has
585 # gotten, the user might get a blank page. It would be much better
586 # to at least print an error message. The easiest way to do this
587 # is to set $SIG{__DIE__}.
589 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
594 $sth->execute($bibitem) || die $sth->errstr;
596 while ( my $data = $sth->fetchrow_hashref ) {
598 # Find out who currently has this item.
599 # FIXME - Wouldn't it be better to do this as a left join of
600 # some sort? Currently, this code assumes that if
601 # fetchrow_hashref() fails, then the book is on the shelf.
602 # fetchrow_hashref() can fail for any number of reasons (e.g.,
603 # database server crash), not just because no items match the
605 my $sth2 = $dbh->prepare(
606 "SELECT * FROM issues
607 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
609 AND returndate IS NULL
613 $sth2->execute( $data->{'itemnumber'} );
614 if ( my $data2 = $sth2->fetchrow_hashref ) {
615 $data->{'date_due'} = $data2->{'date_due'};
616 $data->{'card'} = $data2->{'cardnumber'};
617 $data->{'borrower'} = $data2->{'borrowernumber'};
620 if ( $data->{'wthdrawn'} eq '1' ) {
621 $data->{'date_due'} = 'Cancelled';
624 $data->{'date_due'} = 'Available';
630 # Find the last 3 people who borrowed this item.
631 $sth2 = $dbh->prepare(
632 "SELECT * FROM issues, borrowers
633 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
635 AND returndate IS NOT NULL
636 ORDER BY returndate DESC,timestamp DESC"
639 # $sth2 = $dbh->prepare("
642 # LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
643 # WHERE itemnumber = ?
644 # AND returndate is not NULL
645 # ORDER BY returndate DESC,timestamp DESC
648 $sth2->execute( $data->{'itemnumber'} );
649 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
650 { # FIXME : error if there is less than 3 pple borrowing this item
651 if ( my $data2 = $sth2->fetchrow_hashref ) {
652 $data->{"timestamp$i2"} = $data2->{'timestamp'};
653 $data->{"card$i2"} = $data2->{'cardnumber'};
654 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
659 $results[$i] = $data;
667 =head2 CanBookBeIssued
669 $issuingimpossible, $needsconfirmation =
670 CanBookBeIssued( $borrower, $barcode, $year, $month, $day, $inprocess );
672 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
676 sub CanBookBeIssued {
677 my ( $borrower, $barcode, $year, $month, $day, $inprocess ) = @_;
678 my %needsconfirmation; # filled with problems that needs confirmations
679 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
680 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
681 my $issue = GetItemIssue($item->{itemnumber});
682 my $dbh = C4::Context->dbh;
687 my ( $duedate, $invalidduedate ) = fixdate( $year, $month, $day );
688 $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
693 if ( $borrower->{flags}->{GNA} ) {
694 $issuingimpossible{GNA} = 1;
696 if ( $borrower->{flags}->{'LOST'} ) {
697 $issuingimpossible{CARD_LOST} = 1;
699 if ( $borrower->{flags}->{'DBARRED'} ) {
700 $issuingimpossible{DEBARRED} = 1;
702 if ( Date_to_Days(Today) >
703 Date_to_Days( split "-", $borrower->{'dateexpiry'} ) )
707 #if (&Date_Cmp(&ParseDate($borrower->{expiry}),&ParseDate("today"))<0) {
708 $issuingimpossible{EXPIRED} = 1;
717 GetBorrowerAcctRecord( $borrower->{'borrowernumber'}, $duedate );
718 if ( C4::Context->preference("IssuingInProcess") ) {
719 my $amountlimit = C4::Context->preference("noissuescharge");
720 if ( $amount > $amountlimit && !$inprocess ) {
721 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
723 elsif ( $amount <= $amountlimit && !$inprocess ) {
724 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
729 $needsconfirmation{DEBT} = $amount;
734 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
736 my $toomany = TooMany( $borrower, $item->{biblionumber} );
737 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
742 unless ( $item->{barcode} ) {
743 $issuingimpossible{UNKNOWN_BARCODE} = 1;
745 if ( $item->{'notforloan'}
746 && $item->{'notforloan'} > 0 )
748 $issuingimpossible{NOT_FOR_LOAN} = 1;
750 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
752 $issuingimpossible{WTHDRAWN} = 1;
754 if ( $item->{'restricted'}
755 && $item->{'restricted'} == 1 )
757 $issuingimpossible{RESTRICTED} = 1;
759 if ( C4::Context->preference("IndependantBranches") ) {
760 my $userenv = C4::Context->userenv;
761 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
762 $issuingimpossible{NOTSAMEBRANCH} = 1
763 if ( $item->{'holdingbranch'} ne $userenv->{branch} );
768 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
770 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
773 # Already issued to current borrower. Ask whether the loan should
775 my ($CanBookBeRenewed) = CanBookBeRenewed(
776 $borrower->{'borrowernumber'},
777 $item->{'itemnumber'}
779 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
780 $issuingimpossible{NO_MORE_RENEWALS} = 1;
784 # $needsconfirmation{RENEW_ISSUE} = 1;
787 elsif ($issue->{borrowernumber}) {
789 # issued to someone else
790 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
792 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
793 $needsconfirmation{ISSUED_TO_ANOTHER} =
794 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
797 # See if the item is on reserve.
798 my ( $restype, $res ) = CheckReserves( $item->{'itemnumber'} );
800 my $resbor = $res->{'borrowernumber'};
801 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
804 # The item is on reserve and waiting, but has been
805 # reserved by some other patron.
806 my ( $resborrower, $flags ) =
807 GetMemberDetails( $resbor, 0 );
808 my $branches = GetBranches();
810 $branches->{ $res->{'branchcode'} }->{'branchname'};
811 $needsconfirmation{RESERVE_WAITING} =
812 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
814 # CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'}); Doesn't belong in a checking subroutine.
816 elsif ( $restype eq "Reserved" ) {
818 # The item is on reserve for someone else.
819 my ( $resborrower, $flags ) =
820 GetMemberDetails( $resbor, 0 );
821 my $branches = GetBranches();
823 $branches->{ $res->{'branchcode'} }->{'branchname'};
824 $needsconfirmation{RESERVED} =
825 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
828 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" )
830 if ( $borrower->{'categorycode'} eq 'W' ) {
831 my %issuingimpossible;
832 return ( \%issuingimpossible, \%needsconfirmation );
835 return ( \%issuingimpossible, \%needsconfirmation );
839 return ( \%issuingimpossible, \%needsconfirmation );
845 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
847 &AddIssue($borrower,$barcode,$date)
851 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
853 =item C<$barcode> is the bar code of the book being issued.
855 =item C<$date> contains the max date of return. calculated if empty.
857 AddIssue does the following things :
858 - step 0�: check that there is a borrowernumber & a barcode provided
859 - check for RENEWAL (book issued & being issued to the same patron)
860 - renewal YES = Calculate Charge & renew
862 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
864 - fill reserve if reserve to this patron
865 - cancel reserve or not, otherwise
866 * TRANSFERT PENDING ?
867 - complete the transfert
875 my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
877 my $dbh = C4::Context->dbh;
878 if ($borrower and $barcode){
879 # my ($borrower, $flags) = &GetMemberDetails($borrowernumber, 0);
880 # find which item we issue
881 my $item = GetItem('', $barcode);
883 # get actual issuing if there is one
884 my $actualissue = GetItemIssue( $item->{itemnumber});
886 # get biblioinformation for this item
887 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
890 # check if we just renew the issue.
892 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
893 # we renew, do we need to add some charge ?
894 my ( $charge, $itemtype ) = GetIssuingCharges(
895 $item->{'itemnumber'},
896 $borrower->{'borrowernumber'}
900 $item->{'itemnumber'},
901 $borrower->{'borrowernumber'}, $charge
903 $item->{'charge'} = $charge;
906 C4::Context->userenv->{'branch'},
908 '', $item->{'itemnumber'},
909 $biblio->{'itemtype'}, $borrower->{'borrowernumber'}
912 $borrower->{'borrowernumber'},
913 $item->{'itemnumber'}
916 else {# it's NOT a renewal
917 if ( $actualissue->{borrowernumber}) {
918 # This book is currently on loan, but not to the person
919 # who wants to borrow it now. mark it returned before issuing to the new borrower
922 C4::Context->userenv->{'branch'}
926 # See if the item is on reserve.
927 my ( $restype, $res ) =
928 CheckReserves( $item->{'itemnumber'} );
930 my $resbor = $res->{'borrowernumber'};
931 if ( $resbor eq $borrower->{'borrowernumber'} ) {
933 # The item is reserved by the current patron
936 elsif ( $restype eq "Waiting" ) {
939 # The item is on reserve and waiting, but has been
940 # reserved by some other patron.
941 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
942 my $branches = GetBranches();
944 $branches->{ $res->{'branchcode'} }->{'branchname'};
945 if ($cancelreserve) {
946 CancelReserve( 0, $res->{'itemnumber'},
947 $res->{'borrowernumber'} );
951 # set waiting reserve to first in reserve queue as book isn't waiting now
954 $res->{'biblionumber'},
955 $res->{'borrowernumber'},
960 elsif ( $restype eq "Reserved" ) {
963 # The item is reserved by someone else.
964 my ( $resborrower, $flags ) =
965 GetMemberDetails( $resbor, 0 );
966 my $branches = GetBranches();
968 $branches->{ $res->{'branchcode'} }->{'branchname'};
969 if ($cancelreserve) { # cancel reserves on this item
970 CancelReserve( 0, $res->{'itemnumber'},
971 $res->{'borrowernumber'} );
976 # Starting process for transfer job (checking transfert and validate it if we have one)
977 my ($datesent) = GetTransfers($item->{'itemnumber'});
979 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
982 "UPDATE branchtransfers
983 SET datearrived = now(),
985 comments = 'Forced branchtransfert'
986 WHERE itemnumber= ? AND datearrived IS NULL"
988 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
992 # Record in the database the fact that the book was issued.
996 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
999 my $loanlength = GetLoanLength(
1000 $borrower->{'categorycode'},
1001 $biblio->{'itemtype'},
1002 $borrower->{'branchcode'}
1004 my $datedue = time + ($loanlength) * 86400;
1005 my @datearr = localtime($datedue);
1007 ( 1900 + $datearr[5] ) . "-"
1008 . ( $datearr[4] + 1 ) . "-"
1014 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
1015 if ( C4::Context->preference('ReturnBeforeExpiry')
1016 && $dateduef gt $borrower->{dateexpiry} )
1018 $dateduef = $borrower->{dateexpiry};
1021 $borrower->{'borrowernumber'},
1022 $item->{'itemnumber'},
1023 strftime( "%Y-%m-%d", localtime ),$dateduef, C4::Context->userenv->{'branch'}
1026 $item->{'issues'}++;
1029 "UPDATE items SET issues=?, holdingbranch=?, itemlost=0, datelastborrowed = now() WHERE itemnumber=?");
1032 C4::Context->userenv->{'branch'},
1033 $item->{'itemnumber'}
1036 &ModDateLastSeen( $item->{'itemnumber'} );
1037 # If it costs to borrow this book, charge it to the patron's account.
1038 my ( $charge, $itemtype ) = GetIssuingCharges(
1039 $item->{'itemnumber'},
1040 $borrower->{'borrowernumber'}
1042 if ( $charge > 0 ) {
1044 $item->{'itemnumber'},
1045 $borrower->{'borrowernumber'}, $charge
1047 $item->{'charge'} = $charge;
1050 # Record the fact that this book was issued.
1052 C4::Context->userenv->{'branch'},
1054 '', $item->{'itemnumber'},
1055 $item->{'itemtype'}, $borrower->{'borrowernumber'}
1059 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'})
1060 if C4::Context->preference("IssueLog");
1064 =head2 GetLoanLength
1066 Get loan length for an itemtype, a borrower type and a branch
1068 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1073 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1074 my $dbh = C4::Context->dbh;
1077 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=?"
1080 # try to find issuelength & return the 1st available.
1081 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1082 $sth->execute( $borrowertype, $itemtype, $branchcode );
1083 my $loanlength = $sth->fetchrow_hashref;
1084 return $loanlength->{issuelength}
1085 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1087 $sth->execute( $borrowertype, $itemtype, "" );
1088 $loanlength = $sth->fetchrow_hashref;
1089 return $loanlength->{issuelength}
1090 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1092 $sth->execute( $borrowertype, "*", $branchcode );
1093 $loanlength = $sth->fetchrow_hashref;
1094 return $loanlength->{issuelength}
1095 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1097 $sth->execute( "*", $itemtype, $branchcode );
1098 $loanlength = $sth->fetchrow_hashref;
1099 return $loanlength->{issuelength}
1100 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1102 $sth->execute( $borrowertype, "*", "" );
1103 $loanlength = $sth->fetchrow_hashref;
1104 return $loanlength->{issuelength}
1105 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1107 $sth->execute( "*", "*", $branchcode );
1108 $loanlength = $sth->fetchrow_hashref;
1109 return $loanlength->{issuelength}
1110 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1112 $sth->execute( "*", $itemtype, "" );
1113 $loanlength = $sth->fetchrow_hashref;
1114 return $loanlength->{issuelength}
1115 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1117 $sth->execute( "*", "*", "" );
1118 $loanlength = $sth->fetchrow_hashref;
1119 return $loanlength->{issuelength}
1120 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1122 # if no rule is set => 21 days (hardcoded)
1128 ($doreturn, $messages, $iteminformation, $borrower) =
1129 &AddReturn($barcode, $branch);
1133 C<$barcode> is the bar code of the book being returned. C<$branch> is
1134 the code of the branch where the book is being returned.
1136 C<&AddReturn> returns a list of four items:
1138 C<$doreturn> is true iff the return succeeded.
1140 C<$messages> is a reference-to-hash giving the reason for failure:
1146 No item with this barcode exists. The value is C<$barcode>.
1150 The book is not currently on loan. The value is C<$barcode>.
1152 =item C<IsPermanent>
1154 The book's home branch is a permanent collection. If you have borrowed
1155 this book, you are not allowed to return it. The value is the code for
1156 the book's home branch.
1160 This book has been withdrawn/cancelled. The value should be ignored.
1164 The item was reserved. The value is a reference-to-hash whose keys are
1165 fields from the reserves table of the Koha database, and
1166 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1167 either C<Waiting>, C<Reserved>, or 0.
1171 C<$borrower> is a reference-to-hash, giving information about the
1172 patron who last borrowed the book.
1177 my ( $barcode, $branch ) = @_;
1178 my $dbh = C4::Context->dbh;
1182 my $validTransfert = 0;
1183 my $reserveDone = 0;
1185 # get information on item
1186 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1187 unless ($iteminformation->{'itemnumber'} ) {
1188 $messages->{'BadBarcode'} = $barcode;
1192 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1193 $messages->{'NotIssued'} = $barcode;
1197 # check if the book is in a permanent collection....
1198 my $hbr = $iteminformation->{'homebranch'};
1199 my $branches = GetBranches();
1200 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1201 $messages->{'IsPermanent'} = $hbr;
1204 # check that the book has been cancelled
1205 if ( $iteminformation->{'wthdrawn'} ) {
1206 $messages->{'wthdrawn'} = 1;
1210 # new op dev : if the book returned in an other branch update the holding branch
1212 # update issues, thereby returning book (should push this out into another subroutine
1213 $borrower = GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1215 # case of a return of document (deal with issues and holdingbranch)
1220 "UPDATE issues SET returndate = now() WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (returndate IS NULL)"
1222 $sth->execute( $borrower->{'borrowernumber'},
1223 $iteminformation->{'itemnumber'} );
1224 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1227 # continue to deal with returns cases, but not only if we have an issue
1229 # the holdingbranch is updated if the document is returned in an other location .
1230 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} )
1232 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1233 # reload iteminformation holdingbranch with the userenv value
1234 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1236 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1237 ($borrower) = GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1239 # fix up the accounts.....
1240 if ( $iteminformation->{'itemlost'} ) {
1241 $messages->{'WasLost'} = 1;
1244 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1245 # check if we have a transfer for this document
1246 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1248 # if we have a transfer to do, we update the line of transfers with the datearrived
1250 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1253 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1255 $sth->execute( $iteminformation->{'itemnumber'} );
1257 # now we check if there is a reservation with the validate of transfer if we have one, we can set it with the status 'W'
1258 SetWaitingStatus( $iteminformation->{'itemnumber'} );
1261 $messages->{'WrongTransfer'} = $tobranch;
1262 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1264 $validTransfert = 1;
1267 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1268 # fix up the accounts.....
1269 if ($iteminformation->{'itemlost'}) {
1270 FixAccountForLostAndReturned($iteminformation, $borrower);
1271 $messages->{'WasLost'} = 1;
1273 # fix up the overdues in accounts...
1274 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1275 $iteminformation->{'itemnumber'} );
1277 # find reserves.....
1278 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1279 my ( $resfound, $resrec ) =
1280 CheckReserves( $iteminformation->{'itemnumber'} );
1282 $resrec->{'ResFound'} = $resfound;
1283 $messages->{'ResFound'} = $resrec;
1288 # Record the fact that this book was returned.
1290 $branch, 'return', '0', '',
1291 $iteminformation->{'itemnumber'},
1292 $iteminformation->{'itemtype'},
1293 $borrower->{'borrowernumber'}
1296 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'})
1297 if C4::Context->preference("ReturnLog");
1299 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1300 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1302 if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1303 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1304 dotransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1305 $messages->{'WasTransfered'} = 1;
1306 warn "was transfered";
1310 return ( $doreturn, $messages, $iteminformation, $borrower );
1313 =head2 FixOverduesOnReturn
1315 &FixOverduesOnReturn($brn,$itm);
1317 C<$brn> borrowernumber
1321 internal function, called only by AddReturn
1325 sub FixOverduesOnReturn {
1326 my ( $borrowernumber, $item ) = @_;
1327 my $dbh = C4::Context->dbh;
1329 # check for overdue fine
1332 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1334 $sth->execute( $borrowernumber, $item );
1336 # alter fine to show that the book has been returned
1337 if ( my $data = $sth->fetchrow_hashref ) {
1340 "UPDATE accountlines SET accounttype='F' WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accountno = ?)"
1342 $usth->execute( $borrowernumber, $item, $data->{'accountno'} );
1349 =head2 FixAccountForLostAndReturned
1351 &FixAccountForLostAndReturned($iteminfo,$borrower);
1353 Calculates the charge for a book lost and returned (Not exported & used only once)
1355 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1357 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1359 Internal function, called by AddReturn
1363 sub FixAccountForLostAndReturned {
1364 my ($iteminfo, $borrower) = @_;
1366 my $dbh = C4::Context->dbh;
1367 my $itm = $iteminfo->{'itemnumber'};
1368 # check for charge made for lost book
1369 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1370 $sth->execute($itm);
1371 if (my $data = $sth->fetchrow_hashref) {
1372 # writeoff this amount
1374 my $amount = $data->{'amount'};
1375 my $acctno = $data->{'accountno'};
1377 if ($data->{'amountoutstanding'} == $amount) {
1378 $offset = $data->{'amount'};
1381 $offset = $amount - $data->{'amountoutstanding'};
1382 $amountleft = $data->{'amountoutstanding'} - $amount;
1384 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1385 WHERE (borrowernumber = ?)
1386 AND (itemnumber = ?) AND (accountno = ?) ");
1387 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1389 #check if any credit is left if so writeoff other accounts
1390 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1391 if ($amountleft < 0){
1394 if ($amountleft > 0){
1395 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1396 AND (amountoutstanding >0) ORDER BY date");
1397 $msth->execute($data->{'borrowernumber'});
1398 # offset transactions
1401 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1402 if ($accdata->{'amountoutstanding'} < $amountleft) {
1404 $amountleft -= $accdata->{'amountoutstanding'};
1406 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1409 my $thisacct = $accdata->{'accountno'};
1410 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1411 WHERE (borrowernumber = ?)
1412 AND (accountno=?)");
1413 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1415 $usth = $dbh->prepare("INSERT INTO accountoffsets
1416 (borrowernumber, accountno, offsetaccount, offsetamount)
1419 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1424 if ($amountleft > 0){
1427 my $desc="Book Returned ".$iteminfo->{'barcode'};
1428 $usth = $dbh->prepare("INSERT INTO accountlines
1429 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1430 VALUES (?,?,now(),?,?,'CR',?)");
1431 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1433 $usth = $dbh->prepare("INSERT INTO accountoffsets
1434 (borrowernumber, accountno, offsetaccount, offsetamount)
1436 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1438 $usth = $dbh->prepare("UPDATE items SET paidfor='' WHERE itemnumber=?");
1439 $usth->execute($itm);
1448 $issues = &GetBorrowerIssue($itemnumber);
1450 Returns patrons currently having a book. nothing if item is not issued atm
1452 C<$itemnumber> is the itemnumber
1454 Returns an array of hashes
1458 my ( $itemnumber) = @_;
1459 return unless $itemnumber;
1460 my $dbh = C4::Context->dbh;
1464 my $today = POSIX::strftime("%Y%m%d", localtime);
1466 my $sth = $dbh->prepare(
1467 "SELECT * FROM issues
1468 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1470 issues.itemnumber=? AND returndate IS NULL ");
1471 $sth->execute($itemnumber);
1472 my $data = $sth->fetchrow_hashref;
1473 my $datedue = $data->{'date_due'};
1475 if ( $datedue < $today ) {
1476 $data->{'overdue'} = 1;
1478 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1483 =head2 GetItemIssues
1485 $issues = &GetBorrowerIssues($itemnumber, $history);
1487 Returns patrons that have issued a book
1489 C<$itemnumber> is the itemnumber
1490 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1492 Returns an array of hashes
1496 my ( $itemnumber,$history ) = @_;
1497 my $dbh = C4::Context->dbh;
1501 my $today = POSIX::strftime("%Y%m%d", localtime);
1503 my $sth = $dbh->prepare(
1504 "SELECT * FROM issues
1506 itemnumber=?".($history?"":" AND returndate IS NULL ").
1507 "ORDER BY issues.date_due DESC"
1509 $sth->execute($itemnumber);
1510 while ( my $data = $sth->fetchrow_hashref ) {
1511 my $datedue = $data->{'date_due'};
1513 if ( $datedue < $today ) {
1514 $data->{'overdue'} = 1;
1516 my $itemnumber = $data->{'itemnumber'};
1518 push @GetItemIssues, $data;
1521 return ( \@GetItemIssues );
1524 =head2 GetBorrowerIssues
1526 $issues = &GetBorrowerIssues($borrower);
1528 Returns a list of books currently on loan to a patron.
1530 C<$borrower->{borrowernumber}> is the borrower number of the patron
1531 whose issues we want to list.
1533 C<&GetBorrowerIssues> returns a PHP-style array: C<$issues> is a
1534 reference-to-hash whose keys are integers in the range 1...I<n>, where
1535 I<n> is the number of items on issue (either today or before today).
1536 C<$issues-E<gt>{I<n>}> is a reference-to-hash whose keys are all of
1537 the fields of the biblio, biblioitems, items, and issues fields of the
1538 Koha database for that particular item.
1542 sub GetBorrowerIssues {
1543 my ( $borrower ) = @_;
1544 my $dbh = C4::Context->dbh;
1545 my @GetBorrowerIssues;
1547 my $today = POSIX::strftime("%Y%m%d", localtime);
1549 my $sth = $dbh->prepare(
1550 "SELECT * FROM issues
1551 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1552 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1553 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1555 borrowernumber=? AND returndate IS NULL
1556 ORDER BY issues.date_due"
1558 $sth->execute($borrower->{'borrowernumber'});
1559 while ( my $data = $sth->fetchrow_hashref ) {
1560 my $datedue = $data->{'date_due'};
1562 if ( $datedue < $today ) {
1563 $data->{'overdue'} = 1;
1565 my $itemnumber = $data->{'itemnumber'};
1567 push @GetBorrowerIssues, $data;
1570 return ( \@GetBorrowerIssues );
1573 =head2 GetBiblioIssues
1575 $issues = GetBiblioIssues($biblionumber);
1577 this function get all issues from a biblionumber.
1580 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1581 tables issues and the firstname,surname & cardnumber from borrowers.
1585 sub GetBiblioIssues {
1586 my $biblionumber = shift;
1587 return undef unless $biblionumber;
1588 my $dbh = C4::Context->dbh;
1590 SELECT issues.*,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1592 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1593 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1594 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1595 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1596 WHERE biblio.biblionumber = ?
1597 ORDER BY issues.timestamp
1599 my $sth = $dbh->prepare($query);
1600 $sth->execute($biblionumber);
1603 while ( my $data = $sth->fetchrow_hashref ) {
1604 push @issues, $data;
1609 =head2 CanBookBeRenewed
1611 $ok = &CanBookBeRenewed($borrowernumber, $itemnumber);
1613 Find out whether a borrowed item may be renewed.
1615 C<$dbh> is a DBI handle to the Koha database.
1617 C<$borrowernumber> is the borrower number of the patron who currently
1618 has the item on loan.
1620 C<$itemnumber> is the number of the item to renew.
1622 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1623 item must currently be on loan to the specified borrower; renewals
1624 must be allowed for the item's type; and the borrower must not have
1625 already renewed the loan.
1629 sub CanBookBeRenewed {
1631 # check renewal status
1632 my ( $borrowernumber, $itemnumber ) = @_;
1633 my $dbh = C4::Context->dbh;
1637 # Look in the issues table for this item, lent to this borrower,
1638 # and not yet returned.
1640 # FIXME - I think this function could be redone to use only one SQL call.
1641 my $sth1 = $dbh->prepare(
1642 "SELECT * FROM issues
1643 WHERE borrowernumber = ?
1645 AND returndate IS NULL"
1647 $sth1->execute( $borrowernumber, $itemnumber );
1648 if ( my $data1 = $sth1->fetchrow_hashref ) {
1650 # Found a matching item
1652 # See if this item may be renewed. This query is convoluted
1653 # because it's a bit messy: given the item number, we need to find
1654 # the biblioitem, which gives us the itemtype, which tells us
1655 # whether it may be renewed.
1656 my $sth2 = $dbh->prepare(
1657 "SELECT renewalsallowed FROM items
1658 LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1659 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1660 WHERE items.itemnumber = ?
1663 $sth2->execute($itemnumber);
1664 if ( my $data2 = $sth2->fetchrow_hashref ) {
1665 $renews = $data2->{'renewalsallowed'};
1667 if ( $renews && $renews > $data1->{'renewals'} ) {
1671 my ( $resfound, $resrec ) = C4::Reserves2::CheckReserves($itemnumber);
1675 ( $resfound, $resrec ) = C4::Reserves2::CheckReserves($itemnumber);
1682 return ($renewokay);
1687 &AddRenewal($borrowernumber, $itemnumber, $datedue);
1691 C<$borrowernumber> is the borrower number of the patron who currently
1694 C<$itemnumber> is the number of the item to renew.
1696 C<$datedue> can be used to set the due date. If C<$datedue> is the
1697 empty string, C<&AddRenewal> will calculate the due date automatically
1698 from the book's item type. If you wish to set the due date manually,
1699 C<$datedue> should be in the form YYYY-MM-DD.
1705 my ( $borrowernumber, $itemnumber, $datedue ) = @_;
1706 my $dbh = C4::Context->dbh;
1708 # If the due date wasn't specified, calculate it by adding the
1709 # book's loan length to today's date.
1710 if ( $datedue eq "" ) {
1712 my $biblio = GetBiblioFromItemNumber($itemnumber);
1713 my $borrower = GetMemberDetails( $borrowernumber, 0 );
1714 my $loanlength = GetLoanLength(
1715 $borrower->{'categorycode'},
1716 $biblio->{'itemtype'},
1717 $borrower->{'branchcode'}
1719 my ( $due_year, $due_month, $due_day ) =
1720 Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
1721 $datedue = "$due_year-$due_month-$due_day";
1725 # Find the issues record for this book
1727 $dbh->prepare("SELECT * FROM issues
1728 WHERE borrowernumber=?
1730 AND returndate IS NULL"
1732 $sth->execute( $borrowernumber, $itemnumber );
1733 my $issuedata = $sth->fetchrow_hashref;
1736 # Update the issues record to have the new due date, and a new count
1737 # of how many times it has been renewed.
1738 my $renews = $issuedata->{'renewals'} + 1;
1739 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1740 WHERE borrowernumber=?
1742 AND returndate IS NULL"
1744 $sth->execute( $datedue, $renews, $borrowernumber, $itemnumber );
1748 UpdateStats( C4::Context->userenv->{'branchcode'}, 'renew', '', '', $itemnumber );
1750 # Charge a new rental fee, if applicable?
1751 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1752 if ( $charge > 0 ) {
1753 my $accountno = getnextacctno( $borrowernumber );
1754 my $item = GetBiblioFromItemNumber($itemnumber);
1755 $sth = $dbh->prepare(
1756 "INSERT INTO accountlines
1757 (borrowernumber,accountno,date,amount,
1758 description,accounttype,amountoutstanding,
1760 VALUES (?,?,now(),?,?,?,?,?)"
1762 $sth->execute( $borrowernumber, $accountno, $charge,
1763 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1764 'Rent', $charge, $itemnumber );
1769 =head2 GetIssuingCharges
1771 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1773 Calculate how much it would cost for a given patron to borrow a given
1774 item, including any applicable discounts.
1776 C<$itemnumber> is the item number of item the patron wishes to borrow.
1778 C<$borrowernumber> is the patron's borrower number.
1780 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1781 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1786 sub GetIssuingCharges {
1788 # calculate charges due
1789 my ( $itemnumber, $borrowernumber ) = @_;
1791 my $dbh = C4::Context->dbh;
1794 # Get the book's item type and rental charge (via its biblioitem).
1795 my $sth1 = $dbh->prepare(
1796 "SELECT itemtypes.itemtype,rentalcharge FROM items
1797 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1798 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1799 WHERE items.itemnumber =?
1802 $sth1->execute($itemnumber);
1803 if ( my $data1 = $sth1->fetchrow_hashref ) {
1804 $item_type = $data1->{'itemtype'};
1805 $charge = $data1->{'rentalcharge'};
1806 my $q2 = "SELECT rentaldiscount FROM borrowers
1807 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1808 WHERE borrowers.borrowernumber = ?
1809 AND issuingrules.itemtype = ?";
1810 my $sth2 = $dbh->prepare($q2);
1811 $sth2->execute( $borrowernumber, $item_type );
1812 if ( my $data2 = $sth2->fetchrow_hashref ) {
1813 my $discount = $data2->{'rentaldiscount'};
1814 if ( $discount eq 'NULL' ) {
1817 $charge = ( $charge * ( 100 - $discount ) ) / 100;
1823 return ( $charge, $item_type );
1826 =head2 AddIssuingCharge
1828 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1832 sub AddIssuingCharge {
1833 my ( $itemnumber, $borrowernumber, $charge ) = @_;
1834 my $dbh = C4::Context->dbh;
1835 my $nextaccntno = getnextacctno( $borrowernumber );
1837 INSERT INTO accountlines
1838 (borrowernumber, itemnumber, accountno,
1839 date, amount, description, accounttype,
1841 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1843 my $sth = $dbh->prepare($query);
1844 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1850 GetTransfers($itemnumber);
1855 my ($itemnumber) = @_;
1857 my $dbh = C4::Context->dbh;
1863 FROM branchtransfers
1864 WHERE itemnumber = ?
1865 AND datearrived IS NULL
1867 my $sth = $dbh->prepare($query);
1868 $sth->execute($itemnumber);
1869 my @row = $sth->fetchrow_array();
1875 =head2 GetTransfersFromTo
1877 @results = GetTransfersFromTo($frombranch,$tobranch);
1879 Returns the list of pending transfers between $from and $to branch
1883 sub GetTransfersFromTo {
1884 my ( $frombranch, $tobranch ) = @_;
1885 return unless ( $frombranch && $tobranch );
1886 my $dbh = C4::Context->dbh;
1888 SELECT itemnumber,datesent,frombranch
1889 FROM branchtransfers
1892 AND datearrived IS NULL
1894 my $sth = $dbh->prepare($query);
1895 $sth->execute( $frombranch, $tobranch );
1898 while ( my $data = $sth->fetchrow_hashref ) {
1899 push @gettransfers, $data;
1902 return (@gettransfers);
1905 =head2 DeleteTransfer
1907 &DeleteTransfer($itemnumber);
1911 sub DeleteTransfer {
1912 my ($itemnumber) = @_;
1913 my $dbh = C4::Context->dbh;
1914 my $sth = $dbh->prepare(
1915 "DELETE FROM branchtransfers
1917 AND datearrived IS NULL "
1919 $sth->execute($itemnumber);
1923 =head2 AnonymiseIssueHistory
1925 $rows = AnonymiseIssueHistory($borrowernumber,$date)
1927 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
1928 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
1930 return the number of affected rows.
1934 sub AnonymiseIssueHistory {
1936 my $borrowernumber = shift;
1937 my $dbh = C4::Context->dbh;
1940 SET borrowernumber = NULL
1941 WHERE returndate < '".$date."'
1942 AND borrowernumber IS NOT NULL
1944 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
1945 my $rows_affected = $dbh->do($query);
1946 return $rows_affected;
1949 =head2 updateWrongTransfer
1951 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
1953 This function validate the line of brachtransfer but with the wrong destination (mistake from a librarian ...), and create a new line in branchtransfer from the actual library to the original library of reservation
1957 sub updateWrongTransfer {
1958 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
1959 my $dbh = C4::Context->dbh;
1960 # first step validate the actual line of transfert .
1963 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
1965 $sth->execute($FromLibrary,$itemNumber);
1968 # second step create a new line of branchtransfer to the right location .
1969 dotransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
1971 #third step changing holdingbranch of item
1972 UpdateHoldingbranch($FromLibrary,$itemNumber);
1975 =head2 UpdateHoldingbranch
1977 $items = UpdateHoldingbranch($branch,$itmenumber);
1978 Simple methode for updating hodlingbranch in items BDD line
1981 sub UpdateHoldingbranch {
1982 my ( $branch,$itmenumber ) = @_;
1983 my $dbh = C4::Context->dbh;
1984 # first step validate the actual line of transfert .
1987 "update items set holdingbranch = ? where itemnumber= ?"
1989 $sth->execute($branch,$itmenumber);
2001 Koha Developement team <info@koha.org>