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
40 use POSIX qw(strftime);
41 use C4::Branch; # GetBranches
42 use C4::Log; # logaction
44 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,%EXPORT_TAGS);
46 # set the version for version checking
47 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v).".".join( "_", map { sprintf "%03d", $_ } @v ); };
51 C4::Circulation - Koha circulation module
59 The functions in this module deal with circulation, issues, and
60 returns, as well as general information about the library.
61 Also deals with stocktaking.
69 # FIXME subs that should probably be elsewhere
75 # subs to deal with issuing a book
86 &AnonymiseIssueHistory
88 # subs to deal with returns
93 # subs to deal with transfers
102 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
103 # 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 ?
107 =head3 $str = &decode($chunk);
111 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
118 sub cuecatbarcodedecode {
121 my @fields = split( /\./, $barcode );
122 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
123 if ( $#results == 2 ) {
133 =head3 $str = &decode($chunk);
137 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
147 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
148 my @s = map { index( $seq, $_ ); } split( //, $encoded );
149 my $l = ( $#s + 1 ) % 4;
160 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
162 chr( ( $n >> 16 ) ^ 67 )
163 .chr( ( $n >> 8 & 255 ) ^ 67 )
164 .chr( ( $n & 255 ) ^ 67 );
167 $r = substr( $r, 0, length($r) - $l );
173 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
175 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
177 C<$newbranch> is the code for the branch to which the item should be transferred.
179 C<$barcode> is the barcode of the item to be transferred.
181 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
182 Otherwise, if an item is reserved, the transfer fails.
184 Returns three values:
188 is true if the transfer was successful.
192 is a reference-to-hash which may have any of the following keys:
198 There is no item in the catalog with the given barcode. The value is C<$barcode>.
202 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.
204 =item C<DestinationEqualsHolding>
206 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.
210 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.
214 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>.
216 =item C<WasTransferred>
218 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
225 my ( $tbr, $barcode, $ignoreRs ) = @_;
228 my $branches = GetBranches();
229 my $itemnumber = GetItemnumberFromBarcode( $barcode );
230 my $issue = GetItemIssue($itemnumber);
231 my $biblio = GetBiblioFromItemNumber($itemnumber);
234 if ( not $itemnumber ) {
235 $messages->{'BadBarcode'} = $barcode;
239 # get branches of book...
240 my $hbr = $biblio->{'homebranch'};
241 my $fbr = $biblio->{'holdingbranch'};
244 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
245 $messages->{'IsPermanent'} = $hbr;
248 # can't transfer book if is already there....
249 if ( $fbr eq $tbr ) {
250 $messages->{'DestinationEqualsHolding'} = 1;
254 # check if it is still issued to someone, return it...
255 if ($issue->{borrowernumber}) {
256 AddReturn( $barcode, $fbr );
257 $messages->{'WasReturned'} = $issue->{borrowernumber};
261 # That'll save a database query.
262 my ( $resfound, $resrec ) =
263 CheckReserves( $itemnumber );
264 if ( $resfound and not $ignoreRs ) {
265 $resrec->{'ResFound'} = $resfound;
267 # $messages->{'ResFound'} = $resrec;
271 #actually do the transfer....
273 ModItemTransfer( $itemnumber, $fbr, $tbr );
275 # don't need to update MARC anymore, we do it in batch now
276 $messages->{'WasTransfered'} = 1;
277 ModDateLastSeen( $itemnumber );
279 return ( $dotransfer, $messages, $biblio );
282 =head2 CanBookBeIssued
284 Check if a book can be issued.
286 my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($borrower,$barcode,$year,$month,$day);
290 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
292 =item C<$barcode> is the bar code of the book being issued.
294 =item C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
302 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
303 Possible values are :
309 sticky due date is invalid
313 borrower gone with no address
317 borrower declared it's card lost
323 =head3 UNKNOWN_BARCODE
337 item is restricted (set by ??)
339 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
340 Possible values are :
348 renewing, not issuing
350 =head3 ISSUED_TO_ANOTHER
352 issued to someone else.
356 reserved for someone else.
360 sticky due date is invalid
364 if the borrower borrows to much things
368 # check if a book can be issued.
372 my $borrower = shift;
373 my $biblionumber = shift;
374 my $cat_borrower = $borrower->{'categorycode'};
375 my $branch_borrower = $borrower->{'branchcode'};
376 my $dbh = C4::Context->dbh;
379 $dbh->prepare('SELECT itemtype FROM biblioitems WHERE biblionumber = ?');
380 $sth->execute($biblionumber);
381 my $type = $sth->fetchrow;
384 'SELECT * FROM issuingrules
385 WHERE categorycode = ?
392 "SELECT COUNT(*) FROM issues i, biblioitems s1, items s2
393 WHERE i.borrowernumber = ?
394 AND i.returndate IS NULL
395 AND i.itemnumber = s2.itemnumber
396 AND s1.itemtype LIKE ?
397 AND s1.biblioitemnumber = s2.biblioitemnumber"
401 'SELECT COUNT(*) FROM issues
402 WHERE borrowernumber = ?
403 AND returndate IS NULL'
407 # check the 3 parameters (branch / itemtype / category code
408 $sth->execute( $cat_borrower, $type, $branch_borrower );
409 my $result = $sth->fetchrow_hashref;
410 # warn "$cat_borrower, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
412 if ( $result->{maxissueqty} ne '' ) {
413 # warn "checking on everything set";
414 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
415 my $alreadyissued = $sth2->fetchrow;
416 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
417 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/itemtype failed)" );
419 # now checking for total
420 $sth->execute( $cat_borrower, '', $branch_borrower );
421 my $result = $sth->fetchrow_hashref;
422 if ( $result->{maxissueqty} ne '*' ) {
423 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
424 my $alreadyissued = $sth2->fetchrow;
425 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
426 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/total failed)" );
431 # check the 2 parameters (branch / itemtype / default categorycode
432 $sth->execute( '*', $type, $branch_borrower );
433 my $result = $sth->fetchrow_hashref;
434 # warn "*, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
436 if ( $result->{maxissueqty} ne '' ) {
437 # warn "checking on 2 parameters (default categorycode)";
438 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
439 my $alreadyissued = $sth2->fetchrow;
440 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
441 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / itemtype failed)" );
443 # now checking for total
444 $sth->execute( '*', '*', $branch_borrower );
445 my $result = $sth->fetchrow_hashref;
446 if ( $result->{maxissueqty} ne '' ) {
447 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
448 my $alreadyissued = $sth2->fetchrow;
449 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
450 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / total failed)" );
455 # check the 1 parameters (default branch / itemtype / categorycode
456 $sth->execute( $cat_borrower, $type, '*' );
457 my $result = $sth->fetchrow_hashref;
458 # warn "$cat_borrower, $type, * = ".Data::Dumper::Dumper($result);
460 if ( $result->{maxissueqty} ne '' ) {
461 # warn "checking on 1 parameter (default branch + categorycode)";
462 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
463 my $alreadyissued = $sth2->fetchrow;
464 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
465 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch/category/itemtype failed)" );
467 # now checking for total
468 $sth->execute( $cat_borrower, '*', '*' );
469 my $result = $sth->fetchrow_hashref;
470 if ( $result->{maxissueqty} ne '' ) {
471 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
472 my $alreadyissued = $sth2->fetchrow;
473 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
474 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / category / total failed)" );
479 # check the 0 parameters (default branch / itemtype / default categorycode
480 $sth->execute( '*', $type, '*' );
481 my $result = $sth->fetchrow_hashref;
482 # warn "*, $type, * = ".Data::Dumper::Dumper($result);
484 if ( $result->{maxissueqty} ne '' ) {
485 # warn "checking on default branch and default categorycode";
486 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
487 my $alreadyissued = $sth2->fetchrow;
488 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
489 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / itemtype failed)" );
491 # now checking for total
492 $sth->execute( '*', '*', '*' );
493 my $result = $sth->fetchrow_hashref;
494 if ( $result->{maxissueqty} ne '' ) {
495 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
496 my $alreadyissued = $sth2->fetchrow;
497 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
498 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / total failed)" );
503 #OK, the patron can issue !!!
509 @issues = &itemissues($biblioitemnumber, $biblio);
511 Looks up information about who has borrowed the bookZ<>(s) with the
512 given biblioitemnumber.
514 C<$biblio> is ignored.
516 C<&itemissues> returns an array of references-to-hash. The keys
517 include the fields from the C<items> table in the Koha database.
518 Additional keys include:
524 If the item is currently on loan, this gives the due date.
526 If the item is not on loan, then this is either "Available" or
527 "Cancelled", if the item has been withdrawn.
531 If the item is currently on loan, this gives the card number of the
532 patron who currently has the item.
534 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
536 These give the timestamp for the last three times the item was
539 =item C<card0>, C<card1>, C<card2>
541 The card number of the last three patrons who borrowed this item.
543 =item C<borrower0>, C<borrower1>, C<borrower2>
545 The borrower number of the last three patrons who borrowed this item.
553 my ( $bibitem, $biblio ) = @_;
554 my $dbh = C4::Context->dbh;
556 # FIXME - If this function die()s, the script will abort, and the
557 # user won't get anything; depending on how far the script has
558 # gotten, the user might get a blank page. It would be much better
559 # to at least print an error message. The easiest way to do this
560 # is to set $SIG{__DIE__}.
562 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
567 $sth->execute($bibitem) || die $sth->errstr;
569 while ( my $data = $sth->fetchrow_hashref ) {
571 # Find out who currently has this item.
572 # FIXME - Wouldn't it be better to do this as a left join of
573 # some sort? Currently, this code assumes that if
574 # fetchrow_hashref() fails, then the book is on the shelf.
575 # fetchrow_hashref() can fail for any number of reasons (e.g.,
576 # database server crash), not just because no items match the
578 my $sth2 = $dbh->prepare(
579 "SELECT * FROM issues
580 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
582 AND returndate IS NULL
586 $sth2->execute( $data->{'itemnumber'} );
587 if ( my $data2 = $sth2->fetchrow_hashref ) {
588 $data->{'date_due'} = $data2->{'date_due'};
589 $data->{'card'} = $data2->{'cardnumber'};
590 $data->{'borrower'} = $data2->{'borrowernumber'};
593 if ( $data->{'wthdrawn'} eq '1' ) {
594 $data->{'date_due'} = 'Cancelled';
597 $data->{'date_due'} = 'Available';
603 # Find the last 3 people who borrowed this item.
604 $sth2 = $dbh->prepare(
605 "SELECT * FROM issues
606 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
608 AND returndate IS NOT NULL
609 ORDER BY returndate DESC,timestamp DESC"
612 # $sth2 = $dbh->prepare("
615 # LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
616 # WHERE itemnumber = ?
617 # AND returndate is not NULL
618 # ORDER BY returndate DESC,timestamp DESC
621 $sth2->execute( $data->{'itemnumber'} );
622 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
623 { # FIXME : error if there is less than 3 pple borrowing this item
624 if ( my $data2 = $sth2->fetchrow_hashref ) {
625 $data->{"timestamp$i2"} = $data2->{'timestamp'};
626 $data->{"card$i2"} = $data2->{'cardnumber'};
627 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
632 $results[$i] = $data;
640 =head2 CanBookBeIssued
642 $issuingimpossible, $needsconfirmation =
643 CanBookBeIssued( $borrower, $barcode, $year, $month, $day, $inprocess );
645 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
649 sub CanBookBeIssued {
650 my ( $borrower, $barcode, $year, $month, $day, $inprocess ) = @_;
651 my %needsconfirmation; # filled with problems that needs confirmations
652 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
653 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
654 my $issue = GetItemIssue($item->{itemnumber});
655 my $dbh = C4::Context->dbh;
660 my ( $duedate, $invalidduedate ) = fixdate( $year, $month, $day );
661 $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
666 if ( $borrower->{flags}->{GNA} ) {
667 $issuingimpossible{GNA} = 1;
669 if ( $borrower->{flags}->{'LOST'} ) {
670 $issuingimpossible{CARD_LOST} = 1;
672 if ( $borrower->{flags}->{'DBARRED'} ) {
673 $issuingimpossible{DEBARRED} = 1;
675 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
676 $issuingimpossible{EXPIRED} = 1;
678 my @expirydate= split /-/,$borrower->{'dateexpiry'};
679 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
680 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
681 $issuingimpossible{EXPIRED} = 1;
690 GetMemberAccountRecords( $borrower->{'borrowernumber'}, $duedate );
691 if ( C4::Context->preference("IssuingInProcess") ) {
692 my $amountlimit = C4::Context->preference("noissuescharge");
693 if ( $amount > $amountlimit && !$inprocess ) {
694 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
696 elsif ( $amount <= $amountlimit && !$inprocess ) {
697 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
702 $needsconfirmation{DEBT} = $amount;
707 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
709 my $toomany = TooMany( $borrower, $item->{biblionumber} );
710 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
715 unless ( $item->{barcode} ) {
716 $issuingimpossible{UNKNOWN_BARCODE} = 1;
718 if ( $item->{'notforloan'}
719 && $item->{'notforloan'} > 0 )
721 $issuingimpossible{NOT_FOR_LOAN} = 1;
723 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
725 $issuingimpossible{WTHDRAWN} = 1;
727 if ( $item->{'restricted'}
728 && $item->{'restricted'} == 1 )
730 $issuingimpossible{RESTRICTED} = 1;
732 if ( C4::Context->preference("IndependantBranches") ) {
733 my $userenv = C4::Context->userenv;
734 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
735 $issuingimpossible{NOTSAMEBRANCH} = 1
736 if ( $item->{'holdingbranch'} ne $userenv->{branch} );
741 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
743 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
746 # Already issued to current borrower. Ask whether the loan should
748 my ($CanBookBeRenewed) = CanBookBeRenewed(
749 $borrower->{'borrowernumber'},
750 $item->{'itemnumber'}
752 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
753 $issuingimpossible{NO_MORE_RENEWALS} = 1;
756 $needsconfirmation{RENEW_ISSUE} = 1;
759 elsif ($issue->{borrowernumber}) {
761 # issued to someone else
762 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
764 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
765 $needsconfirmation{ISSUED_TO_ANOTHER} =
766 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
769 # See if the item is on reserve.
770 my ( $restype, $res ) = CheckReserves( $item->{'itemnumber'} );
772 my $resbor = $res->{'borrowernumber'};
773 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
776 # The item is on reserve and waiting, but has been
777 # reserved by some other patron.
778 my ( $resborrower, $flags ) =
779 GetMemberDetails( $resbor, 0 );
780 my $branches = GetBranches();
782 $branches->{ $res->{'branchcode'} }->{'branchname'};
783 $needsconfirmation{RESERVE_WAITING} =
784 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
786 # CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'}); Doesn't belong in a checking subroutine.
788 elsif ( $restype eq "Reserved" ) {
790 # The item is on reserve for someone else.
791 my ( $resborrower, $flags ) =
792 GetMemberDetails( $resbor, 0 );
793 my $branches = GetBranches();
795 $branches->{ $res->{'branchcode'} }->{'branchname'};
796 $needsconfirmation{RESERVED} =
797 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
800 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
801 if ( $borrower->{'categorycode'} eq 'W' ) {
802 my %issuingimpossible;
803 return ( \%issuingimpossible, \%needsconfirmation );
805 return ( \%issuingimpossible, \%needsconfirmation );
808 return ( \%issuingimpossible, \%needsconfirmation );
814 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
816 &AddIssue($borrower,$barcode,$date)
820 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
822 =item C<$barcode> is the bar code of the book being issued.
824 =item C<$date> contains the max date of return. calculated if empty.
826 AddIssue does the following things :
827 - step 01: check that there is a borrowernumber & a barcode provided
828 - check for RENEWAL (book issued & being issued to the same patron)
829 - renewal YES = Calculate Charge & renew
831 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
833 - fill reserve if reserve to this patron
834 - cancel reserve or not, otherwise
835 * TRANSFERT PENDING ?
836 - complete the transfert
844 my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
845 my $dbh = C4::Context->dbh;
846 my $barcodecheck=CheckValidBarcode($barcode);
847 if ($borrower and $barcode and $barcodecheck ne '0'){
848 # my ($borrower, $flags) = &GetMemberDetails($borrowernumber, 0);
849 # find which item we issue
850 my $item = GetItem('', $barcode);
852 # get actual issuing if there is one
853 my $actualissue = GetItemIssue( $item->{itemnumber});
855 # get biblioinformation for this item
856 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
859 # check if we just renew the issue.
861 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
862 # we renew, do we need to add some charge ?
863 my ( $charge, $itemtype ) = GetIssuingCharges(
864 $item->{'itemnumber'},
865 $borrower->{'borrowernumber'}
869 $item->{'itemnumber'},
870 $borrower->{'borrowernumber'}, $charge
872 $item->{'charge'} = $charge;
875 C4::Context->userenv->{'branch'},
877 '', $item->{'itemnumber'},
878 $biblio->{'itemtype'}, $borrower->{'borrowernumber'}
881 $borrower->{'borrowernumber'},
882 $item->{'itemnumber'}
885 else {# it's NOT a renewal
886 if ( $actualissue->{borrowernumber}) {
887 # This book is currently on loan, but not to the person
888 # who wants to borrow it now. mark it returned before issuing to the new borrower
891 C4::Context->userenv->{'branch'}
895 # See if the item is on reserve.
896 my ( $restype, $res ) =
897 CheckReserves( $item->{'itemnumber'} );
899 my $resbor = $res->{'borrowernumber'};
900 if ( $resbor eq $borrower->{'borrowernumber'} ) {
902 # The item is reserved by the current patron
903 ModReserveFill($res);
905 elsif ( $restype eq "Waiting" ) {
908 # The item is on reserve and waiting, but has been
909 # reserved by some other patron.
910 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
911 my $branches = GetBranches();
913 $branches->{ $res->{'branchcode'} }->{'branchname'};
915 elsif ( $restype eq "Reserved" ) {
918 # The item is reserved by someone else.
919 my ( $resborrower, $flags ) =
920 GetMemberDetails( $resbor, 0 );
921 my $branches = GetBranches();
923 $branches->{ $res->{'branchcode'} }->{'branchname'};
924 if ($cancelreserve) { # cancel reserves on this item
925 CancelReserve( 0, $res->{'itemnumber'},
926 $res->{'borrowernumber'} );
929 if ($cancelreserve) {
930 CancelReserve( $res->{'biblionumber'}, 0,
931 $res->{'borrowernumber'} );
934 # set waiting reserve to first in reserve queue as book isn't waiting now
937 $res->{'biblionumber'},
938 $res->{'borrowernumber'},
944 # Starting process for transfer job (checking transfert and validate it if we have one)
945 my ($datesent) = GetTransfers($item->{'itemnumber'});
947 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
950 "UPDATE branchtransfers
951 SET datearrived = now(),
953 comments = 'Forced branchtransfert'
954 WHERE itemnumber= ? AND datearrived IS NULL"
956 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
960 # Record in the database the fact that the book was issued.
964 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
967 my $loanlength = GetLoanLength(
968 $borrower->{'categorycode'},
969 $biblio->{'itemtype'},
970 $borrower->{'branchcode'}
972 my $datedue = time + ($loanlength) * 86400;
973 my @datearr = localtime($datedue);
975 sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]);
979 $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')
982 && $dateduef gt $borrower->{dateexpiry} )
984 $dateduef = $borrower->{dateexpiry};
987 $borrower->{'borrowernumber'},
988 $item->{'itemnumber'},
989 strftime( "%Y-%m-%d", localtime ),$dateduef, C4::Context->userenv->{'branch'}
995 "UPDATE items SET issues=?, holdingbranch=?, itemlost=0, datelastborrowed = now() WHERE itemnumber=?");
998 C4::Context->userenv->{'branch'},
999 $item->{'itemnumber'}
1002 &ModDateLastSeen( $item->{'itemnumber'} );
1003 # If it costs to borrow this book, charge it to the patron's account.
1004 my ( $charge, $itemtype ) = GetIssuingCharges(
1005 $item->{'itemnumber'},
1006 $borrower->{'borrowernumber'}
1008 if ( $charge > 0 ) {
1010 $item->{'itemnumber'},
1011 $borrower->{'borrowernumber'}, $charge
1013 $item->{'charge'} = $charge;
1016 # Record the fact that this book was issued.
1018 C4::Context->userenv->{'branch'},
1020 '', $item->{'itemnumber'},
1021 $item->{'itemtype'}, $borrower->{'borrowernumber'}
1025 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'})
1026 if C4::Context->preference("IssueLog");
1030 =head2 GetLoanLength
1032 Get loan length for an itemtype, a borrower type and a branch
1034 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1039 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1040 my $dbh = C4::Context->dbh;
1043 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=?"
1046 # try to find issuelength & return the 1st available.
1047 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1048 $sth->execute( $borrowertype, $itemtype, $branchcode );
1049 my $loanlength = $sth->fetchrow_hashref;
1050 return $loanlength->{issuelength}
1051 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1053 $sth->execute( $borrowertype, $itemtype, "" );
1054 $loanlength = $sth->fetchrow_hashref;
1055 return $loanlength->{issuelength}
1056 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1058 $sth->execute( $borrowertype, "*", $branchcode );
1059 $loanlength = $sth->fetchrow_hashref;
1060 return $loanlength->{issuelength}
1061 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1063 $sth->execute( "*", $itemtype, $branchcode );
1064 $loanlength = $sth->fetchrow_hashref;
1065 return $loanlength->{issuelength}
1066 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1068 $sth->execute( $borrowertype, "*", "" );
1069 $loanlength = $sth->fetchrow_hashref;
1070 return $loanlength->{issuelength}
1071 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1073 $sth->execute( "*", "*", $branchcode );
1074 $loanlength = $sth->fetchrow_hashref;
1075 return $loanlength->{issuelength}
1076 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1078 $sth->execute( "*", $itemtype, "" );
1079 $loanlength = $sth->fetchrow_hashref;
1080 return $loanlength->{issuelength}
1081 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1083 $sth->execute( "*", "*", "" );
1084 $loanlength = $sth->fetchrow_hashref;
1085 return $loanlength->{issuelength}
1086 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1088 # if no rule is set => 21 days (hardcoded)
1094 ($doreturn, $messages, $iteminformation, $borrower) =
1095 &AddReturn($barcode, $branch);
1099 C<$barcode> is the bar code of the book being returned. C<$branch> is
1100 the code of the branch where the book is being returned.
1102 C<&AddReturn> returns a list of four items:
1104 C<$doreturn> is true iff the return succeeded.
1106 C<$messages> is a reference-to-hash giving the reason for failure:
1112 No item with this barcode exists. The value is C<$barcode>.
1116 The book is not currently on loan. The value is C<$barcode>.
1118 =item C<IsPermanent>
1120 The book's home branch is a permanent collection. If you have borrowed
1121 this book, you are not allowed to return it. The value is the code for
1122 the book's home branch.
1126 This book has been withdrawn/cancelled. The value should be ignored.
1130 The item was reserved. The value is a reference-to-hash whose keys are
1131 fields from the reserves table of the Koha database, and
1132 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1133 either C<Waiting>, C<Reserved>, or 0.
1137 C<$borrower> is a reference-to-hash, giving information about the
1138 patron who last borrowed the book.
1143 my ( $barcode, $branch ) = @_;
1144 my $dbh = C4::Context->dbh;
1148 my $validTransfert = 0;
1149 my $reserveDone = 0;
1151 # get information on item
1152 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1153 unless ($iteminformation->{'itemnumber'} ) {
1154 $messages->{'BadBarcode'} = $barcode;
1158 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1159 $messages->{'NotIssued'} = $barcode;
1163 # check if the book is in a permanent collection....
1164 my $hbr = $iteminformation->{'homebranch'};
1165 my $branches = GetBranches();
1166 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1167 $messages->{'IsPermanent'} = $hbr;
1170 # check that the book has been cancelled
1171 if ( $iteminformation->{'wthdrawn'} ) {
1172 $messages->{'wthdrawn'} = 1;
1176 # new op dev : if the book returned in an other branch update the holding branch
1178 # update issues, thereby returning book (should push this out into another subroutine
1179 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1181 # case of a return of document (deal with issues and holdingbranch)
1186 "UPDATE issues SET returndate = now() WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (returndate IS NULL)"
1188 $sth->execute( $borrower->{'borrowernumber'},
1189 $iteminformation->{'itemnumber'} );
1190 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1193 # continue to deal with returns cases, but not only if we have an issue
1195 # the holdingbranch is updated if the document is returned in an other location .
1196 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} )
1198 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1199 # reload iteminformation holdingbranch with the userenv value
1200 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1202 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1203 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1205 # fix up the accounts.....
1206 if ( $iteminformation->{'itemlost'} ) {
1207 $messages->{'WasLost'} = 1;
1210 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1211 # check if we have a transfer for this document
1212 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1214 # if we have a transfer to do, we update the line of transfers with the datearrived
1216 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1219 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1221 $sth->execute( $iteminformation->{'itemnumber'} );
1223 # 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'
1224 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1227 $messages->{'WrongTransfer'} = $tobranch;
1228 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1230 $validTransfert = 1;
1233 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1234 # fix up the accounts.....
1235 if ($iteminformation->{'itemlost'}) {
1236 FixAccountForLostAndReturned($iteminformation, $borrower);
1237 $messages->{'WasLost'} = 1;
1239 # fix up the overdues in accounts...
1240 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1241 $iteminformation->{'itemnumber'} );
1243 # find reserves.....
1244 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1245 my ( $resfound, $resrec ) =
1246 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1248 $resrec->{'ResFound'} = $resfound;
1249 $messages->{'ResFound'} = $resrec;
1254 # Record the fact that this book was returned.
1256 $branch, 'return', '0', '',
1257 $iteminformation->{'itemnumber'},
1258 $iteminformation->{'itemtype'},
1259 $borrower->{'borrowernumber'}
1262 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'})
1263 if C4::Context->preference("ReturnLog");
1265 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1266 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1268 if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1269 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1270 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1271 $messages->{'WasTransfered'} = 1;
1272 warn "was transfered";
1276 return ( $doreturn, $messages, $iteminformation, $borrower );
1279 =head2 FixOverduesOnReturn
1281 &FixOverduesOnReturn($brn,$itm);
1283 C<$brn> borrowernumber
1287 internal function, called only by AddReturn
1291 sub FixOverduesOnReturn {
1292 my ( $borrowernumber, $item ) = @_;
1293 my $dbh = C4::Context->dbh;
1295 # check for overdue fine
1298 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1300 $sth->execute( $borrowernumber, $item );
1302 # alter fine to show that the book has been returned
1303 if ( my $data = $sth->fetchrow_hashref ) {
1306 "UPDATE accountlines SET accounttype='F' WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accountno = ?)"
1308 $usth->execute( $borrowernumber, $item, $data->{'accountno'} );
1315 =head2 FixAccountForLostAndReturned
1317 &FixAccountForLostAndReturned($iteminfo,$borrower);
1319 Calculates the charge for a book lost and returned (Not exported & used only once)
1321 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1323 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1325 Internal function, called by AddReturn
1329 sub FixAccountForLostAndReturned {
1330 my ($iteminfo, $borrower) = @_;
1332 my $dbh = C4::Context->dbh;
1333 my $itm = $iteminfo->{'itemnumber'};
1334 # check for charge made for lost book
1335 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1336 $sth->execute($itm);
1337 if (my $data = $sth->fetchrow_hashref) {
1338 # writeoff this amount
1340 my $amount = $data->{'amount'};
1341 my $acctno = $data->{'accountno'};
1343 if ($data->{'amountoutstanding'} == $amount) {
1344 $offset = $data->{'amount'};
1347 $offset = $amount - $data->{'amountoutstanding'};
1348 $amountleft = $data->{'amountoutstanding'} - $amount;
1350 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1351 WHERE (borrowernumber = ?)
1352 AND (itemnumber = ?) AND (accountno = ?) ");
1353 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1355 #check if any credit is left if so writeoff other accounts
1356 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1357 if ($amountleft < 0){
1360 if ($amountleft > 0){
1361 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1362 AND (amountoutstanding >0) ORDER BY date");
1363 $msth->execute($data->{'borrowernumber'});
1364 # offset transactions
1367 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1368 if ($accdata->{'amountoutstanding'} < $amountleft) {
1370 $amountleft -= $accdata->{'amountoutstanding'};
1372 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1375 my $thisacct = $accdata->{'accountno'};
1376 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1377 WHERE (borrowernumber = ?)
1378 AND (accountno=?)");
1379 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1381 $usth = $dbh->prepare("INSERT INTO accountoffsets
1382 (borrowernumber, accountno, offsetaccount, offsetamount)
1385 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1390 if ($amountleft > 0){
1393 my $desc="Book Returned ".$iteminfo->{'barcode'};
1394 $usth = $dbh->prepare("INSERT INTO accountlines
1395 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1396 VALUES (?,?,now(),?,?,'CR',?)");
1397 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1399 $usth = $dbh->prepare("INSERT INTO accountoffsets
1400 (borrowernumber, accountno, offsetaccount, offsetamount)
1402 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1404 $usth = $dbh->prepare("UPDATE items SET paidfor='' WHERE itemnumber=?");
1405 $usth->execute($itm);
1414 $issues = &GetItemIssue($itemnumber);
1416 Returns patrons currently having a book. nothing if item is not issued atm
1418 C<$itemnumber> is the itemnumber
1420 Returns an array of hashes
1424 my ( $itemnumber) = @_;
1425 return unless $itemnumber;
1426 my $dbh = C4::Context->dbh;
1430 my $today = POSIX::strftime("%Y%m%d", localtime);
1432 my $sth = $dbh->prepare(
1433 "SELECT * FROM issues
1434 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1436 issues.itemnumber=? AND returndate IS NULL ");
1437 $sth->execute($itemnumber);
1438 my $data = $sth->fetchrow_hashref;
1439 my $datedue = $data->{'date_due'};
1441 if ( $datedue < $today ) {
1442 $data->{'overdue'} = 1;
1444 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1449 =head2 GetItemIssues
1451 $issues = &GetItemIssues($itemnumber, $history);
1453 Returns patrons that have issued a book
1455 C<$itemnumber> is the itemnumber
1456 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1458 Returns an array of hashes
1462 my ( $itemnumber,$history ) = @_;
1463 my $dbh = C4::Context->dbh;
1467 my $today = POSIX::strftime("%Y%m%d", localtime);
1469 my $sth = $dbh->prepare(
1470 "SELECT * FROM issues
1471 LEFT JOIN borrowers ON borrowers.borrowernumber
1472 LEFT JOIN items ON items.itemnumber=issues.itemnumber
1474 issues.itemnumber=?".($history?"":" AND returndate IS NULL ").
1475 "ORDER BY issues.date_due DESC"
1477 $sth->execute($itemnumber);
1478 while ( my $data = $sth->fetchrow_hashref ) {
1479 my $datedue = $data->{'date_due'};
1481 if ( $datedue < $today ) {
1482 $data->{'overdue'} = 1;
1484 my $itemnumber = $data->{'itemnumber'};
1485 push @GetItemIssues, $data;
1488 return ( \@GetItemIssues );
1491 =head2 GetBiblioIssues
1493 $issues = GetBiblioIssues($biblionumber);
1495 this function get all issues from a biblionumber.
1498 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1499 tables issues and the firstname,surname & cardnumber from borrowers.
1503 sub GetBiblioIssues {
1504 my $biblionumber = shift;
1505 return undef unless $biblionumber;
1506 my $dbh = C4::Context->dbh;
1508 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1510 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1511 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1512 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1513 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1514 WHERE biblio.biblionumber = ?
1515 ORDER BY issues.timestamp
1517 my $sth = $dbh->prepare($query);
1518 $sth->execute($biblionumber);
1521 while ( my $data = $sth->fetchrow_hashref ) {
1522 push @issues, $data;
1527 =head2 CanBookBeRenewed
1529 $ok = &CanBookBeRenewed($borrowernumber, $itemnumber);
1531 Find out whether a borrowed item may be renewed.
1533 C<$dbh> is a DBI handle to the Koha database.
1535 C<$borrowernumber> is the borrower number of the patron who currently
1536 has the item on loan.
1538 C<$itemnumber> is the number of the item to renew.
1540 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1541 item must currently be on loan to the specified borrower; renewals
1542 must be allowed for the item's type; and the borrower must not have
1543 already renewed the loan.
1547 sub CanBookBeRenewed {
1549 # check renewal status
1550 my ( $borrowernumber, $itemnumber ) = @_;
1551 my $dbh = C4::Context->dbh;
1555 # Look in the issues table for this item, lent to this borrower,
1556 # and not yet returned.
1558 # FIXME - I think this function could be redone to use only one SQL call.
1559 my $sth1 = $dbh->prepare(
1560 "SELECT * FROM issues
1561 WHERE borrowernumber = ?
1563 AND returndate IS NULL"
1565 $sth1->execute( $borrowernumber, $itemnumber );
1566 if ( my $data1 = $sth1->fetchrow_hashref ) {
1568 # Found a matching item
1570 # See if this item may be renewed. This query is convoluted
1571 # because it's a bit messy: given the item number, we need to find
1572 # the biblioitem, which gives us the itemtype, which tells us
1573 # whether it may be renewed.
1574 my $sth2 = $dbh->prepare(
1575 "SELECT renewalsallowed FROM items
1576 LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1577 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1578 WHERE items.itemnumber = ?
1581 $sth2->execute($itemnumber);
1582 if ( my $data2 = $sth2->fetchrow_hashref ) {
1583 $renews = $data2->{'renewalsallowed'};
1585 if ( $renews && $renews >= $data1->{'renewals'} ) {
1589 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1596 return ($renewokay);
1601 &AddRenewal($borrowernumber, $itemnumber, $datedue);
1605 C<$borrowernumber> is the borrower number of the patron who currently
1608 C<$itemnumber> is the number of the item to renew.
1610 C<$datedue> can be used to set the due date. If C<$datedue> is the
1611 empty string, C<&AddRenewal> will calculate the due date automatically
1612 from the book's item type. If you wish to set the due date manually,
1613 C<$datedue> should be in the form YYYY-MM-DD.
1619 my ( $borrowernumber, $itemnumber, $branch ,$datedue ) = @_;
1620 my $dbh = C4::Context->dbh;
1622 # If the due date wasn't specified, calculate it by adding the
1623 # book's loan length to today's date.
1624 if ( $datedue eq "" ) {
1626 my $biblio = GetBiblioFromItemNumber($itemnumber);
1627 my $borrower = GetMemberDetails( $borrowernumber, 0 );
1628 my $loanlength = GetLoanLength(
1629 $borrower->{'categorycode'},
1630 $biblio->{'itemtype'},
1631 $borrower->{'branchcode'}
1633 my ( $due_year, $due_month, $due_day ) =
1634 Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
1635 $datedue = "$due_year-$due_month-$due_day";
1636 $datedue=CheckValidDatedue($datedue,$itemnumber,$branch);
1639 # Find the issues record for this book
1641 $dbh->prepare("SELECT * FROM issues
1642 WHERE borrowernumber=?
1644 AND returndate IS NULL"
1646 $sth->execute( $borrowernumber, $itemnumber );
1647 my $issuedata = $sth->fetchrow_hashref;
1650 # Update the issues record to have the new due date, and a new count
1651 # of how many times it has been renewed.
1652 my $renews = $issuedata->{'renewals'} + 1;
1653 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1654 WHERE borrowernumber=?
1656 AND returndate IS NULL"
1658 $sth->execute( $datedue, $renews, $borrowernumber, $itemnumber );
1662 UpdateStats( C4::Context->userenv->{'branchcode'}, 'renew', '', '', $itemnumber );
1664 # Charge a new rental fee, if applicable?
1665 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1666 if ( $charge > 0 ) {
1667 my $accountno = getnextacctno( $borrowernumber );
1668 my $item = GetBiblioFromItemNumber($itemnumber);
1669 $sth = $dbh->prepare(
1670 "INSERT INTO accountlines
1671 (borrowernumber,accountno,date,amount,
1672 description,accounttype,amountoutstanding,
1674 VALUES (?,?,now(),?,?,?,?,?)"
1676 $sth->execute( $borrowernumber, $accountno, $charge,
1677 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1678 'Rent', $charge, $itemnumber );
1683 =head2 GetIssuingCharges
1685 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1687 Calculate how much it would cost for a given patron to borrow a given
1688 item, including any applicable discounts.
1690 C<$itemnumber> is the item number of item the patron wishes to borrow.
1692 C<$borrowernumber> is the patron's borrower number.
1694 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1695 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1700 sub GetIssuingCharges {
1702 # calculate charges due
1703 my ( $itemnumber, $borrowernumber ) = @_;
1705 my $dbh = C4::Context->dbh;
1708 # Get the book's item type and rental charge (via its biblioitem).
1709 my $sth1 = $dbh->prepare(
1710 "SELECT itemtypes.itemtype,rentalcharge FROM items
1711 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1712 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1713 WHERE items.itemnumber =?
1716 $sth1->execute($itemnumber);
1717 if ( my $data1 = $sth1->fetchrow_hashref ) {
1718 $item_type = $data1->{'itemtype'};
1719 $charge = $data1->{'rentalcharge'};
1720 my $q2 = "SELECT rentaldiscount FROM borrowers
1721 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1722 WHERE borrowers.borrowernumber = ?
1723 AND issuingrules.itemtype = ?";
1724 my $sth2 = $dbh->prepare($q2);
1725 $sth2->execute( $borrowernumber, $item_type );
1726 if ( my $data2 = $sth2->fetchrow_hashref ) {
1727 my $discount = $data2->{'rentaldiscount'};
1728 if ( $discount eq 'NULL' ) {
1731 $charge = ( $charge * ( 100 - $discount ) ) / 100;
1737 return ( $charge, $item_type );
1740 =head2 AddIssuingCharge
1742 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1746 sub AddIssuingCharge {
1747 my ( $itemnumber, $borrowernumber, $charge ) = @_;
1748 my $dbh = C4::Context->dbh;
1749 my $nextaccntno = getnextacctno( $borrowernumber );
1751 INSERT INTO accountlines
1752 (borrowernumber, itemnumber, accountno,
1753 date, amount, description, accounttype,
1755 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1757 my $sth = $dbh->prepare($query);
1758 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1764 GetTransfers($itemnumber);
1769 my ($itemnumber) = @_;
1771 my $dbh = C4::Context->dbh;
1777 FROM branchtransfers
1778 WHERE itemnumber = ?
1779 AND datearrived IS NULL
1781 my $sth = $dbh->prepare($query);
1782 $sth->execute($itemnumber);
1783 my @row = $sth->fetchrow_array();
1789 =head2 GetTransfersFromTo
1791 @results = GetTransfersFromTo($frombranch,$tobranch);
1793 Returns the list of pending transfers between $from and $to branch
1797 sub GetTransfersFromTo {
1798 my ( $frombranch, $tobranch ) = @_;
1799 return unless ( $frombranch && $tobranch );
1800 my $dbh = C4::Context->dbh;
1802 SELECT itemnumber,datesent,frombranch
1803 FROM branchtransfers
1806 AND datearrived IS NULL
1808 my $sth = $dbh->prepare($query);
1809 $sth->execute( $frombranch, $tobranch );
1812 while ( my $data = $sth->fetchrow_hashref ) {
1813 push @gettransfers, $data;
1816 return (@gettransfers);
1819 =head2 DeleteTransfer
1821 &DeleteTransfer($itemnumber);
1825 sub DeleteTransfer {
1826 my ($itemnumber) = @_;
1827 my $dbh = C4::Context->dbh;
1828 my $sth = $dbh->prepare(
1829 "DELETE FROM branchtransfers
1831 AND datearrived IS NULL "
1833 $sth->execute($itemnumber);
1837 =head2 AnonymiseIssueHistory
1839 $rows = AnonymiseIssueHistory($borrowernumber,$date)
1841 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
1842 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
1844 return the number of affected rows.
1848 sub AnonymiseIssueHistory {
1850 my $borrowernumber = shift;
1851 my $dbh = C4::Context->dbh;
1854 SET borrowernumber = NULL
1855 WHERE returndate < '".$date."'
1856 AND borrowernumber IS NOT NULL
1858 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
1859 my $rows_affected = $dbh->do($query);
1860 return $rows_affected;
1863 =head2 updateWrongTransfer
1865 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
1867 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
1871 sub updateWrongTransfer {
1872 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
1873 my $dbh = C4::Context->dbh;
1874 # first step validate the actual line of transfert .
1877 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
1879 $sth->execute($FromLibrary,$itemNumber);
1882 # second step create a new line of branchtransfer to the right location .
1883 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
1885 #third step changing holdingbranch of item
1886 UpdateHoldingbranch($FromLibrary,$itemNumber);
1889 =head2 UpdateHoldingbranch
1891 $items = UpdateHoldingbranch($branch,$itmenumber);
1892 Simple methode for updating hodlingbranch in items BDD line
1895 sub UpdateHoldingbranch {
1896 my ( $branch,$itmenumber ) = @_;
1897 my $dbh = C4::Context->dbh;
1898 # first step validate the actual line of transfert .
1901 "update items set holdingbranch = ? where itemnumber= ?"
1903 $sth->execute($branch,$itmenumber);
1908 =head2 CheckValidDatedue
1910 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
1911 this function return a new date due after checked if it's a repeatable or special holiday
1912 C<$date_due> = returndate calculate with no day check
1913 C<$itemnumber> = itemnumber
1914 C<$branchcode> = localisation of issue
1916 sub CheckValidDatedue{
1917 my ($date_due,$itemnumber,$branchcode)=@_;
1918 my @datedue=split('-',$date_due);
1919 my $years=$datedue[0];
1920 my $month=$datedue[1];
1921 my $day=$datedue[2];
1923 for (my $i=0;$i<2;$i++){
1924 $dow=Day_of_Week($years,$month,$day);
1925 ($dow=0) if ($dow>6);
1926 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
1927 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1928 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1929 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
1931 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
1934 my $newdatedue=$years."-".$month."-".$day;
1937 =head2 CheckRepeatableHolidays
1939 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
1940 this function check if the date due is a repeatable holiday
1941 C<$date_due> = returndate calculate with no day check
1942 C<$itemnumber> = itemnumber
1943 C<$branchcode> = localisation of issue
1947 sub CheckRepeatableHolidays{
1948 my($itemnumber,$week_day,$branchcode)=@_;
1949 my $dbh = C4::Context->dbh;
1950 my $query = qq|SELECT count(*)
1951 FROM repeatable_holidays
1954 my $sth = $dbh->prepare($query);
1955 $sth->execute($branchcode,$week_day);
1956 my $result=$sth->fetchrow;
1962 =head2 CheckSpecialHolidays
1964 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1965 this function check if the date is a special holiday
1966 C<$years> = the years of datedue
1967 C<$month> = the month of datedue
1968 C<$day> = the day of datedue
1969 C<$itemnumber> = itemnumber
1970 C<$branchcode> = localisation of issue
1972 sub CheckSpecialHolidays{
1973 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
1974 my $dbh = C4::Context->dbh;
1975 my $query=qq|SELECT count(*)
1976 FROM `special_holidays`
1982 my $sth = $dbh->prepare($query);
1983 $sth->execute($years,$month,$day,$branchcode);
1984 my $countspecial=$sth->fetchrow ;
1986 return $countspecial;
1989 =head2 CheckRepeatableSpecialHolidays
1991 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1992 this function check if the date is a repeatble special holidays
1993 C<$month> = the month of datedue
1994 C<$day> = the day of datedue
1995 C<$itemnumber> = itemnumber
1996 C<$branchcode> = localisation of issue
1998 sub CheckRepeatableSpecialHolidays{
1999 my ($month,$day,$itemnumber,$branchcode) = @_;
2000 my $dbh = C4::Context->dbh;
2001 my $query=qq|SELECT count(*)
2002 FROM `repeatable_holidays`
2007 my $sth = $dbh->prepare($query);
2008 $sth->execute($month,$day,$branchcode);
2009 my $countspecial=$sth->fetchrow ;
2011 return $countspecial;
2016 sub CheckValidBarcode{
2018 my $dbh = C4::Context->dbh;
2019 my $query=qq|SELECT count(*)
2023 my $sth = $dbh->prepare($query);
2024 $sth->execute($barcode);
2025 my $exist=$sth->fetchrow ;
2036 Koha Developement team <info@koha.org>