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
42 use POSIX qw(strftime);
43 use C4::Branch; # GetBranches
44 use C4::Log; # logaction
48 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
51 # set the version for version checking
55 # FIXME subs that should probably be elsewhere
61 # subs to deal with issuing a book
73 &AnonymiseIssueHistory
76 # subs to deal with returns
82 # subs to deal with transfers
94 C4::Circulation - Koha circulation module
102 The functions in this module deal with circulation, issues, and
103 returns, as well as general information about the library.
104 Also deals with stocktaking.
110 =head3 $str = &decode($chunk);
114 =item Generic filter function for barcode string.
120 # 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 ?
121 # FIXME -- the &decode fcn below should be wrapped into this one.
125 my $filter = C4::Context->preference('itemBarcodeInputFilter');
126 if($filter eq 'whitespace') {
129 } elsif($filter eq 'cuecat') {
131 my @fields = split( /\./, $barcode );
132 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
133 if ( $#results == 2 ) {
139 } elsif($filter eq 'T-prefix') {
140 my $num = ( $barcode =~ /^[Tt] /) ? substr($barcode,2) + 0 : $barcode;
141 return sprintf( "T%07d",$num);
147 =head3 $str = &decode($chunk);
151 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
161 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
162 my @s = map { index( $seq, $_ ); } split( //, $encoded );
163 my $l = ( $#s + 1 ) % 4;
174 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
176 chr( ( $n >> 16 ) ^ 67 )
177 .chr( ( $n >> 8 & 255 ) ^ 67 )
178 .chr( ( $n & 255 ) ^ 67 );
181 $r = substr( $r, 0, length($r) - $l );
187 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
189 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
191 C<$newbranch> is the code for the branch to which the item should be transferred.
193 C<$barcode> is the barcode of the item to be transferred.
195 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
196 Otherwise, if an item is reserved, the transfer fails.
198 Returns three values:
202 is true if the transfer was successful.
206 is a reference-to-hash which may have any of the following keys:
212 There is no item in the catalog with the given barcode. The value is C<$barcode>.
216 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.
218 =item C<DestinationEqualsHolding>
220 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.
224 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.
228 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>.
230 =item C<WasTransferred>
232 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
239 my ( $tbr, $barcode, $ignoreRs ) = @_;
242 my $branches = GetBranches();
243 my $itemnumber = GetItemnumberFromBarcode( $barcode );
244 my $issue = GetItemIssue($itemnumber);
245 my $biblio = GetBiblioFromItemNumber($itemnumber);
248 if ( not $itemnumber ) {
249 $messages->{'BadBarcode'} = $barcode;
253 # get branches of book...
254 my $hbr = $biblio->{'homebranch'};
255 my $fbr = $biblio->{'holdingbranch'};
258 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
259 $messages->{'IsPermanent'} = $hbr;
262 # can't transfer book if is already there....
263 if ( $fbr eq $tbr ) {
264 $messages->{'DestinationEqualsHolding'} = 1;
268 # check if it is still issued to someone, return it...
269 if ($issue->{borrowernumber}) {
270 AddReturn( $barcode, $fbr );
271 $messages->{'WasReturned'} = $issue->{borrowernumber};
275 # That'll save a database query.
276 my ( $resfound, $resrec ) =
277 CheckReserves( $itemnumber );
278 if ( $resfound and not $ignoreRs ) {
279 $resrec->{'ResFound'} = $resfound;
281 # $messages->{'ResFound'} = $resrec;
285 #actually do the transfer....
287 ModItemTransfer( $itemnumber, $fbr, $tbr );
289 # don't need to update MARC anymore, we do it in batch now
290 $messages->{'WasTransfered'} = 1;
291 ModDateLastSeen( $itemnumber );
293 return ( $dotransfer, $messages, $biblio );
296 =head2 CanBookBeIssued
298 Check if a book can be issued.
300 my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($borrower,$barcode,$year,$month,$day);
304 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
306 =item C<$barcode> is the bar code of the book being issued.
308 =item C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
316 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
317 Possible values are :
323 sticky due date is invalid
327 borrower gone with no address
331 borrower declared it's card lost
337 =head3 UNKNOWN_BARCODE
351 item is restricted (set by ??)
353 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
354 Possible values are :
362 renewing, not issuing
364 =head3 ISSUED_TO_ANOTHER
366 issued to someone else.
370 reserved for someone else.
374 sticky due date is invalid
378 if the borrower borrows to much things
382 # check if a book can be issued.
386 my $borrower = shift;
387 my $biblionumber = shift;
389 my $cat_borrower = $borrower->{'categorycode'};
390 my $dbh = C4::Context->dbh;
392 # Get which branchcode we need
393 if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
394 $branch = C4::Context->userenv->{'branch'};
396 elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
397 $branch = $borrower->{'branchcode'};
401 $branch = $item->{'homebranch'};
403 my $type = (C4::Context->preference('item-level_itypes'))
404 ? $item->{'itype'} # item-level
405 : $item->{'itemtype'}; # biblio-level
409 'SELECT * FROM issuingrules
410 WHERE categorycode = ?
415 my $query2 = "SELECT COUNT(*) FROM issues i, biblioitems s1, items s2
416 WHERE i.borrowernumber = ?
417 AND i.itemnumber = s2.itemnumber
418 AND s1.biblioitemnumber = s2.biblioitemnumber";
419 if (C4::Context->preference('item-level_itypes')){
420 $query2.=" AND s2.itype=? ";
422 $query2.=" AND s1.itemtype= ? ";
424 my $sth2= $dbh->prepare($query2);
427 'SELECT COUNT(*) FROM issues
428 WHERE borrowernumber = ?'
432 # check the 3 parameters (branch / itemtype / category code
433 $sth->execute( $cat_borrower, $type, $branch );
434 my $result = $sth->fetchrow_hashref;
435 # warn "$cat_borrower, $type, $branch = ".Data::Dumper::Dumper($result);
437 if ( $result->{maxissueqty} ne '' ) {
438 # warn "checking on everything set";
439 $sth2->execute( $borrower->{'borrowernumber'}, $type );
440 my $alreadyissued = $sth2->fetchrow;
441 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
442 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/itemtype failed)" );
444 # now checking for total
445 $sth->execute( $cat_borrower, '*', $branch );
446 my $result = $sth->fetchrow_hashref;
447 if ( $result->{maxissueqty} ne '' ) {
448 $sth2->execute( $borrower->{'borrowernumber'}, $type );
449 my $alreadyissued = $sth2->fetchrow;
450 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
451 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/total failed)" );
456 # check the 2 parameters (branch / itemtype / default categorycode
457 $sth->execute( '*', $type, $branch );
458 $result = $sth->fetchrow_hashref;
459 # warn "*, $type, $branch = ".Data::Dumper::Dumper($result);
461 if ( $result->{maxissueqty} ne '' ) {
462 # warn "checking on 2 parameters (default categorycode)";
463 $sth2->execute( $borrower->{'borrowernumber'}, $type );
464 my $alreadyissued = $sth2->fetchrow;
465 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
466 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / itemtype failed)" );
468 # now checking for total
469 $sth->execute( '*', '*', $branch );
470 my $result = $sth->fetchrow_hashref;
471 if ( $result->{maxissueqty} ne '' ) {
472 $sth2->execute( $borrower->{'borrowernumber'}, $type );
473 my $alreadyissued = $sth2->fetchrow;
474 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
475 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / total failed)" );
480 # check the 1 parameters (default branch / itemtype / categorycode
481 $sth->execute( $cat_borrower, $type, '*' );
482 $result = $sth->fetchrow_hashref;
483 # warn "$cat_borrower, $type, * = ".Data::Dumper::Dumper($result);
485 if ( $result->{maxissueqty} ne '' ) {
486 # warn "checking on 1 parameter (default branch + categorycode)";
487 $sth2->execute( $borrower->{'borrowernumber'}, $type );
488 my $alreadyissued = $sth2->fetchrow;
489 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
490 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch/category/itemtype failed)" );
492 # now checking for total
493 $sth->execute( $cat_borrower, '*', '*' );
494 my $result = $sth->fetchrow_hashref;
495 if ( $result->{maxissueqty} ne '' ) {
496 $sth2->execute( $borrower->{'borrowernumber'}, $type );
497 my $alreadyissued = $sth2->fetchrow;
498 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
499 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / category / total failed)" );
504 # check the 0 parameters (default branch / itemtype / default categorycode
505 $sth->execute( '*', $type, '*' );
506 $result = $sth->fetchrow_hashref;
507 # warn "*, $type, * = ".Data::Dumper::Dumper($result);
509 if ( $result->{maxissueqty} ne '' ) {
510 # warn "checking on default branch and default categorycode";
511 $sth2->execute( $borrower->{'borrowernumber'}, $type );
512 my $alreadyissued = $sth2->fetchrow;
513 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
514 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / itemtype failed)" );
517 # now checking for total
518 $sth->execute( '*', '*', '*' );
519 $result = $sth->fetchrow_hashref;
520 if ( $result->{maxissueqty} ne '' ) {
521 warn "checking total";
522 $sth2->execute( $borrower->{'borrowernumber'}, $type );
523 my $alreadyissued = $sth2->fetchrow;
524 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
525 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / total failed)" );
529 # OK, the patron can issue !!!
535 @issues = &itemissues($biblioitemnumber, $biblio);
537 Looks up information about who has borrowed the bookZ<>(s) with the
538 given biblioitemnumber.
540 C<$biblio> is ignored.
542 C<&itemissues> returns an array of references-to-hash. The keys
543 include the fields from the C<items> table in the Koha database.
544 Additional keys include:
550 If the item is currently on loan, this gives the due date.
552 If the item is not on loan, then this is either "Available" or
553 "Cancelled", if the item has been withdrawn.
557 If the item is currently on loan, this gives the card number of the
558 patron who currently has the item.
560 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
562 These give the timestamp for the last three times the item was
565 =item C<card0>, C<card1>, C<card2>
567 The card number of the last three patrons who borrowed this item.
569 =item C<borrower0>, C<borrower1>, C<borrower2>
571 The borrower number of the last three patrons who borrowed this item.
579 my ( $bibitem, $biblio ) = @_;
580 my $dbh = C4::Context->dbh;
582 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
587 $sth->execute($bibitem) || die $sth->errstr;
589 while ( my $data = $sth->fetchrow_hashref ) {
591 # Find out who currently has this item.
592 # FIXME - Wouldn't it be better to do this as a left join of
593 # some sort? Currently, this code assumes that if
594 # fetchrow_hashref() fails, then the book is on the shelf.
595 # fetchrow_hashref() can fail for any number of reasons (e.g.,
596 # database server crash), not just because no items match the
598 my $sth2 = $dbh->prepare(
599 "SELECT * FROM issues
600 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
605 $sth2->execute( $data->{'itemnumber'} );
606 if ( my $data2 = $sth2->fetchrow_hashref ) {
607 $data->{'date_due'} = $data2->{'date_due'};
608 $data->{'card'} = $data2->{'cardnumber'};
609 $data->{'borrower'} = $data2->{'borrowernumber'};
612 $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
617 # Find the last 3 people who borrowed this item.
618 $sth2 = $dbh->prepare(
619 "SELECT * FROM old_issues
620 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
622 ORDER BY returndate DESC,timestamp DESC"
625 $sth2->execute( $data->{'itemnumber'} );
626 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
627 { # FIXME : error if there is less than 3 pple borrowing this item
628 if ( my $data2 = $sth2->fetchrow_hashref ) {
629 $data->{"timestamp$i2"} = $data2->{'timestamp'};
630 $data->{"card$i2"} = $data2->{'cardnumber'};
631 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
636 $results[$i] = $data;
644 =head2 CanBookBeIssued
646 ( $issuingimpossible, $needsconfirmation ) =
647 CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
648 C<$duedatespec> is a C4::Dates object.
649 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
653 sub CanBookBeIssued {
654 my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
655 my %needsconfirmation; # filled with problems that needs confirmations
656 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
657 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
658 my $issue = GetItemIssue($item->{itemnumber});
659 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
660 $item->{'itemtype'}=$item->{'itype'};
661 my $dbh = C4::Context->dbh;
664 # DUE DATE is OK ? -- should already have checked.
666 #$issuingimpossible{INVALID_DATE} = 1 unless ($duedate);
671 if ( $borrower->{'category_type'} eq 'X' && ( $item->{barcode} )) {
672 # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
673 &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
674 return( { STATS => 1 }, {});
676 if ( $borrower->{flags}->{GNA} ) {
677 $issuingimpossible{GNA} = 1;
679 if ( $borrower->{flags}->{'LOST'} ) {
680 $issuingimpossible{CARD_LOST} = 1;
682 if ( $borrower->{flags}->{'DBARRED'} ) {
683 $issuingimpossible{DEBARRED} = 1;
685 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
686 $issuingimpossible{EXPIRED} = 1;
688 my @expirydate= split /-/,$borrower->{'dateexpiry'};
689 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
690 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
691 $issuingimpossible{EXPIRED} = 1;
700 C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
701 if ( C4::Context->preference("IssuingInProcess") ) {
702 my $amountlimit = C4::Context->preference("noissuescharge");
703 if ( $amount > $amountlimit && !$inprocess ) {
704 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
706 elsif ( $amount <= $amountlimit && !$inprocess ) {
707 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
712 $needsconfirmation{DEBT} = $amount;
717 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
719 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
720 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
725 unless ( $item->{barcode} ) {
726 $issuingimpossible{UNKNOWN_BARCODE} = 1;
728 if ( $item->{'notforloan'}
729 && $item->{'notforloan'} > 0 )
731 $issuingimpossible{NOT_FOR_LOAN} = 1;
733 elsif ( !$item->{'notforloan'} ){
734 # we have to check itemtypes.notforloan also
735 if (C4::Context->preference('item-level_itypes')){
736 # this should probably be a subroutine
737 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
738 $sth->execute($item->{'itemtype'});
739 my $notforloan=$sth->fetchrow_hashref();
741 if ($notforloan->{'notforloan'} == 1){
742 $issuingimpossible{NOT_FOR_LOAN} = 1;
745 elsif ($biblioitem->{'notforloan'} == 1){
746 $issuingimpossible{NOT_FOR_LOAN} = 1;
749 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
751 $issuingimpossible{WTHDRAWN} = 1;
753 if ( $item->{'restricted'}
754 && $item->{'restricted'} == 1 )
756 $issuingimpossible{RESTRICTED} = 1;
758 if ( C4::Context->preference("IndependantBranches") ) {
759 my $userenv = C4::Context->userenv;
760 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
761 $issuingimpossible{NOTSAMEBRANCH} = 1
762 if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
767 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
769 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
772 # Already issued to current borrower. Ask whether the loan should
774 my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
775 $borrower->{'borrowernumber'},
776 $item->{'itemnumber'}
778 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
779 $issuingimpossible{NO_MORE_RENEWALS} = 1;
782 $needsconfirmation{RENEW_ISSUE} = 1;
785 elsif ($issue->{borrowernumber}) {
787 # issued to someone else
788 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
790 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
791 $needsconfirmation{ISSUED_TO_ANOTHER} =
792 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
795 # See if the item is on reserve.
796 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
798 my $resbor = $res->{'borrowernumber'};
799 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
800 my $branches = GetBranches();
801 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
802 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 $needsconfirmation{RESERVE_WAITING} =
807 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
809 elsif ( $restype eq "Reserved" ) {
810 # The item is on reserve for someone else.
811 $needsconfirmation{RESERVED} =
812 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
815 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
816 if ( $borrower->{'categorycode'} eq 'W' ) {
818 return ( \%emptyhash, \%needsconfirmation );
821 return ( \%issuingimpossible, \%needsconfirmation );
826 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
828 &AddIssue($borrower,$barcode,$date)
832 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
834 =item C<$barcode> is the bar code of the book being issued.
836 =item C<$date> contains the max date of return. calculated if empty.
838 AddIssue does the following things :
839 - step 01: check that there is a borrowernumber & a barcode provided
840 - check for RENEWAL (book issued & being issued to the same patron)
841 - renewal YES = Calculate Charge & renew
843 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
845 - fill reserve if reserve to this patron
846 - cancel reserve or not, otherwise
847 * TRANSFERT PENDING ?
848 - complete the transfert
856 my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
857 my $dbh = C4::Context->dbh;
858 my $barcodecheck=CheckValidBarcode($barcode);
859 if ($borrower and $barcode and $barcodecheck ne '0'){
860 # find which item we issue
861 my $item = GetItem('', $barcode);
865 # Get which branchcode we need
866 if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
867 $branch = C4::Context->userenv->{'branch'};
869 elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
870 $branch = $borrower->{'branchcode'};
874 $branch = $item->{'homebranch'};
877 # get actual issuing if there is one
878 my $actualissue = GetItemIssue( $item->{itemnumber});
880 # get biblioinformation for this item
881 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
884 # check if we just renew the issue.
886 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
888 $borrower->{'borrowernumber'},
889 $item->{'itemnumber'},
897 if ( $actualissue->{borrowernumber}) {
898 # This book is currently on loan, but not to the person
899 # who wants to borrow it now. mark it returned before issuing to the new borrower
902 C4::Context->userenv->{'branch'}
906 # See if the item is on reserve.
907 my ( $restype, $res ) =
908 C4::Reserves::CheckReserves( $item->{'itemnumber'} );
910 my $resbor = $res->{'borrowernumber'};
911 if ( $resbor eq $borrower->{'borrowernumber'} ) {
913 # The item is reserved by the current patron
914 ModReserveFill($res);
916 elsif ( $restype eq "Waiting" ) {
919 # The item is on reserve and waiting, but has been
920 # reserved by some other patron.
921 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
922 my $branches = GetBranches();
924 $branches->{ $res->{'branchcode'} }->{'branchname'};
926 elsif ( $restype eq "Reserved" ) {
929 # The item is reserved by someone else.
930 my ( $resborrower, $flags ) =
931 GetMemberDetails( $resbor, 0 );
932 my $branches = GetBranches();
933 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
934 if ($cancelreserve) { # cancel reserves on this item
935 CancelReserve( 0, $res->{'itemnumber'},
936 $res->{'borrowernumber'} );
939 if ($cancelreserve) {
940 CancelReserve( $res->{'biblionumber'}, 0,
941 $res->{'borrowernumber'} );
944 # set waiting reserve to first in reserve queue as book isn't waiting now
946 $res->{'biblionumber'},
947 $res->{'borrowernumber'},
953 # Starting process for transfer job (checking transfert and validate it if we have one)
954 my ($datesent) = GetTransfers($item->{'itemnumber'});
956 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
959 "UPDATE branchtransfers
960 SET datearrived = now(),
962 comments = 'Forced branchtransfer'
963 WHERE itemnumber= ? AND datearrived IS NULL"
965 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
969 # Record in the database the fact that the book was issued.
973 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
980 my $itype=(C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ;
981 my $loanlength = GetLoanLength(
982 $borrower->{'categorycode'},
986 $dateduef = CalcDateDue(C4::Dates->new(),$loanlength,$branch);
987 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
988 if ( C4::Context->preference('ReturnBeforeExpiry') && $dateduef->output('iso') gt $borrower->{dateexpiry} ) {
989 $dateduef = C4::Dates->new($borrower->{dateexpiry},'iso');
993 $borrower->{'borrowernumber'},
994 $item->{'itemnumber'},
995 strftime( "%Y-%m-%d", localtime ),$dateduef->output('iso'), C4::Context->userenv->{'branch'}
999 ModItem({ issues => $item->{'issues'},
1000 holdingbranch => C4::Context->userenv->{'branch'},
1002 datelastborrowed => C4::Dates->new()->output('iso'),
1003 onloan => $dateduef->output('iso'),
1004 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1005 ModDateLastSeen( $item->{'itemnumber'} );
1007 # If it costs to borrow this book, charge it to the patron's account.
1008 my ( $charge, $itemtype ) = GetIssuingCharges(
1009 $item->{'itemnumber'},
1010 $borrower->{'borrowernumber'}
1012 if ( $charge > 0 ) {
1014 $item->{'itemnumber'},
1015 $borrower->{'borrowernumber'}, $charge
1017 $item->{'charge'} = $charge;
1020 # Record the fact that this book was issued.
1022 C4::Context->userenv->{'branch'},
1024 '', $item->{'itemnumber'},
1025 $item->{'itemtype'}, $borrower->{'borrowernumber'}
1029 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'})
1030 if C4::Context->preference("IssueLog");
1035 =head2 GetLoanLength
1037 Get loan length for an itemtype, a borrower type and a branch
1039 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1044 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1045 my $dbh = C4::Context->dbh;
1048 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1050 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1051 # try to find issuelength & return the 1st available.
1052 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1053 $sth->execute( $borrowertype, $itemtype, $branchcode );
1054 my $loanlength = $sth->fetchrow_hashref;
1055 return $loanlength->{issuelength}
1056 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1058 $sth->execute( $borrowertype, $itemtype, "*" );
1059 $loanlength = $sth->fetchrow_hashref;
1060 return $loanlength->{issuelength}
1061 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1063 $sth->execute( $borrowertype, "*", $branchcode );
1064 $loanlength = $sth->fetchrow_hashref;
1065 return $loanlength->{issuelength}
1066 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1068 $sth->execute( "*", $itemtype, $branchcode );
1069 $loanlength = $sth->fetchrow_hashref;
1070 return $loanlength->{issuelength}
1071 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1073 $sth->execute( $borrowertype, "*", "*" );
1074 $loanlength = $sth->fetchrow_hashref;
1075 return $loanlength->{issuelength}
1076 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1078 $sth->execute( "*", "*", $branchcode );
1079 $loanlength = $sth->fetchrow_hashref;
1080 return $loanlength->{issuelength}
1081 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1083 $sth->execute( "*", $itemtype, "*" );
1084 $loanlength = $sth->fetchrow_hashref;
1085 return $loanlength->{issuelength}
1086 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1088 $sth->execute( "*", "*", "*" );
1089 $loanlength = $sth->fetchrow_hashref;
1090 return $loanlength->{issuelength}
1091 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1093 # if no rule is set => 21 days (hardcoded)
1099 ($doreturn, $messages, $iteminformation, $borrower) =
1100 &AddReturn($barcode, $branch, $exemptfine);
1104 C<$barcode> is the bar code of the book being returned. C<$branch> is
1105 the code of the branch where the book is being returned. C<$exemptfine>
1106 indicates that overdue charges for the item will not be applied.
1108 C<&AddReturn> returns a list of four items:
1110 C<$doreturn> is true iff the return succeeded.
1112 C<$messages> is a reference-to-hash giving the reason for failure:
1118 No item with this barcode exists. The value is C<$barcode>.
1122 The book is not currently on loan. The value is C<$barcode>.
1124 =item C<IsPermanent>
1126 The book's home branch is a permanent collection. If you have borrowed
1127 this book, you are not allowed to return it. The value is the code for
1128 the book's home branch.
1132 This book has been withdrawn/cancelled. The value should be ignored.
1136 The item was reserved. The value is a reference-to-hash whose keys are
1137 fields from the reserves table of the Koha database, and
1138 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1139 either C<Waiting>, C<Reserved>, or 0.
1143 C<$borrower> is a reference-to-hash, giving information about the
1144 patron who last borrowed the book.
1149 my ( $barcode, $branch, $exemptfine ) = @_;
1150 my $dbh = C4::Context->dbh;
1154 my $validTransfert = 0;
1155 my $reserveDone = 0;
1157 # get information on item
1158 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1159 my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1160 # use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);
1161 unless ($iteminformation->{'itemnumber'} ) {
1162 $messages->{'BadBarcode'} = $barcode;
1166 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1167 $messages->{'NotIssued'} = $barcode;
1171 # check if the book is in a permanent collection....
1172 my $hbr = $iteminformation->{'homebranch'};
1173 my $branches = GetBranches();
1174 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1175 $messages->{'IsPermanent'} = $hbr;
1178 # if independent branches are on and returning to different branch, refuse the return
1179 if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1180 $messages->{'Wrongbranch'} = 1;
1184 # check that the book has been cancelled
1185 if ( $iteminformation->{'wthdrawn'} ) {
1186 $messages->{'wthdrawn'} = 1;
1190 # new op dev : if the book returned in an other branch update the holding branch
1192 # update issues, thereby returning book (should push this out into another subroutine
1193 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1195 # case of a return of document (deal with issues and holdingbranch)
1198 MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
1199 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1202 # continue to deal with returns cases, but not only if we have an issue
1204 # the holdingbranch is updated if the document is returned in an other location .
1205 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1206 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1207 # reload iteminformation holdingbranch with the userenv value
1208 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1210 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1211 ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1213 if ($iteminformation->{borrowernumber}){
1214 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1216 # fix up the accounts.....
1217 if ( $iteminformation->{'itemlost'} ) {
1218 $messages->{'WasLost'} = 1;
1221 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1222 # check if we have a transfer for this document
1223 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1225 # if we have a transfer to do, we update the line of transfers with the datearrived
1227 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1230 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1232 $sth->execute( $iteminformation->{'itemnumber'} );
1234 # 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'
1235 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1238 $messages->{'WrongTransfer'} = $tobranch;
1239 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1241 $validTransfert = 1;
1244 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1245 # fix up the accounts.....
1246 if ($iteminformation->{'itemlost'}) {
1247 FixAccountForLostAndReturned($iteminformation, $borrower);
1248 $messages->{'WasLost'} = 1;
1250 # fix up the overdues in accounts...
1251 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1252 $iteminformation->{'itemnumber'}, $exemptfine );
1254 # find reserves.....
1255 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1256 my ( $resfound, $resrec ) =
1257 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1259 $resrec->{'ResFound'} = $resfound;
1260 $messages->{'ResFound'} = $resrec;
1265 # Record the fact that this book was returned.
1267 $branch, 'return', '0', '',
1268 $iteminformation->{'itemnumber'},
1269 $biblio->{'itemtype'},
1270 $borrower->{'borrowernumber'}
1273 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'})
1274 if C4::Context->preference("ReturnLog");
1276 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1277 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1279 if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1280 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1281 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1282 $messages->{'WasTransfered'} = 1;
1285 $messages->{'NeedsTransfer'} = 1;
1289 return ( $doreturn, $messages, $iteminformation, $borrower );
1292 =head2 MarkIssueReturned
1296 MarkIssueReturned($borrowernumber, $itemnumber);
1300 Unconditionally marks an issue as being returned by
1301 moving the C<issues> row to C<old_issues> and
1302 setting C<returndate> to the current date.
1304 Ideally, this function would be internal to C<C4::Circulation>,
1305 not exported, but it is currently needed by one
1306 routine in C<C4::Accounts>.
1310 sub MarkIssueReturned {
1311 my ($borrowernumber, $itemnumber) = @_;
1313 my $dbh = C4::Context->dbh;
1315 my $sth_upd = $dbh->prepare("UPDATE issues SET returndate = now()
1316 WHERE borrowernumber = ?
1317 AND itemnumber = ?");
1318 $sth_upd->execute($borrowernumber, $itemnumber);
1319 my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues
1320 WHERE borrowernumber = ?
1321 AND itemnumber = ?");
1322 $sth_copy->execute($borrowernumber, $itemnumber);
1323 my $sth_del = $dbh->prepare("DELETE FROM issues
1324 WHERE borrowernumber = ?
1325 AND itemnumber = ?");
1326 $sth_del->execute($borrowernumber, $itemnumber);
1329 =head2 FixOverduesOnReturn
1331 &FixOverduesOnReturn($brn,$itm, $exemptfine);
1333 C<$brn> borrowernumber
1337 internal function, called only by AddReturn
1341 sub FixOverduesOnReturn {
1342 my ( $borrowernumber, $item, $exemptfine ) = @_;
1343 my $dbh = C4::Context->dbh;
1345 # check for overdue fine
1348 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1350 $sth->execute( $borrowernumber, $item );
1352 # alter fine to show that the book has been returned
1354 if ($data = $sth->fetchrow_hashref) {
1355 my $uquery =($exemptfine)? "update accountlines set accounttype='FFOR', amountoutstanding=0":"update accountlines set accounttype='F' ";
1356 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1357 my $usth = $dbh->prepare($uquery);
1358 $usth->execute($borrowernumber,$item ,$data->{'accountno'});
1366 =head2 FixAccountForLostAndReturned
1368 &FixAccountForLostAndReturned($iteminfo,$borrower);
1370 Calculates the charge for a book lost and returned (Not exported & used only once)
1372 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1374 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1376 Internal function, called by AddReturn
1380 sub FixAccountForLostAndReturned {
1381 my ($iteminfo, $borrower) = @_;
1383 my $dbh = C4::Context->dbh;
1384 my $itm = $iteminfo->{'itemnumber'};
1385 # check for charge made for lost book
1386 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1387 $sth->execute($itm);
1388 if (my $data = $sth->fetchrow_hashref) {
1389 # writeoff this amount
1391 my $amount = $data->{'amount'};
1392 my $acctno = $data->{'accountno'};
1394 if ($data->{'amountoutstanding'} == $amount) {
1395 $offset = $data->{'amount'};
1398 $offset = $amount - $data->{'amountoutstanding'};
1399 $amountleft = $data->{'amountoutstanding'} - $amount;
1401 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1402 WHERE (borrowernumber = ?)
1403 AND (itemnumber = ?) AND (accountno = ?) ");
1404 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1406 #check if any credit is left if so writeoff other accounts
1407 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1408 if ($amountleft < 0){
1411 if ($amountleft > 0){
1412 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1413 AND (amountoutstanding >0) ORDER BY date");
1414 $msth->execute($data->{'borrowernumber'});
1415 # offset transactions
1418 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1419 if ($accdata->{'amountoutstanding'} < $amountleft) {
1421 $amountleft -= $accdata->{'amountoutstanding'};
1423 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1426 my $thisacct = $accdata->{'accountno'};
1427 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1428 WHERE (borrowernumber = ?)
1429 AND (accountno=?)");
1430 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1432 $usth = $dbh->prepare("INSERT INTO accountoffsets
1433 (borrowernumber, accountno, offsetaccount, offsetamount)
1436 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1441 if ($amountleft > 0){
1444 my $desc="Item Returned ".$iteminfo->{'barcode'};
1445 $usth = $dbh->prepare("INSERT INTO accountlines
1446 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1447 VALUES (?,?,now(),?,?,'CR',?)");
1448 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1450 $usth = $dbh->prepare("INSERT INTO accountoffsets
1451 (borrowernumber, accountno, offsetaccount, offsetamount)
1453 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1455 ModItem({ paidfor => '' }, undef, $itm);
1463 $issues = &GetItemIssue($itemnumber);
1465 Returns patrons currently having a book. nothing if item is not issued atm
1467 C<$itemnumber> is the itemnumber
1469 Returns an array of hashes
1474 my ( $itemnumber) = @_;
1475 return unless $itemnumber;
1476 my $dbh = C4::Context->dbh;
1480 my $today = POSIX::strftime("%Y%m%d", localtime);
1482 my $sth = $dbh->prepare(
1483 "SELECT * FROM issues
1484 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1486 issues.itemnumber=?");
1487 $sth->execute($itemnumber);
1488 my $data = $sth->fetchrow_hashref;
1489 my $datedue = $data->{'date_due'};
1491 if ( $datedue < $today ) {
1492 $data->{'overdue'} = 1;
1494 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1499 =head2 GetItemIssues
1501 $issues = &GetItemIssues($itemnumber, $history);
1503 Returns patrons that have issued a book
1505 C<$itemnumber> is the itemnumber
1506 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1508 Returns an array of hashes
1513 my ( $itemnumber,$history ) = @_;
1514 my $dbh = C4::Context->dbh;
1518 my $today = POSIX::strftime("%Y%m%d", localtime);
1520 my $sql = "SELECT * FROM issues
1521 JOIN borrowers USING (borrowernumber)
1522 JOIN items USING (itemnumber)
1523 WHERE issues.itemnumber = ? ";
1526 SELECT * FROM old_issues
1527 LEFT JOIN borrowers USING (borrowernumber)
1528 JOIN items USING (itemnumber)
1529 WHERE old_issues.itemnumber = ? ";
1531 $sql .= "ORDER BY date_due DESC";
1532 my $sth = $dbh->prepare($sql);
1534 $sth->execute($itemnumber, $itemnumber);
1536 $sth->execute($itemnumber);
1538 while ( my $data = $sth->fetchrow_hashref ) {
1539 my $datedue = $data->{'date_due'};
1541 if ( $datedue < $today ) {
1542 $data->{'overdue'} = 1;
1544 my $itemnumber = $data->{'itemnumber'};
1545 push @GetItemIssues, $data;
1548 return ( \@GetItemIssues );
1551 =head2 GetBiblioIssues
1553 $issues = GetBiblioIssues($biblionumber);
1555 this function get all issues from a biblionumber.
1558 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1559 tables issues and the firstname,surname & cardnumber from borrowers.
1563 sub GetBiblioIssues {
1564 my $biblionumber = shift;
1565 return undef unless $biblionumber;
1566 my $dbh = C4::Context->dbh;
1568 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1570 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1571 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1572 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1573 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1574 WHERE biblio.biblionumber = ?
1576 SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1578 LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1579 LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1580 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1581 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1582 WHERE biblio.biblionumber = ?
1585 my $sth = $dbh->prepare($query);
1586 $sth->execute($biblionumber, $biblionumber);
1589 while ( my $data = $sth->fetchrow_hashref ) {
1590 push @issues, $data;
1595 =head2 CanBookBeRenewed
1597 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber);
1599 Find out whether a borrowed item may be renewed.
1601 C<$dbh> is a DBI handle to the Koha database.
1603 C<$borrowernumber> is the borrower number of the patron who currently
1604 has the item on loan.
1606 C<$itemnumber> is the number of the item to renew.
1608 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1609 item must currently be on loan to the specified borrower; renewals
1610 must be allowed for the item's type; and the borrower must not have
1611 already renewed the loan. $error will contain the reason the renewal can not proceed
1615 sub CanBookBeRenewed {
1617 # check renewal status
1618 my ( $borrowernumber, $itemnumber ) = @_;
1619 my $dbh = C4::Context->dbh;
1624 # Look in the issues table for this item, lent to this borrower,
1625 # and not yet returned.
1627 # FIXME - I think this function could be redone to use only one SQL call.
1628 my $sth1 = $dbh->prepare(
1629 "SELECT * FROM issues
1630 WHERE borrowernumber = ?
1633 $sth1->execute( $borrowernumber, $itemnumber );
1634 if ( my $data1 = $sth1->fetchrow_hashref ) {
1636 # Found a matching item
1638 # See if this item may be renewed. This query is convoluted
1639 # because it's a bit messy: given the item number, we need to find
1640 # the biblioitem, which gives us the itemtype, which tells us
1641 # whether it may be renewed.
1642 my $query = "SELECT renewalsallowed FROM items ";
1643 $query .= (C4::Context->preference('item-level_itypes'))
1644 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1645 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1646 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1647 $query .= "WHERE items.itemnumber = ?";
1648 my $sth2 = $dbh->prepare($query);
1649 $sth2->execute($itemnumber);
1650 if ( my $data2 = $sth2->fetchrow_hashref ) {
1651 $renews = $data2->{'renewalsallowed'};
1653 if ( $renews && $renews > $data1->{'renewals'} ) {
1660 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1668 return ($renewokay,$error);
1673 &AddRenewal($borrowernumber, $itemnumber, $datedue);
1677 C<$borrowernumber> is the borrower number of the patron who currently
1680 C<$itemnumber> is the number of the item to renew.
1682 C<$datedue> can be used to set the due date. If C<$datedue> is the
1683 empty string, C<&AddRenewal> will calculate the due date automatically
1684 from the book's item type. If you wish to set the due date manually,
1685 C<$datedue> should be in the form YYYY-MM-DD.
1691 my ( $borrowernumber, $itemnumber, $branch ,$datedue ) = @_;
1692 my $dbh = C4::Context->dbh;
1693 my $biblio = GetBiblioFromItemNumber($itemnumber);
1694 # If the due date wasn't specified, calculate it by adding the
1695 # book's loan length to today's date.
1696 unless ( $datedue ) {
1699 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
1700 my $loanlength = GetLoanLength(
1701 $borrower->{'categorycode'},
1702 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1703 $borrower->{'branchcode'}
1705 #FIXME -- choose issuer or borrower branch -- use circControl.
1707 #FIXME -- $debug-ify the (0)
1708 #my @darray = Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
1709 #$datedue = C4::Dates->new( sprintf("%04d-%02d-%02d",@darray[0..2]), 'iso');
1710 #(0) and print STDERR "C4::Dates->new->output = " . C4::Dates->new()->output()
1711 # . "\ndatedue->output = " . $datedue->output()
1712 # . "\n(Y,M,D) = " . join ',', @darray;
1713 #$datedue=CheckValidDatedue($datedue,$itemnumber,$branch,$loanlength);
1714 $datedue = CalcDateDue(C4::Dates->new(),$loanlength,$branch);
1717 # Find the issues record for this book
1719 $dbh->prepare("SELECT * FROM issues
1720 WHERE borrowernumber=?
1723 $sth->execute( $borrowernumber, $itemnumber );
1724 my $issuedata = $sth->fetchrow_hashref;
1727 # Update the issues record to have the new due date, and a new count
1728 # of how many times it has been renewed.
1729 my $renews = $issuedata->{'renewals'} + 1;
1730 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1731 WHERE borrowernumber=?
1734 $sth->execute( $datedue->output('iso'), $renews, $borrowernumber, $itemnumber );
1737 # Update the renewal count on the item, and tell zebra to reindex
1738 $renews = $biblio->{'renewals'} + 1;
1739 ModItem({ renewals => $renews }, $biblio->{'biblionumber'}, $itemnumber);
1741 # Charge a new rental fee, if applicable?
1742 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1743 if ( $charge > 0 ) {
1744 my $accountno = getnextacctno( $borrowernumber );
1745 my $item = GetBiblioFromItemNumber($itemnumber);
1746 $sth = $dbh->prepare(
1747 "INSERT INTO accountlines
1748 (borrowernumber,accountno,date,amount,
1749 description,accounttype,amountoutstanding,
1751 VALUES (?,?,now(),?,?,?,?,?)"
1753 $sth->execute( $borrowernumber, $accountno, $charge,
1754 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1755 'Rent', $charge, $itemnumber );
1759 UpdateStats( $branch, 'renew', $charge, '', $itemnumber );
1763 # check renewal status
1764 my ($bornum,$itemno)=@_;
1765 my $dbh = C4::Context->dbh;
1767 my $renewsallowed = 0;
1769 # Look in the issues table for this item, lent to this borrower,
1770 # and not yet returned.
1772 # FIXME - I think this function could be redone to use only one SQL call.
1773 my $sth = $dbh->prepare("select * from issues
1774 where (borrowernumber = ?)
1775 and (itemnumber = ?)");
1776 $sth->execute($bornum,$itemno);
1777 my $data = $sth->fetchrow_hashref;
1778 $renewcount = $data->{'renewals'} if $data->{'renewals'};
1780 my $query = "SELECT renewalsallowed FROM items ";
1781 $query .= (C4::Context->preference('item-level_itypes'))
1782 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1783 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1784 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1785 $query .= "WHERE items.itemnumber = ?";
1786 my $sth2 = $dbh->prepare($query);
1787 $sth2->execute($itemno);
1788 my $data2 = $sth2->fetchrow_hashref();
1789 $renewsallowed = $data2->{'renewalsallowed'};
1790 $renewsleft = $renewsallowed - $renewcount;
1791 return ($renewcount,$renewsallowed,$renewsleft);
1794 =head2 GetIssuingCharges
1796 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1798 Calculate how much it would cost for a given patron to borrow a given
1799 item, including any applicable discounts.
1801 C<$itemnumber> is the item number of item the patron wishes to borrow.
1803 C<$borrowernumber> is the patron's borrower number.
1805 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1806 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1811 sub GetIssuingCharges {
1813 # calculate charges due
1814 my ( $itemnumber, $borrowernumber ) = @_;
1816 my $dbh = C4::Context->dbh;
1819 # Get the book's item type and rental charge (via its biblioitem).
1820 my $qcharge = "SELECT itemtypes.itemtype,rentalcharge FROM items
1821 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1822 $qcharge .= (C4::Context->preference('item-level_itypes'))
1823 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1824 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1826 $qcharge .= "WHERE items.itemnumber =?";
1828 my $sth1 = $dbh->prepare($qcharge);
1829 $sth1->execute($itemnumber);
1830 if ( my $data1 = $sth1->fetchrow_hashref ) {
1831 $item_type = $data1->{'itemtype'};
1832 $charge = $data1->{'rentalcharge'};
1833 my $q2 = "SELECT rentaldiscount FROM borrowers
1834 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1835 WHERE borrowers.borrowernumber = ?
1836 AND issuingrules.itemtype = ?";
1837 my $sth2 = $dbh->prepare($q2);
1838 $sth2->execute( $borrowernumber, $item_type );
1839 if ( my $data2 = $sth2->fetchrow_hashref ) {
1840 my $discount = $data2->{'rentaldiscount'};
1841 if ( $discount eq 'NULL' ) {
1844 $charge = ( $charge * ( 100 - $discount ) ) / 100;
1850 return ( $charge, $item_type );
1853 =head2 AddIssuingCharge
1855 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1859 sub AddIssuingCharge {
1860 my ( $itemnumber, $borrowernumber, $charge ) = @_;
1861 my $dbh = C4::Context->dbh;
1862 my $nextaccntno = getnextacctno( $borrowernumber );
1864 INSERT INTO accountlines
1865 (borrowernumber, itemnumber, accountno,
1866 date, amount, description, accounttype,
1868 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1870 my $sth = $dbh->prepare($query);
1871 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1877 GetTransfers($itemnumber);
1882 my ($itemnumber) = @_;
1884 my $dbh = C4::Context->dbh;
1890 FROM branchtransfers
1891 WHERE itemnumber = ?
1892 AND datearrived IS NULL
1894 my $sth = $dbh->prepare($query);
1895 $sth->execute($itemnumber);
1896 my @row = $sth->fetchrow_array();
1902 =head2 GetTransfersFromTo
1904 @results = GetTransfersFromTo($frombranch,$tobranch);
1906 Returns the list of pending transfers between $from and $to branch
1910 sub GetTransfersFromTo {
1911 my ( $frombranch, $tobranch ) = @_;
1912 return unless ( $frombranch && $tobranch );
1913 my $dbh = C4::Context->dbh;
1915 SELECT itemnumber,datesent,frombranch
1916 FROM branchtransfers
1919 AND datearrived IS NULL
1921 my $sth = $dbh->prepare($query);
1922 $sth->execute( $frombranch, $tobranch );
1925 while ( my $data = $sth->fetchrow_hashref ) {
1926 push @gettransfers, $data;
1929 return (@gettransfers);
1932 =head2 DeleteTransfer
1934 &DeleteTransfer($itemnumber);
1938 sub DeleteTransfer {
1939 my ($itemnumber) = @_;
1940 my $dbh = C4::Context->dbh;
1941 my $sth = $dbh->prepare(
1942 "DELETE FROM branchtransfers
1944 AND datearrived IS NULL "
1946 $sth->execute($itemnumber);
1950 =head2 AnonymiseIssueHistory
1952 $rows = AnonymiseIssueHistory($borrowernumber,$date)
1954 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
1955 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
1957 return the number of affected rows.
1961 sub AnonymiseIssueHistory {
1963 my $borrowernumber = shift;
1964 my $dbh = C4::Context->dbh;
1967 SET borrowernumber = NULL
1968 WHERE returndate < '".$date."'
1969 AND borrowernumber IS NOT NULL
1971 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
1972 my $rows_affected = $dbh->do($query);
1973 return $rows_affected;
1976 =head2 updateWrongTransfer
1978 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
1980 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
1984 sub updateWrongTransfer {
1985 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
1986 my $dbh = C4::Context->dbh;
1987 # first step validate the actual line of transfert .
1990 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
1992 $sth->execute($FromLibrary,$itemNumber);
1995 # second step create a new line of branchtransfer to the right location .
1996 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
1998 #third step changing holdingbranch of item
1999 UpdateHoldingbranch($FromLibrary,$itemNumber);
2002 =head2 UpdateHoldingbranch
2004 $items = UpdateHoldingbranch($branch,$itmenumber);
2005 Simple methode for updating hodlingbranch in items BDD line
2009 sub UpdateHoldingbranch {
2010 my ( $branch,$itemnumber ) = @_;
2011 ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2016 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2017 this function calculates the due date given the loan length ,
2018 checking against the holidays calendar as per the 'useDaysMode' syspref.
2019 C<$startdate> = C4::Dates object representing start date of loan period (assumed to be today)
2020 C<$branch> = location whose calendar to use
2021 C<$loanlength> = loan length prior to adjustment
2025 my ($startdate,$loanlength,$branch) = @_;
2026 if(C4::Context->preference('useDaysMode') eq 'Days') { # ignoring calendar
2027 my $datedue = time + ($loanlength) * 86400;
2028 #FIXME - assumes now even though we take a startdate
2029 my @datearr = localtime($datedue);
2030 return C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2032 my $calendar = C4::Calendar->new( branchcode => $branch );
2033 my $datedue = $calendar->addDate($startdate, $loanlength);
2038 =head2 CheckValidDatedue
2039 This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2040 To be replaced by CalcDateDue() once C4::Calendar use is tested.
2042 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2043 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2044 C<$date_due> = returndate calculate with no day check
2045 C<$itemnumber> = itemnumber
2046 C<$branchcode> = location of issue (affected by 'CircControl' syspref)
2047 C<$loanlength> = loan length prior to adjustment
2050 sub CheckValidDatedue {
2051 my ($date_due,$itemnumber,$branchcode)=@_;
2052 my @datedue=split('-',$date_due->output('iso'));
2053 my $years=$datedue[0];
2054 my $month=$datedue[1];
2055 my $day=$datedue[2];
2056 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2058 for (my $i=0;$i<2;$i++){
2059 $dow=Day_of_Week($years,$month,$day);
2060 ($dow=0) if ($dow>6);
2061 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2062 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2063 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2064 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2066 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2069 my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2074 =head2 CheckRepeatableHolidays
2076 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2077 this function checks if the date due is a repeatable holiday
2078 C<$date_due> = returndate calculate with no day check
2079 C<$itemnumber> = itemnumber
2080 C<$branchcode> = localisation of issue
2084 sub CheckRepeatableHolidays{
2085 my($itemnumber,$week_day,$branchcode)=@_;
2086 my $dbh = C4::Context->dbh;
2087 my $query = qq|SELECT count(*)
2088 FROM repeatable_holidays
2091 my $sth = $dbh->prepare($query);
2092 $sth->execute($branchcode,$week_day);
2093 my $result=$sth->fetchrow;
2099 =head2 CheckSpecialHolidays
2101 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2102 this function check if the date is a special holiday
2103 C<$years> = the years of datedue
2104 C<$month> = the month of datedue
2105 C<$day> = the day of datedue
2106 C<$itemnumber> = itemnumber
2107 C<$branchcode> = localisation of issue
2111 sub CheckSpecialHolidays{
2112 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2113 my $dbh = C4::Context->dbh;
2114 my $query=qq|SELECT count(*)
2115 FROM `special_holidays`
2121 my $sth = $dbh->prepare($query);
2122 $sth->execute($years,$month,$day,$branchcode);
2123 my $countspecial=$sth->fetchrow ;
2125 return $countspecial;
2128 =head2 CheckRepeatableSpecialHolidays
2130 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2131 this function check if the date is a repeatble special holidays
2132 C<$month> = the month of datedue
2133 C<$day> = the day of datedue
2134 C<$itemnumber> = itemnumber
2135 C<$branchcode> = localisation of issue
2139 sub CheckRepeatableSpecialHolidays{
2140 my ($month,$day,$itemnumber,$branchcode) = @_;
2141 my $dbh = C4::Context->dbh;
2142 my $query=qq|SELECT count(*)
2143 FROM `repeatable_holidays`
2148 my $sth = $dbh->prepare($query);
2149 $sth->execute($month,$day,$branchcode);
2150 my $countspecial=$sth->fetchrow ;
2152 return $countspecial;
2157 sub CheckValidBarcode{
2159 my $dbh = C4::Context->dbh;
2160 my $query=qq|SELECT count(*)
2164 my $sth = $dbh->prepare($query);
2165 $sth->execute($barcode);
2166 my $exist=$sth->fetchrow ;
2177 Koha Developement team <info@koha.org>