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
45 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,%EXPORT_TAGS);
47 # set the version for version checking
52 C4::Circulation - Koha circulation module
60 The functions in this module deal with circulation, issues, and
61 returns, as well as general information about the library.
62 Also deals with stocktaking.
70 # FIXME subs that should probably be elsewhere
76 # subs to deal with issuing a book
88 &AnonymiseIssueHistory
90 # subs to deal with returns
95 # subs to deal with transfers
104 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
105 # 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 ?
109 =head3 $str = &decode($chunk);
113 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
120 sub cuecatbarcodedecode {
123 my @fields = split( /\./, $barcode );
124 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
125 if ( $#results == 2 ) {
135 =head3 $str = &decode($chunk);
139 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
149 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
150 my @s = map { index( $seq, $_ ); } split( //, $encoded );
151 my $l = ( $#s + 1 ) % 4;
162 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
164 chr( ( $n >> 16 ) ^ 67 )
165 .chr( ( $n >> 8 & 255 ) ^ 67 )
166 .chr( ( $n & 255 ) ^ 67 );
169 $r = substr( $r, 0, length($r) - $l );
175 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
177 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
179 C<$newbranch> is the code for the branch to which the item should be transferred.
181 C<$barcode> is the barcode of the item to be transferred.
183 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
184 Otherwise, if an item is reserved, the transfer fails.
186 Returns three values:
190 is true if the transfer was successful.
194 is a reference-to-hash which may have any of the following keys:
200 There is no item in the catalog with the given barcode. The value is C<$barcode>.
204 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.
206 =item C<DestinationEqualsHolding>
208 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.
212 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.
216 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>.
218 =item C<WasTransferred>
220 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
227 my ( $tbr, $barcode, $ignoreRs ) = @_;
230 my $branches = GetBranches();
231 my $itemnumber = GetItemnumberFromBarcode( $barcode );
232 my $issue = GetItemIssue($itemnumber);
233 my $biblio = GetBiblioFromItemNumber($itemnumber);
236 if ( not $itemnumber ) {
237 $messages->{'BadBarcode'} = $barcode;
241 # get branches of book...
242 my $hbr = $biblio->{'homebranch'};
243 my $fbr = $biblio->{'holdingbranch'};
246 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
247 $messages->{'IsPermanent'} = $hbr;
250 # can't transfer book if is already there....
251 if ( $fbr eq $tbr ) {
252 $messages->{'DestinationEqualsHolding'} = 1;
256 # check if it is still issued to someone, return it...
257 if ($issue->{borrowernumber}) {
258 AddReturn( $barcode, $fbr );
259 $messages->{'WasReturned'} = $issue->{borrowernumber};
263 # That'll save a database query.
264 my ( $resfound, $resrec ) =
265 CheckReserves( $itemnumber );
266 if ( $resfound and not $ignoreRs ) {
267 $resrec->{'ResFound'} = $resfound;
269 # $messages->{'ResFound'} = $resrec;
273 #actually do the transfer....
275 ModItemTransfer( $itemnumber, $fbr, $tbr );
277 # don't need to update MARC anymore, we do it in batch now
278 $messages->{'WasTransfered'} = 1;
279 ModDateLastSeen( $itemnumber );
281 return ( $dotransfer, $messages, $biblio );
284 =head2 CanBookBeIssued
286 Check if a book can be issued.
288 my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($borrower,$barcode,$year,$month,$day);
292 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
294 =item C<$barcode> is the bar code of the book being issued.
296 =item C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
304 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
305 Possible values are :
311 sticky due date is invalid
315 borrower gone with no address
319 borrower declared it's card lost
325 =head3 UNKNOWN_BARCODE
339 item is restricted (set by ??)
341 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
342 Possible values are :
350 renewing, not issuing
352 =head3 ISSUED_TO_ANOTHER
354 issued to someone else.
358 reserved for someone else.
362 sticky due date is invalid
366 if the borrower borrows to much things
370 # check if a book can be issued.
374 my $borrower = shift;
375 my $biblionumber = shift;
377 my $cat_borrower = $borrower->{'categorycode'};
378 my $branch_borrower = $borrower->{'branchcode'};
379 my $dbh = C4::Context->dbh;
381 my $branch_issuer = C4::Context->userenv->{'branchcode'};
382 # TODO : specify issuer or borrower for circrule.
383 my $type = (C4::Context->preference('item-level_itypes'))
384 ? $item->{'itype'} # item-level
385 : $item->{'itemtype'}; # biblio-level
389 'SELECT * FROM issuingrules
390 WHERE categorycode = ?
395 my $query2 = "SELECT COUNT(*) FROM issues i, biblioitems s1, items s2
396 WHERE i.borrowernumber = ?
397 AND i.returndate IS NULL
398 AND i.itemnumber = s2.itemnumber
399 AND s1.biblioitemnumber = s2.biblioitemnumber";
400 (C4::Context->preference('item-level_itypes')) ? $query2.=" AND s2.itype=? " : $query2.=" AND s1.itemtype= ? ";
401 my $sth2= $dbh->prepare($query2);
404 'SELECT COUNT(*) FROM issues
405 WHERE borrowernumber = ?
406 AND returndate IS NULL'
410 # check the 3 parameters (branch / itemtype / category code
411 $sth->execute( $cat_borrower, $type, $branch_borrower );
412 my $result = $sth->fetchrow_hashref;
413 # warn "$cat_borrower, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
415 if ( $result->{maxissueqty} ne '' ) {
416 # warn "checking on everything set";
417 $sth2->execute( $borrower->{'borrowernumber'}, $type );
418 my $alreadyissued = $sth2->fetchrow;
419 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
420 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/itemtype failed)" );
422 # now checking for total
423 $sth->execute( $cat_borrower, '', $branch_borrower );
424 my $result = $sth->fetchrow_hashref;
425 if ( $result->{maxissueqty} ne '*' ) {
426 $sth2->execute( $borrower->{'borrowernumber'}, $type );
427 my $alreadyissued = $sth2->fetchrow;
428 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
429 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/total failed)" );
434 # check the 2 parameters (branch / itemtype / default categorycode
435 $sth->execute( '*', $type, $branch_borrower );
436 my $result = $sth->fetchrow_hashref;
437 # warn "*, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
439 if ( $result->{maxissueqty} ne '' ) {
440 # warn "checking on 2 parameters (default categorycode)";
441 $sth2->execute( $borrower->{'borrowernumber'}, $type );
442 my $alreadyissued = $sth2->fetchrow;
443 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
444 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / itemtype failed)" );
446 # now checking for total
447 $sth->execute( '*', '*', $branch_borrower );
448 my $result = $sth->fetchrow_hashref;
449 if ( $result->{maxissueqty} ne '' ) {
450 $sth2->execute( $borrower->{'borrowernumber'}, $type );
451 my $alreadyissued = $sth2->fetchrow;
452 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
453 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / total failed)" );
458 # check the 1 parameters (default branch / itemtype / categorycode
459 $sth->execute( $cat_borrower, $type, '*' );
460 my $result = $sth->fetchrow_hashref;
461 # warn "$cat_borrower, $type, * = ".Data::Dumper::Dumper($result);
463 if ( $result->{maxissueqty} ne '' ) {
464 # warn "checking on 1 parameter (default branch + categorycode)";
465 $sth2->execute( $borrower->{'borrowernumber'}, $type );
466 my $alreadyissued = $sth2->fetchrow;
467 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
468 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch/category/itemtype failed)" );
470 # now checking for total
471 $sth->execute( $cat_borrower, '*', '*' );
472 my $result = $sth->fetchrow_hashref;
473 if ( $result->{maxissueqty} ne '' ) {
474 $sth2->execute( $borrower->{'borrowernumber'}, $type );
475 my $alreadyissued = $sth2->fetchrow;
476 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
477 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / category / total failed)" );
482 # check the 0 parameters (default branch / itemtype / default categorycode
483 $sth->execute( '*', $type, '*' );
484 my $result = $sth->fetchrow_hashref;
485 # warn "*, $type, * = ".Data::Dumper::Dumper($result);
487 if ( $result->{maxissueqty} ne '' ) {
488 # warn "checking on default branch and default categorycode";
489 $sth2->execute( $borrower->{'borrowernumber'}, $type );
490 my $alreadyissued = $sth2->fetchrow;
491 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
492 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / itemtype failed)" );
494 # now checking for total
495 $sth->execute( '*', '*', '*' );
496 my $result = $sth->fetchrow_hashref;
497 if ( $result->{maxissueqty} ne '' ) {
498 $sth2->execute( $borrower->{'borrowernumber'}, $type );
499 my $alreadyissued = $sth2->fetchrow;
500 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
501 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / total failed)" );
506 #OK, the patron can issue !!!
512 @issues = &itemissues($biblioitemnumber, $biblio);
514 Looks up information about who has borrowed the bookZ<>(s) with the
515 given biblioitemnumber.
517 C<$biblio> is ignored.
519 C<&itemissues> returns an array of references-to-hash. The keys
520 include the fields from the C<items> table in the Koha database.
521 Additional keys include:
527 If the item is currently on loan, this gives the due date.
529 If the item is not on loan, then this is either "Available" or
530 "Cancelled", if the item has been withdrawn.
534 If the item is currently on loan, this gives the card number of the
535 patron who currently has the item.
537 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
539 These give the timestamp for the last three times the item was
542 =item C<card0>, C<card1>, C<card2>
544 The card number of the last three patrons who borrowed this item.
546 =item C<borrower0>, C<borrower1>, C<borrower2>
548 The borrower number of the last three patrons who borrowed this item.
556 my ( $bibitem, $biblio ) = @_;
557 my $dbh = C4::Context->dbh;
559 # FIXME - If this function die()s, the script will abort, and the
560 # user won't get anything; depending on how far the script has
561 # gotten, the user might get a blank page. It would be much better
562 # to at least print an error message. The easiest way to do this
563 # is to set $SIG{__DIE__}.
565 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
570 $sth->execute($bibitem) || die $sth->errstr;
572 while ( my $data = $sth->fetchrow_hashref ) {
574 # Find out who currently has this item.
575 # FIXME - Wouldn't it be better to do this as a left join of
576 # some sort? Currently, this code assumes that if
577 # fetchrow_hashref() fails, then the book is on the shelf.
578 # fetchrow_hashref() can fail for any number of reasons (e.g.,
579 # database server crash), not just because no items match the
581 my $sth2 = $dbh->prepare(
582 "SELECT * FROM issues
583 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
585 AND returndate IS NULL
589 $sth2->execute( $data->{'itemnumber'} );
590 if ( my $data2 = $sth2->fetchrow_hashref ) {
591 $data->{'date_due'} = $data2->{'date_due'};
592 $data->{'card'} = $data2->{'cardnumber'};
593 $data->{'borrower'} = $data2->{'borrowernumber'};
596 if ( $data->{'wthdrawn'} eq '1' ) {
597 $data->{'date_due'} = 'Cancelled';
600 $data->{'date_due'} = 'Available';
606 # Find the last 3 people who borrowed this item.
607 $sth2 = $dbh->prepare(
608 "SELECT * FROM issues
609 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
611 AND returndate IS NOT NULL
612 ORDER BY returndate DESC,timestamp DESC"
615 $sth2->execute( $data->{'itemnumber'} );
616 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
617 { # FIXME : error if there is less than 3 pple borrowing this item
618 if ( my $data2 = $sth2->fetchrow_hashref ) {
619 $data->{"timestamp$i2"} = $data2->{'timestamp'};
620 $data->{"card$i2"} = $data2->{'cardnumber'};
621 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
626 $results[$i] = $data;
634 =head2 CanBookBeIssued
636 $issuingimpossible, $needsconfirmation =
637 CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
638 C<$duedatespec> is a C4::Dates object.
639 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
643 sub CanBookBeIssued {
644 my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
645 my %needsconfirmation; # filled with problems that needs confirmations
646 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
647 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
648 my $issue = GetItemIssue($item->{itemnumber});
649 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
650 $item->{'itemtype'}=$biblioitem->{'itemtype'};
651 my $dbh = C4::Context->dbh;
654 # DUE DATE is OK ? -- should already have checked.
656 #$issuingimpossible{INVALID_DATE} = 1 unless ($duedate);
661 if ( $borrower->{flags}->{GNA} ) {
662 $issuingimpossible{GNA} = 1;
664 if ( $borrower->{flags}->{'LOST'} ) {
665 $issuingimpossible{CARD_LOST} = 1;
667 if ( $borrower->{flags}->{'DBARRED'} ) {
668 $issuingimpossible{DEBARRED} = 1;
670 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
671 $issuingimpossible{EXPIRED} = 1;
673 my @expirydate= split /-/,$borrower->{'dateexpiry'};
674 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
675 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
676 $issuingimpossible{EXPIRED} = 1;
685 C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
686 if ( C4::Context->preference("IssuingInProcess") ) {
687 my $amountlimit = C4::Context->preference("noissuescharge");
688 if ( $amount > $amountlimit && !$inprocess ) {
689 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
691 elsif ( $amount <= $amountlimit && !$inprocess ) {
692 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
697 $needsconfirmation{DEBT} = $amount;
702 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
704 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
705 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
710 unless ( $item->{barcode} ) {
711 $issuingimpossible{UNKNOWN_BARCODE} = 1;
713 if ( $item->{'notforloan'}
714 && $item->{'notforloan'} > 0 )
716 $issuingimpossible{NOT_FOR_LOAN} = 1;
718 elsif ( !$item->{'notforloan'} ){
719 # we have to check itemtypes.notforloan also
720 if (C4::Context->preference('item-level_itypes')){
721 # this should probably be a subroutine
722 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
723 $sth->execute($item->{'itemtype'});
724 my $notforloan=$sth->fetchrow_hashref();
726 if ($notforloan->{'notforloan'} == 1){
727 $issuingimpossible{NOT_FOR_LOAN} = 1;
730 elsif ($biblioitem->{'notforloan'} == 1){
731 $issuingimpossible{NOT_FOR_LOAN} = 1;
734 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
736 $issuingimpossible{WTHDRAWN} = 1;
738 if ( $item->{'restricted'}
739 && $item->{'restricted'} == 1 )
741 $issuingimpossible{RESTRICTED} = 1;
743 if ( C4::Context->preference("IndependantBranches") ) {
744 my $userenv = C4::Context->userenv;
745 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
746 $issuingimpossible{NOTSAMEBRANCH} = 1
747 if ( $item->{C4::Context->preference("HomeOrHoldingbranch")} ne $userenv->{branch} );
752 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
754 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
757 # Already issued to current borrower. Ask whether the loan should
759 my ($CanBookBeRenewed) = CanBookBeRenewed(
760 $borrower->{'borrowernumber'},
761 $item->{'itemnumber'}
763 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
764 $issuingimpossible{NO_MORE_RENEWALS} = 1;
767 $needsconfirmation{RENEW_ISSUE} = 1;
770 elsif ($issue->{borrowernumber}) {
772 # issued to someone else
773 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
775 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
776 $needsconfirmation{ISSUED_TO_ANOTHER} =
777 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
780 # See if the item is on reserve.
781 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
783 my $resbor = $res->{'borrowernumber'};
784 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
787 # The item is on reserve and waiting, but has been
788 # reserved by some other patron.
789 my ( $resborrower, $flags ) =
790 GetMemberDetails( $resbor, 0 );
791 my $branches = GetBranches();
793 $branches->{ $res->{'branchcode'} }->{'branchname'};
794 $needsconfirmation{RESERVE_WAITING} =
795 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
797 # CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'}); Doesn't belong in a checking subroutine.
799 elsif ( $restype eq "Reserved" ) {
801 # The item is on reserve for someone else.
802 my ( $resborrower, $flags ) =
803 GetMemberDetails( $resbor, 0 );
804 my $branches = GetBranches();
806 $branches->{ $res->{'branchcode'} }->{'branchname'};
807 $needsconfirmation{RESERVED} =
808 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
811 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
812 if ( $borrower->{'categorycode'} eq 'W' ) {
813 my %issuingimpossible;
814 return ( \%issuingimpossible, \%needsconfirmation );
816 return ( \%issuingimpossible, \%needsconfirmation );
819 return ( \%issuingimpossible, \%needsconfirmation );
825 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
827 &AddIssue($borrower,$barcode,$date)
831 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
833 =item C<$barcode> is the bar code of the book being issued.
835 =item C<$date> contains the max date of return. calculated if empty.
837 AddIssue does the following things :
838 - step 01: check that there is a borrowernumber & a barcode provided
839 - check for RENEWAL (book issued & being issued to the same patron)
840 - renewal YES = Calculate Charge & renew
842 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
844 - fill reserve if reserve to this patron
845 - cancel reserve or not, otherwise
846 * TRANSFERT PENDING ?
847 - complete the transfert
855 my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
856 my $dbh = C4::Context->dbh;
857 my $barcodecheck=CheckValidBarcode($barcode);
858 if ($borrower and $barcode and $barcodecheck ne '0'){
859 # my ($borrower, $flags) = &GetMemberDetails($borrowernumber, 0);
860 # find which item we issue
861 my $item = GetItem('', $barcode);
864 # get actual issuing if there is one
865 my $actualissue = GetItemIssue( $item->{itemnumber});
867 # get biblioinformation for this item
868 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
871 # check if we just renew the issue.
873 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
875 $borrower->{'borrowernumber'},
876 $item->{'itemnumber'},
877 C4::Context->userenv->{'branch'},
884 if ( $actualissue->{borrowernumber}) {
885 # This book is currently on loan, but not to the person
886 # who wants to borrow it now. mark it returned before issuing to the new borrower
889 C4::Context->userenv->{'branch'}
893 # See if the item is on reserve.
894 my ( $restype, $res ) =
895 C4::Reserves::CheckReserves( $item->{'itemnumber'} );
897 my $resbor = $res->{'borrowernumber'};
898 if ( $resbor eq $borrower->{'borrowernumber'} ) {
900 # The item is reserved by the current patron
901 ModReserveFill($res);
903 elsif ( $restype eq "Waiting" ) {
906 # The item is on reserve and waiting, but has been
907 # reserved by some other patron.
908 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
909 my $branches = GetBranches();
911 $branches->{ $res->{'branchcode'} }->{'branchname'};
913 elsif ( $restype eq "Reserved" ) {
916 # The item is reserved by someone else.
917 my ( $resborrower, $flags ) =
918 GetMemberDetails( $resbor, 0 );
919 my $branches = GetBranches();
921 $branches->{ $res->{'branchcode'} }->{'branchname'};
922 if ($cancelreserve) { # cancel reserves on this item
923 CancelReserve( 0, $res->{'itemnumber'},
924 $res->{'borrowernumber'} );
927 if ($cancelreserve) {
928 CancelReserve( $res->{'biblionumber'}, 0,
929 $res->{'borrowernumber'} );
932 # set waiting reserve to first in reserve queue as book isn't waiting now
935 $res->{'biblionumber'},
936 $res->{'borrowernumber'},
942 # Starting process for transfer job (checking transfert and validate it if we have one)
943 my ($datesent) = GetTransfers($item->{'itemnumber'});
945 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
948 "UPDATE branchtransfers
949 SET datearrived = now(),
951 comments = 'Forced branchtransfert'
952 WHERE itemnumber= ? AND datearrived IS NULL"
954 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
958 # Record in the database the fact that the book was issued.
962 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
969 my $itype=(C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ;
970 my $loanlength = GetLoanLength(
971 $borrower->{'categorycode'},
973 $borrower->{'branchcode'}
975 $datedue = time + ($loanlength) * 86400;
976 my @datearr = localtime($datedue);
977 $dateduef = C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
978 $dateduef=CheckValidDatedue($dateduef,$item->{'itemnumber'},C4::Context->userenv->{'branch'});
980 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
981 if ( C4::Context->preference('ReturnBeforeExpiry') && $dateduef->output('iso') gt $borrower->{dateexpiry} ) {
982 $dateduef = C4::Dates->new($borrower->{dateexpiry},'iso');
986 $borrower->{'borrowernumber'},
987 $item->{'itemnumber'},
988 strftime( "%Y-%m-%d", localtime ),$dateduef->output('iso'), C4::Context->userenv->{'branch'}
994 "UPDATE items SET issues=?, holdingbranch=?, itemlost=0, datelastborrowed = now(), onloan = ? WHERE itemnumber=?");
997 C4::Context->userenv->{'branch'},
998 $dateduef->output('iso'),
999 $item->{'itemnumber'}
1002 &ModDateLastSeen( $item->{'itemnumber'} );
1003 my $record = GetMarcItem( $item->{'biblionumber'}, $item->{'itemnumber'} );
1004 my $frameworkcode = GetFrameworkCode( $item->{'biblionumber'} );
1005 ModItemInMarc( $record, $item->{'biblionumber'}, $item->{'itemnumber'}, $frameworkcode );
1006 # If it costs to borrow this book, charge it to the patron's account.
1007 my ( $charge, $itemtype ) = GetIssuingCharges(
1008 $item->{'itemnumber'},
1009 $borrower->{'borrowernumber'}
1011 if ( $charge > 0 ) {
1013 $item->{'itemnumber'},
1014 $borrower->{'borrowernumber'}, $charge
1016 $item->{'charge'} = $charge;
1019 # Record the fact that this book was issued.
1021 C4::Context->userenv->{'branch'},
1023 '', $item->{'itemnumber'},
1024 $item->{'itemtype'}, $borrower->{'borrowernumber'}
1028 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'})
1029 if C4::Context->preference("IssueLog");
1034 =head2 GetLoanLength
1036 Get loan length for an itemtype, a borrower type and a branch
1038 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1043 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1044 my $dbh = C4::Context->dbh;
1047 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1049 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1050 # try to find issuelength & return the 1st available.
1051 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1052 $sth->execute( $borrowertype, $itemtype, $branchcode );
1053 my $loanlength = $sth->fetchrow_hashref;
1054 return $loanlength->{issuelength}
1055 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1057 $sth->execute( $borrowertype, $itemtype, "*" );
1058 $loanlength = $sth->fetchrow_hashref;
1059 return $loanlength->{issuelength}
1060 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1062 $sth->execute( $borrowertype, "*", $branchcode );
1063 $loanlength = $sth->fetchrow_hashref;
1064 return $loanlength->{issuelength}
1065 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1067 $sth->execute( "*", $itemtype, $branchcode );
1068 $loanlength = $sth->fetchrow_hashref;
1069 return $loanlength->{issuelength}
1070 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1072 $sth->execute( $borrowertype, "*", "*" );
1073 $loanlength = $sth->fetchrow_hashref;
1074 return $loanlength->{issuelength}
1075 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1077 $sth->execute( "*", "*", $branchcode );
1078 $loanlength = $sth->fetchrow_hashref;
1079 return $loanlength->{issuelength}
1080 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1082 $sth->execute( "*", $itemtype, "*" );
1083 $loanlength = $sth->fetchrow_hashref;
1084 return $loanlength->{issuelength}
1085 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1087 $sth->execute( "*", "*", "*" );
1088 $loanlength = $sth->fetchrow_hashref;
1089 return $loanlength->{issuelength}
1090 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1092 # if no rule is set => 21 days (hardcoded)
1098 ($doreturn, $messages, $iteminformation, $borrower) =
1099 &AddReturn($barcode, $branch, $exemptfine);
1103 C<$barcode> is the bar code of the book being returned. C<$branch> is
1104 the code of the branch where the book is being returned. C<$exemptfine>
1105 indicates that overdue charges for the item will not be applied.
1107 C<&AddReturn> returns a list of four items:
1109 C<$doreturn> is true iff the return succeeded.
1111 C<$messages> is a reference-to-hash giving the reason for failure:
1117 No item with this barcode exists. The value is C<$barcode>.
1121 The book is not currently on loan. The value is C<$barcode>.
1123 =item C<IsPermanent>
1125 The book's home branch is a permanent collection. If you have borrowed
1126 this book, you are not allowed to return it. The value is the code for
1127 the book's home branch.
1131 This book has been withdrawn/cancelled. The value should be ignored.
1135 The item was reserved. The value is a reference-to-hash whose keys are
1136 fields from the reserves table of the Koha database, and
1137 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1138 either C<Waiting>, C<Reserved>, or 0.
1142 C<$borrower> is a reference-to-hash, giving information about the
1143 patron who last borrowed the book.
1148 my ( $barcode, $branch, $exemptfine ) = @_;
1149 my $dbh = C4::Context->dbh;
1153 my $validTransfert = 0;
1154 my $reserveDone = 0;
1156 # get information on item
1157 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1158 my $biblio = GetBiblioFromItemNumber($iteminformation->{'itemnumber'});
1159 unless ($iteminformation->{'itemnumber'} ) {
1160 $messages->{'BadBarcode'} = $barcode;
1164 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1165 $messages->{'NotIssued'} = $barcode;
1169 # check if the book is in a permanent collection....
1170 my $hbr = $iteminformation->{'homebranch'};
1171 my $branches = GetBranches();
1172 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1173 $messages->{'IsPermanent'} = $hbr;
1176 # if independent branches are on and returning to different branch, refuse the return
1177 if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1178 $messages->{'Wrongbranch'} = 1;
1182 # check that the book has been cancelled
1183 if ( $iteminformation->{'wthdrawn'} ) {
1184 $messages->{'wthdrawn'} = 1;
1188 # new op dev : if the book returned in an other branch update the holding branch
1190 # update issues, thereby returning book (should push this out into another subroutine
1191 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1193 # case of a return of document (deal with issues and holdingbranch)
1198 "UPDATE issues SET returndate = now() WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (returndate IS NULL)"
1200 $sth->execute( $borrower->{'borrowernumber'},
1201 $iteminformation->{'itemnumber'} );
1202 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1205 # continue to deal with returns cases, but not only if we have an issue
1207 # the holdingbranch is updated if the document is returned in an other location .
1208 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1209 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1210 # reload iteminformation holdingbranch with the userenv value
1211 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1213 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1214 my $sth = $dbh->prepare("UPDATE items SET onloan = NULL where itemnumber = ?");
1215 $sth->execute($iteminformation->{'itemnumber'});
1217 my $record = GetMarcItem( $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'} );
1218 my $frameworkcode = GetFrameworkCode( $biblio->{'biblionumber'} );
1219 ModItemInMarc( $record, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'}, $frameworkcode );
1221 if ($iteminformation->{borrowernumber}){
1222 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1224 # fix up the accounts.....
1225 if ( $iteminformation->{'itemlost'} ) {
1226 $messages->{'WasLost'} = 1;
1229 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1230 # check if we have a transfer for this document
1231 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1233 # if we have a transfer to do, we update the line of transfers with the datearrived
1235 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1238 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1240 $sth->execute( $iteminformation->{'itemnumber'} );
1242 # 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'
1243 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1246 $messages->{'WrongTransfer'} = $tobranch;
1247 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1249 $validTransfert = 1;
1252 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1253 # fix up the accounts.....
1254 if ($iteminformation->{'itemlost'}) {
1255 FixAccountForLostAndReturned($iteminformation, $borrower);
1256 $messages->{'WasLost'} = 1;
1258 # fix up the overdues in accounts...
1259 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1260 $iteminformation->{'itemnumber'}, $exemptfine );
1262 # find reserves.....
1263 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1264 my ( $resfound, $resrec ) =
1265 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1267 $resrec->{'ResFound'} = $resfound;
1268 $messages->{'ResFound'} = $resrec;
1273 # Record the fact that this book was returned.
1275 $branch, 'return', '0', '',
1276 $iteminformation->{'itemnumber'},
1277 $iteminformation->{'itemtype'},
1278 $borrower->{'borrowernumber'}
1281 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'})
1282 if C4::Context->preference("ReturnLog");
1284 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1285 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1287 if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1288 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1289 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1290 $messages->{'WasTransfered'} = 1;
1293 $messages->{'NeedsTransfer'} = 1;
1297 return ( $doreturn, $messages, $iteminformation, $borrower );
1300 =head2 FixOverduesOnReturn
1302 &FixOverduesOnReturn($brn,$itm, $exemptfine);
1304 C<$brn> borrowernumber
1308 internal function, called only by AddReturn
1312 sub FixOverduesOnReturn {
1313 my ( $borrowernumber, $item, $exemptfine ) = @_;
1314 my $dbh = C4::Context->dbh;
1316 # check for overdue fine
1319 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1321 $sth->execute( $borrowernumber, $item );
1323 # alter fine to show that the book has been returned
1325 if ($data = $sth->fetchrow_hashref) {
1326 my $uquery =($exemptfine)? "update accountlines set accounttype='FFOR', amountoutstanding=0":"update accountlines set accounttype='F' ";
1327 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1328 my $usth = $dbh->prepare($uquery);
1329 $usth->execute($borrowernumber,$item ,$data->{'accountno'});
1337 =head2 FixAccountForLostAndReturned
1339 &FixAccountForLostAndReturned($iteminfo,$borrower);
1341 Calculates the charge for a book lost and returned (Not exported & used only once)
1343 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1345 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1347 Internal function, called by AddReturn
1351 sub FixAccountForLostAndReturned {
1352 my ($iteminfo, $borrower) = @_;
1354 my $dbh = C4::Context->dbh;
1355 my $itm = $iteminfo->{'itemnumber'};
1356 # check for charge made for lost book
1357 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1358 $sth->execute($itm);
1359 if (my $data = $sth->fetchrow_hashref) {
1360 # writeoff this amount
1362 my $amount = $data->{'amount'};
1363 my $acctno = $data->{'accountno'};
1365 if ($data->{'amountoutstanding'} == $amount) {
1366 $offset = $data->{'amount'};
1369 $offset = $amount - $data->{'amountoutstanding'};
1370 $amountleft = $data->{'amountoutstanding'} - $amount;
1372 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1373 WHERE (borrowernumber = ?)
1374 AND (itemnumber = ?) AND (accountno = ?) ");
1375 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1377 #check if any credit is left if so writeoff other accounts
1378 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1379 if ($amountleft < 0){
1382 if ($amountleft > 0){
1383 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1384 AND (amountoutstanding >0) ORDER BY date");
1385 $msth->execute($data->{'borrowernumber'});
1386 # offset transactions
1389 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1390 if ($accdata->{'amountoutstanding'} < $amountleft) {
1392 $amountleft -= $accdata->{'amountoutstanding'};
1394 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1397 my $thisacct = $accdata->{'accountno'};
1398 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1399 WHERE (borrowernumber = ?)
1400 AND (accountno=?)");
1401 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1403 $usth = $dbh->prepare("INSERT INTO accountoffsets
1404 (borrowernumber, accountno, offsetaccount, offsetamount)
1407 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1412 if ($amountleft > 0){
1415 my $desc="Item Returned ".$iteminfo->{'barcode'};
1416 $usth = $dbh->prepare("INSERT INTO accountlines
1417 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1418 VALUES (?,?,now(),?,?,'CR',?)");
1419 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1421 $usth = $dbh->prepare("INSERT INTO accountoffsets
1422 (borrowernumber, accountno, offsetaccount, offsetamount)
1424 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1426 $usth = $dbh->prepare("UPDATE items SET paidfor='' WHERE itemnumber=?");
1427 $usth->execute($itm);
1436 $issues = &GetItemIssue($itemnumber);
1438 Returns patrons currently having a book. nothing if item is not issued atm
1440 C<$itemnumber> is the itemnumber
1442 Returns an array of hashes
1446 my ( $itemnumber) = @_;
1447 return unless $itemnumber;
1448 my $dbh = C4::Context->dbh;
1452 my $today = POSIX::strftime("%Y%m%d", localtime);
1454 my $sth = $dbh->prepare(
1455 "SELECT * FROM issues
1456 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1458 issues.itemnumber=? AND returndate IS NULL ");
1459 $sth->execute($itemnumber);
1460 my $data = $sth->fetchrow_hashref;
1461 my $datedue = $data->{'date_due'};
1463 if ( $datedue < $today ) {
1464 $data->{'overdue'} = 1;
1466 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1471 =head2 GetItemIssues
1473 $issues = &GetItemIssues($itemnumber, $history);
1475 Returns patrons that have issued a book
1477 C<$itemnumber> is the itemnumber
1478 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1480 Returns an array of hashes
1484 my ( $itemnumber,$history ) = @_;
1485 my $dbh = C4::Context->dbh;
1489 my $today = POSIX::strftime("%Y%m%d", localtime);
1491 my $sth = $dbh->prepare(
1492 "SELECT * FROM issues
1493 LEFT JOIN borrowers ON borrowers.borrowernumber
1494 LEFT JOIN items ON items.itemnumber=issues.itemnumber
1496 issues.itemnumber=?".($history?"":" AND returndate IS NULL ").
1497 "ORDER BY issues.date_due DESC"
1499 $sth->execute($itemnumber);
1500 while ( my $data = $sth->fetchrow_hashref ) {
1501 my $datedue = $data->{'date_due'};
1503 if ( $datedue < $today ) {
1504 $data->{'overdue'} = 1;
1506 my $itemnumber = $data->{'itemnumber'};
1507 push @GetItemIssues, $data;
1510 return ( \@GetItemIssues );
1513 =head2 GetBiblioIssues
1515 $issues = GetBiblioIssues($biblionumber);
1517 this function get all issues from a biblionumber.
1520 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1521 tables issues and the firstname,surname & cardnumber from borrowers.
1525 sub GetBiblioIssues {
1526 my $biblionumber = shift;
1527 return undef unless $biblionumber;
1528 my $dbh = C4::Context->dbh;
1530 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1532 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1533 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1534 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1535 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1536 WHERE biblio.biblionumber = ?
1537 ORDER BY issues.timestamp
1539 my $sth = $dbh->prepare($query);
1540 $sth->execute($biblionumber);
1543 while ( my $data = $sth->fetchrow_hashref ) {
1544 push @issues, $data;
1549 =head2 CanBookBeRenewed
1551 $ok = &CanBookBeRenewed($borrowernumber, $itemnumber);
1553 Find out whether a borrowed item may be renewed.
1555 C<$dbh> is a DBI handle to the Koha database.
1557 C<$borrowernumber> is the borrower number of the patron who currently
1558 has the item on loan.
1560 C<$itemnumber> is the number of the item to renew.
1562 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1563 item must currently be on loan to the specified borrower; renewals
1564 must be allowed for the item's type; and the borrower must not have
1565 already renewed the loan.
1569 sub CanBookBeRenewed {
1571 # check renewal status
1572 my ( $borrowernumber, $itemnumber ) = @_;
1573 my $dbh = C4::Context->dbh;
1577 # Look in the issues table for this item, lent to this borrower,
1578 # and not yet returned.
1580 # FIXME - I think this function could be redone to use only one SQL call.
1581 my $sth1 = $dbh->prepare(
1582 "SELECT * FROM issues
1583 WHERE borrowernumber = ?
1585 AND returndate IS NULL"
1587 $sth1->execute( $borrowernumber, $itemnumber );
1588 if ( my $data1 = $sth1->fetchrow_hashref ) {
1590 # Found a matching item
1592 # See if this item may be renewed. This query is convoluted
1593 # because it's a bit messy: given the item number, we need to find
1594 # the biblioitem, which gives us the itemtype, which tells us
1595 # whether it may be renewed.
1596 my $sth2 = $dbh->prepare(
1597 "SELECT renewalsallowed FROM items
1598 LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1599 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1600 WHERE items.itemnumber = ?
1603 $sth2->execute($itemnumber);
1604 if ( my $data2 = $sth2->fetchrow_hashref ) {
1605 $renews = $data2->{'renewalsallowed'};
1607 if ( $renews && $renews >= $data1->{'renewals'} ) {
1611 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1618 return ($renewokay);
1623 &AddRenewal($borrowernumber, $itemnumber, $datedue);
1627 C<$borrowernumber> is the borrower number of the patron who currently
1630 C<$itemnumber> is the number of the item to renew.
1632 C<$datedue> can be used to set the due date. If C<$datedue> is the
1633 empty string, C<&AddRenewal> will calculate the due date automatically
1634 from the book's item type. If you wish to set the due date manually,
1635 C<$datedue> should be in the form YYYY-MM-DD.
1641 my ( $borrowernumber, $itemnumber, $branch ,$datedue ) = @_;
1642 my $dbh = C4::Context->dbh;
1644 my $biblio = GetBiblioFromItemNumber($itemnumber);
1645 # If the due date wasn't specified, calculate it by adding the
1646 # book's loan length to today's date.
1647 unless ( $datedue ) {
1650 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
1651 my $loanlength = GetLoanLength(
1652 $borrower->{'categorycode'},
1653 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1654 $borrower->{'branchcode'}
1656 #FIXME -- choose issuer or borrower branch.
1657 #FIXME -- where's the calendar ?
1658 #FIXME -- $debug-ify the (0)
1659 my @darray = Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
1660 $datedue = C4::Dates->new( sprintf("%04d-%02d-%02d",@darray[0..2]), 'iso');
1661 (0) and print STDERR "C4::Dates->new->output = " . C4::Dates->new()->output()
1662 . "\ndatedue->output = " . $datedue->output()
1663 . "\n(Y,M,D) = " . join ',', @darray;
1664 $datedue=CheckValidDatedue($datedue,$itemnumber,$branch);
1667 # Find the issues record for this book
1669 $dbh->prepare("SELECT * FROM issues
1670 WHERE borrowernumber=?
1672 AND returndate IS NULL"
1674 $sth->execute( $borrowernumber, $itemnumber );
1675 my $issuedata = $sth->fetchrow_hashref;
1678 # Update the issues record to have the new due date, and a new count
1679 # of how many times it has been renewed.
1680 my $renews = $issuedata->{'renewals'} + 1;
1681 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1682 WHERE borrowernumber=?
1684 AND returndate IS NULL"
1686 $sth->execute( $datedue->output('iso'), $renews, $borrowernumber, $itemnumber );
1689 # Update the renewal count on the item, and tell zebra to reindex
1690 $renews = $biblio->{'renewals'} + 1;
1691 $sth = $dbh->prepare("UPDATE items SET renewals = ? WHERE itemnumber = ?");
1692 $sth->execute($renews,$itemnumber);
1694 my $record = GetMarcItem( $biblio->{'biblionumber'}, $itemnumber );
1695 my $frameworkcode = GetFrameworkCode( $biblio->{'biblionumber'} );
1696 ModItemInMarc( $record, $biblio->{'biblionumber'}, $itemnumber, $frameworkcode );
1698 # Charge a new rental fee, if applicable?
1699 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1700 if ( $charge > 0 ) {
1701 my $accountno = getnextacctno( $borrowernumber );
1702 my $item = GetBiblioFromItemNumber($itemnumber);
1703 $sth = $dbh->prepare(
1704 "INSERT INTO accountlines
1705 (borrowernumber,accountno,date,amount,
1706 description,accounttype,amountoutstanding,
1708 VALUES (?,?,now(),?,?,?,?,?)"
1710 $sth->execute( $borrowernumber, $accountno, $charge,
1711 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1712 'Rent', $charge, $itemnumber );
1716 UpdateStats( $branch, 'renew', $charge, '', $itemnumber );
1720 # check renewal status
1721 my ($bornum,$itemno)=@_;
1722 my $dbh = C4::Context->dbh;
1724 my $renewsallowed = 0;
1726 # Look in the issues table for this item, lent to this borrower,
1727 # and not yet returned.
1729 # FIXME - I think this function could be redone to use only one SQL call.
1730 my $sth = $dbh->prepare("select * from issues
1731 where (borrowernumber = ?)
1732 and (itemnumber = ?)
1733 and returndate is null");
1734 $sth->execute($bornum,$itemno);
1735 my $data = $sth->fetchrow_hashref;
1736 $renewcount = $data->{'renewals'} if $data->{'renewals'};
1737 my $sth2 = $dbh->prepare("select renewalsallowed from items,biblioitems,itemtypes
1738 where (items.itemnumber = ?)
1739 and (items.biblioitemnumber = biblioitems.biblioitemnumber)
1740 and (biblioitems.itemtype = itemtypes.itemtype)");
1741 $sth2->execute($itemno);
1742 my $data2 = $sth2->fetchrow_hashref();
1743 $renewsallowed = $data2->{'renewalsallowed'};
1744 $renewsleft = $renewsallowed - $renewcount;
1745 warn "Renewcount:$renewcount RenewsAll:$renewsallowed RenewLeft:$renewsleft";
1746 return ($renewcount,$renewsallowed,$renewsleft);
1748 =head2 GetIssuingCharges
1750 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1752 Calculate how much it would cost for a given patron to borrow a given
1753 item, including any applicable discounts.
1755 C<$itemnumber> is the item number of item the patron wishes to borrow.
1757 C<$borrowernumber> is the patron's borrower number.
1759 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1760 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1765 sub GetIssuingCharges {
1767 # calculate charges due
1768 my ( $itemnumber, $borrowernumber ) = @_;
1770 my $dbh = C4::Context->dbh;
1773 # Get the book's item type and rental charge (via its biblioitem).
1774 my $qcharge = "SELECT itemtypes.itemtype,rentalcharge FROM items
1775 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1776 $qcharge .= (C4::Context->preference('item-level_itypes'))
1777 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1778 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1780 $qcharge .= "WHERE items.itemnumber =?";
1782 my $sth1 = $dbh->prepare($qcharge);
1783 $sth1->execute($itemnumber);
1784 if ( my $data1 = $sth1->fetchrow_hashref ) {
1785 $item_type = $data1->{'itemtype'};
1786 $charge = $data1->{'rentalcharge'};
1787 my $q2 = "SELECT rentaldiscount FROM borrowers
1788 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1789 WHERE borrowers.borrowernumber = ?
1790 AND issuingrules.itemtype = ?";
1791 my $sth2 = $dbh->prepare($q2);
1792 $sth2->execute( $borrowernumber, $item_type );
1793 if ( my $data2 = $sth2->fetchrow_hashref ) {
1794 my $discount = $data2->{'rentaldiscount'};
1795 if ( $discount eq 'NULL' ) {
1798 $charge = ( $charge * ( 100 - $discount ) ) / 100;
1804 return ( $charge, $item_type );
1807 =head2 AddIssuingCharge
1809 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1813 sub AddIssuingCharge {
1814 my ( $itemnumber, $borrowernumber, $charge ) = @_;
1815 my $dbh = C4::Context->dbh;
1816 my $nextaccntno = getnextacctno( $borrowernumber );
1818 INSERT INTO accountlines
1819 (borrowernumber, itemnumber, accountno,
1820 date, amount, description, accounttype,
1822 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1824 my $sth = $dbh->prepare($query);
1825 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1831 GetTransfers($itemnumber);
1836 my ($itemnumber) = @_;
1838 my $dbh = C4::Context->dbh;
1844 FROM branchtransfers
1845 WHERE itemnumber = ?
1846 AND datearrived IS NULL
1848 my $sth = $dbh->prepare($query);
1849 $sth->execute($itemnumber);
1850 my @row = $sth->fetchrow_array();
1856 =head2 GetTransfersFromTo
1858 @results = GetTransfersFromTo($frombranch,$tobranch);
1860 Returns the list of pending transfers between $from and $to branch
1864 sub GetTransfersFromTo {
1865 my ( $frombranch, $tobranch ) = @_;
1866 return unless ( $frombranch && $tobranch );
1867 my $dbh = C4::Context->dbh;
1869 SELECT itemnumber,datesent,frombranch
1870 FROM branchtransfers
1873 AND datearrived IS NULL
1875 my $sth = $dbh->prepare($query);
1876 $sth->execute( $frombranch, $tobranch );
1879 while ( my $data = $sth->fetchrow_hashref ) {
1880 push @gettransfers, $data;
1883 return (@gettransfers);
1886 =head2 DeleteTransfer
1888 &DeleteTransfer($itemnumber);
1892 sub DeleteTransfer {
1893 my ($itemnumber) = @_;
1894 my $dbh = C4::Context->dbh;
1895 my $sth = $dbh->prepare(
1896 "DELETE FROM branchtransfers
1898 AND datearrived IS NULL "
1900 $sth->execute($itemnumber);
1904 =head2 AnonymiseIssueHistory
1906 $rows = AnonymiseIssueHistory($borrowernumber,$date)
1908 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
1909 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
1911 return the number of affected rows.
1915 sub AnonymiseIssueHistory {
1917 my $borrowernumber = shift;
1918 my $dbh = C4::Context->dbh;
1921 SET borrowernumber = NULL
1922 WHERE returndate < '".$date."'
1923 AND borrowernumber IS NOT NULL
1925 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
1926 my $rows_affected = $dbh->do($query);
1927 return $rows_affected;
1930 =head2 updateWrongTransfer
1932 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
1934 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
1938 sub updateWrongTransfer {
1939 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
1940 my $dbh = C4::Context->dbh;
1941 # first step validate the actual line of transfert .
1944 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
1946 $sth->execute($FromLibrary,$itemNumber);
1949 # second step create a new line of branchtransfer to the right location .
1950 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
1952 #third step changing holdingbranch of item
1953 UpdateHoldingbranch($FromLibrary,$itemNumber);
1956 =head2 UpdateHoldingbranch
1958 $items = UpdateHoldingbranch($branch,$itmenumber);
1959 Simple methode for updating hodlingbranch in items BDD line
1962 sub UpdateHoldingbranch {
1963 my ( $branch,$itmenumber ) = @_;
1964 my $dbh = C4::Context->dbh;
1965 # first step validate the actual line of transfert .
1968 "update items set holdingbranch = ? where itemnumber= ?"
1970 $sth->execute($branch,$itmenumber);
1975 =head2 CheckValidDatedue
1977 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
1978 this function return a new date due after checked if it's a repeatable or special holiday
1979 C<$date_due> = returndate calculate with no day check
1980 C<$itemnumber> = itemnumber
1981 C<$branchcode> = localisation of issue
1983 # Why not create calendar object? -
1984 # TODO add 'duedate' option to useDaysMode .
1985 sub CheckValidDatedue {
1986 my ($date_due,$itemnumber,$branchcode)=@_;
1987 my @datedue=split('-',$date_due->output('iso'));
1988 my $years=$datedue[0];
1989 my $month=$datedue[1];
1990 my $day=$datedue[2];
1991 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
1993 for (my $i=0;$i<2;$i++){
1994 $dow=Day_of_Week($years,$month,$day);
1995 ($dow=0) if ($dow>6);
1996 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
1997 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1998 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1999 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2001 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2004 my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2007 =head2 CheckRepeatableHolidays
2009 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2010 this function check if the date due is a repeatable holiday
2011 C<$date_due> = returndate calculate with no day check
2012 C<$itemnumber> = itemnumber
2013 C<$branchcode> = localisation of issue
2017 sub CheckRepeatableHolidays{
2018 my($itemnumber,$week_day,$branchcode)=@_;
2019 my $dbh = C4::Context->dbh;
2020 my $query = qq|SELECT count(*)
2021 FROM repeatable_holidays
2024 my $sth = $dbh->prepare($query);
2025 $sth->execute($branchcode,$week_day);
2026 my $result=$sth->fetchrow;
2032 =head2 CheckSpecialHolidays
2034 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2035 this function check if the date is a special holiday
2036 C<$years> = the years of datedue
2037 C<$month> = the month of datedue
2038 C<$day> = the day of datedue
2039 C<$itemnumber> = itemnumber
2040 C<$branchcode> = localisation of issue
2042 sub CheckSpecialHolidays{
2043 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2044 my $dbh = C4::Context->dbh;
2045 my $query=qq|SELECT count(*)
2046 FROM `special_holidays`
2052 my $sth = $dbh->prepare($query);
2053 $sth->execute($years,$month,$day,$branchcode);
2054 my $countspecial=$sth->fetchrow ;
2056 return $countspecial;
2059 =head2 CheckRepeatableSpecialHolidays
2061 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2062 this function check if the date is a repeatble special holidays
2063 C<$month> = the month of datedue
2064 C<$day> = the day of datedue
2065 C<$itemnumber> = itemnumber
2066 C<$branchcode> = localisation of issue
2068 sub CheckRepeatableSpecialHolidays{
2069 my ($month,$day,$itemnumber,$branchcode) = @_;
2070 my $dbh = C4::Context->dbh;
2071 my $query=qq|SELECT count(*)
2072 FROM `repeatable_holidays`
2077 my $sth = $dbh->prepare($query);
2078 $sth->execute($month,$day,$branchcode);
2079 my $countspecial=$sth->fetchrow ;
2081 return $countspecial;
2086 sub CheckValidBarcode{
2088 my $dbh = C4::Context->dbh;
2089 my $query=qq|SELECT count(*)
2093 my $sth = $dbh->prepare($query);
2094 $sth->execute($barcode);
2095 my $exist=$sth->fetchrow ;
2106 Koha Developement team <info@koha.org>