1 package C4::Circulation;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
39 use POSIX qw(strftime);
40 use C4::Branch; # GetBranches
41 use C4::Log; # logaction
43 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,%EXPORT_TAGS);
45 # set the version for version checking
50 C4::Circulation - Koha circulation module
58 The functions in this module deal with circulation, issues, and
59 returns, as well as general information about the library.
60 Also deals with stocktaking.
68 # FIXME subs that should probably be elsewhere
74 # subs to deal with issuing a book
85 &AnonymiseIssueHistory
87 # subs to deal with returns
92 # subs to deal with transfers
101 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
102 # 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 ?
106 =head3 $str = &decode($chunk);
110 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
117 sub cuecatbarcodedecode {
120 my @fields = split( /\./, $barcode );
121 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
122 if ( $#results == 2 ) {
132 =head3 $str = &decode($chunk);
136 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
146 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
147 my @s = map { index( $seq, $_ ); } split( //, $encoded );
148 my $l = ( $#s + 1 ) % 4;
159 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
161 chr( ( $n >> 16 ) ^ 67 )
162 .chr( ( $n >> 8 & 255 ) ^ 67 )
163 .chr( ( $n & 255 ) ^ 67 );
166 $r = substr( $r, 0, length($r) - $l );
172 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
174 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
176 C<$newbranch> is the code for the branch to which the item should be transferred.
178 C<$barcode> is the barcode of the item to be transferred.
180 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
181 Otherwise, if an item is reserved, the transfer fails.
183 Returns three values:
187 is true if the transfer was successful.
191 is a reference-to-hash which may have any of the following keys:
197 There is no item in the catalog with the given barcode. The value is C<$barcode>.
201 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.
203 =item C<DestinationEqualsHolding>
205 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.
209 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.
213 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>.
215 =item C<WasTransferred>
217 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
224 my ( $tbr, $barcode, $ignoreRs ) = @_;
227 my $branches = GetBranches();
228 my $itemnumber = GetItemnumberFromBarcode( $barcode );
229 my $issue = GetItemIssue($itemnumber);
230 my $biblio = GetBiblioFromItemNumber($itemnumber);
233 if ( not $itemnumber ) {
234 $messages->{'BadBarcode'} = $barcode;
238 # get branches of book...
239 my $hbr = $biblio->{'homebranch'};
240 my $fbr = $biblio->{'holdingbranch'};
243 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
244 $messages->{'IsPermanent'} = $hbr;
247 # can't transfer book if is already there....
248 if ( $fbr eq $tbr ) {
249 $messages->{'DestinationEqualsHolding'} = 1;
253 # check if it is still issued to someone, return it...
254 if ($issue->{borrowernumber}) {
255 AddReturn( $barcode, $fbr );
256 $messages->{'WasReturned'} = $issue->{borrowernumber};
260 # That'll save a database query.
261 my ( $resfound, $resrec ) =
262 CheckReserves( $itemnumber );
263 if ( $resfound and not $ignoreRs ) {
264 $resrec->{'ResFound'} = $resfound;
266 # $messages->{'ResFound'} = $resrec;
270 #actually do the transfer....
272 ModItemTransfer( $itemnumber, $fbr, $tbr );
274 # don't need to update MARC anymore, we do it in batch now
275 $messages->{'WasTransfered'} = 1;
276 ModDateLastSeen( $itemnumber );
278 return ( $dotransfer, $messages, $biblio );
281 =head2 CanBookBeIssued
283 Check if a book can be issued.
285 my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($borrower,$barcode,$year,$month,$day);
289 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
291 =item C<$barcode> is the bar code of the book being issued.
293 =item C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
301 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
302 Possible values are :
308 sticky due date is invalid
312 borrower gone with no address
316 borrower declared it's card lost
322 =head3 UNKNOWN_BARCODE
336 item is restricted (set by ??)
338 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
339 Possible values are :
347 renewing, not issuing
349 =head3 ISSUED_TO_ANOTHER
351 issued to someone else.
355 reserved for someone else.
359 sticky due date is invalid
363 if the borrower borrows to much things
367 # check if a book can be issued.
371 my $borrower = shift;
372 my $biblionumber = shift;
374 my $cat_borrower = $borrower->{'categorycode'};
375 my $branch_borrower = $borrower->{'branchcode'};
376 my $dbh = C4::Context->dbh;
378 my $branch_issuer = C4::Context->userenv->{'branchcode'};
380 my $type = (C4::Context->preference('item-level_itype'))
381 ? $item->{'itype'} # item-level
382 : $item->{'itemtype'}; # biblio-level
386 'SELECT * FROM issuingrules
387 WHERE categorycode = ?
392 my $query2 = "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.biblioitemnumber = s2.biblioitemnumber"
397 . (C4::Context->preference('item-level_itype'))
399 : " AND s1.itemtype= ? ";
400 my $sth2= $dbh->prepare($query2);
403 'SELECT COUNT(*) FROM issues
404 WHERE borrowernumber = ?
405 AND returndate IS NULL'
409 # check the 3 parameters (branch / itemtype / category code
410 $sth->execute( $cat_borrower, $type, $branch_borrower );
411 my $result = $sth->fetchrow_hashref;
412 # warn "$cat_borrower, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
414 if ( $result->{maxissueqty} ne '' ) {
415 # warn "checking on everything set";
416 $sth2->execute( $borrower->{'borrowernumber'}, $type );
417 my $alreadyissued = $sth2->fetchrow;
418 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
419 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/itemtype failed)" );
421 # now checking for total
422 $sth->execute( $cat_borrower, '', $branch_borrower );
423 my $result = $sth->fetchrow_hashref;
424 if ( $result->{maxissueqty} ne '*' ) {
425 $sth2->execute( $borrower->{'borrowernumber'}, $type );
426 my $alreadyissued = $sth2->fetchrow;
427 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
428 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/total failed)" );
433 # check the 2 parameters (branch / itemtype / default categorycode
434 $sth->execute( '*', $type, $branch_borrower );
435 my $result = $sth->fetchrow_hashref;
436 # warn "*, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
438 if ( $result->{maxissueqty} ne '' ) {
439 # warn "checking on 2 parameters (default categorycode)";
440 $sth2->execute( $borrower->{'borrowernumber'}, $type );
441 my $alreadyissued = $sth2->fetchrow;
442 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
443 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / itemtype failed)" );
445 # now checking for total
446 $sth->execute( '*', '*', $branch_borrower );
447 my $result = $sth->fetchrow_hashref;
448 if ( $result->{maxissueqty} ne '' ) {
449 $sth2->execute( $borrower->{'borrowernumber'}, $type );
450 my $alreadyissued = $sth2->fetchrow;
451 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
452 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / total failed)" );
457 # check the 1 parameters (default branch / itemtype / categorycode
458 $sth->execute( $cat_borrower, $type, '*' );
459 my $result = $sth->fetchrow_hashref;
460 # warn "$cat_borrower, $type, * = ".Data::Dumper::Dumper($result);
462 if ( $result->{maxissueqty} ne '' ) {
463 # warn "checking on 1 parameter (default branch + categorycode)";
464 $sth2->execute( $borrower->{'borrowernumber'}, $type );
465 my $alreadyissued = $sth2->fetchrow;
466 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
467 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch/category/itemtype failed)" );
469 # now checking for total
470 $sth->execute( $cat_borrower, '*', '*' );
471 my $result = $sth->fetchrow_hashref;
472 if ( $result->{maxissueqty} ne '' ) {
473 $sth2->execute( $borrower->{'borrowernumber'}, $type );
474 my $alreadyissued = $sth2->fetchrow;
475 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
476 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / category / total failed)" );
481 # check the 0 parameters (default branch / itemtype / default categorycode
482 $sth->execute( '*', $type, '*' );
483 my $result = $sth->fetchrow_hashref;
484 # warn "*, $type, * = ".Data::Dumper::Dumper($result);
486 if ( $result->{maxissueqty} ne '' ) {
487 # warn "checking on default branch and default categorycode";
488 $sth2->execute( $borrower->{'borrowernumber'}, $type );
489 my $alreadyissued = $sth2->fetchrow;
490 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
491 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / itemtype failed)" );
493 # now checking for total
494 $sth->execute( '*', '*', '*' );
495 my $result = $sth->fetchrow_hashref;
496 if ( $result->{maxissueqty} ne '' ) {
497 $sth2->execute( $borrower->{'borrowernumber'}, $type );
498 my $alreadyissued = $sth2->fetchrow;
499 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
500 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / total failed)" );
505 #OK, the patron can issue !!!
511 @issues = &itemissues($biblioitemnumber, $biblio);
513 Looks up information about who has borrowed the bookZ<>(s) with the
514 given biblioitemnumber.
516 C<$biblio> is ignored.
518 C<&itemissues> returns an array of references-to-hash. The keys
519 include the fields from the C<items> table in the Koha database.
520 Additional keys include:
526 If the item is currently on loan, this gives the due date.
528 If the item is not on loan, then this is either "Available" or
529 "Cancelled", if the item has been withdrawn.
533 If the item is currently on loan, this gives the card number of the
534 patron who currently has the item.
536 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
538 These give the timestamp for the last three times the item was
541 =item C<card0>, C<card1>, C<card2>
543 The card number of the last three patrons who borrowed this item.
545 =item C<borrower0>, C<borrower1>, C<borrower2>
547 The borrower number of the last three patrons who borrowed this item.
555 my ( $bibitem, $biblio ) = @_;
556 my $dbh = C4::Context->dbh;
558 # FIXME - If this function die()s, the script will abort, and the
559 # user won't get anything; depending on how far the script has
560 # gotten, the user might get a blank page. It would be much better
561 # to at least print an error message. The easiest way to do this
562 # is to set $SIG{__DIE__}.
564 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
569 $sth->execute($bibitem) || die $sth->errstr;
571 while ( my $data = $sth->fetchrow_hashref ) {
573 # Find out who currently has this item.
574 # FIXME - Wouldn't it be better to do this as a left join of
575 # some sort? Currently, this code assumes that if
576 # fetchrow_hashref() fails, then the book is on the shelf.
577 # fetchrow_hashref() can fail for any number of reasons (e.g.,
578 # database server crash), not just because no items match the
580 my $sth2 = $dbh->prepare(
581 "SELECT * FROM issues
582 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
584 AND returndate IS NULL
588 $sth2->execute( $data->{'itemnumber'} );
589 if ( my $data2 = $sth2->fetchrow_hashref ) {
590 $data->{'date_due'} = $data2->{'date_due'};
591 $data->{'card'} = $data2->{'cardnumber'};
592 $data->{'borrower'} = $data2->{'borrowernumber'};
595 if ( $data->{'wthdrawn'} eq '1' ) {
596 $data->{'date_due'} = 'Cancelled';
599 $data->{'date_due'} = 'Available';
605 # Find the last 3 people who borrowed this item.
606 $sth2 = $dbh->prepare(
607 "SELECT * FROM issues
608 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
610 AND returndate IS NOT NULL
611 ORDER BY returndate DESC,timestamp DESC"
614 $sth2->execute( $data->{'itemnumber'} );
615 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
616 { # FIXME : error if there is less than 3 pple borrowing this item
617 if ( my $data2 = $sth2->fetchrow_hashref ) {
618 $data->{"timestamp$i2"} = $data2->{'timestamp'};
619 $data->{"card$i2"} = $data2->{'cardnumber'};
620 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
625 $results[$i] = $data;
633 =head2 CanBookBeIssued
635 $issuingimpossible, $needsconfirmation =
636 CanBookBeIssued( $borrower, $barcode, $year, $month, $day, $inprocess );
638 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
642 sub CanBookBeIssued {
643 my ( $borrower, $barcode, $year, $month, $day, $inprocess ) = @_;
644 my %needsconfirmation; # filled with problems that needs confirmations
645 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
646 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
647 my $issue = GetItemIssue($item->{itemnumber});
648 my $dbh = C4::Context->dbh;
653 my ( $duedate, $invalidduedate ) = fixdate( $year, $month, $day );
654 $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
659 if ( $borrower->{flags}->{GNA} ) {
660 $issuingimpossible{GNA} = 1;
662 if ( $borrower->{flags}->{'LOST'} ) {
663 $issuingimpossible{CARD_LOST} = 1;
665 if ( $borrower->{flags}->{'DBARRED'} ) {
666 $issuingimpossible{DEBARRED} = 1;
668 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
669 $issuingimpossible{EXPIRED} = 1;
671 my @expirydate= split /-/,$borrower->{'dateexpiry'};
672 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
673 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
674 $issuingimpossible{EXPIRED} = 1;
683 GetMemberAccountRecords( $borrower->{'borrowernumber'}, $duedate );
684 if ( C4::Context->preference("IssuingInProcess") ) {
685 my $amountlimit = C4::Context->preference("noissuescharge");
686 if ( $amount > $amountlimit && !$inprocess ) {
687 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
689 elsif ( $amount <= $amountlimit && !$inprocess ) {
690 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
695 $needsconfirmation{DEBT} = $amount;
700 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
703 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
704 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
709 unless ( $item->{barcode} ) {
710 $issuingimpossible{UNKNOWN_BARCODE} = 1;
712 if ( $item->{'notforloan'}
713 && $item->{'notforloan'} > 0 )
715 $issuingimpossible{NOT_FOR_LOAN} = 1;
717 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
719 $issuingimpossible{WTHDRAWN} = 1;
721 if ( $item->{'restricted'}
722 && $item->{'restricted'} == 1 )
724 $issuingimpossible{RESTRICTED} = 1;
726 if ( C4::Context->preference("IndependantBranches") ) {
727 my $userenv = C4::Context->userenv;
728 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
729 $issuingimpossible{NOTSAMEBRANCH} = 1
730 if ( $item->{'holdingbranch'} ne $userenv->{branch} );
735 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
737 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
740 # Already issued to current borrower. Ask whether the loan should
742 my ($CanBookBeRenewed) = CanBookBeRenewed(
743 $borrower->{'borrowernumber'},
744 $item->{'itemnumber'}
746 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
747 $issuingimpossible{NO_MORE_RENEWALS} = 1;
750 $needsconfirmation{RENEW_ISSUE} = 1;
753 elsif ($issue->{borrowernumber}) {
755 # issued to someone else
756 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
758 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
759 $needsconfirmation{ISSUED_TO_ANOTHER} =
760 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
763 # See if the item is on reserve.
764 my ( $restype, $res ) = CheckReserves( $item->{'itemnumber'} );
766 my $resbor = $res->{'borrowernumber'};
767 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
770 # The item is on reserve and waiting, but has been
771 # reserved by some other patron.
772 my ( $resborrower, $flags ) =
773 GetMemberDetails( $resbor, 0 );
774 my $branches = GetBranches();
776 $branches->{ $res->{'branchcode'} }->{'branchname'};
777 $needsconfirmation{RESERVE_WAITING} =
778 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
780 # CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'}); Doesn't belong in a checking subroutine.
782 elsif ( $restype eq "Reserved" ) {
784 # The item is on reserve for someone else.
785 my ( $resborrower, $flags ) =
786 GetMemberDetails( $resbor, 0 );
787 my $branches = GetBranches();
789 $branches->{ $res->{'branchcode'} }->{'branchname'};
790 $needsconfirmation{RESERVED} =
791 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
794 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
795 if ( $borrower->{'categorycode'} eq 'W' ) {
796 my %issuingimpossible;
797 return ( \%issuingimpossible, \%needsconfirmation );
799 return ( \%issuingimpossible, \%needsconfirmation );
802 return ( \%issuingimpossible, \%needsconfirmation );
808 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
810 &AddIssue($borrower,$barcode,$date)
814 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
816 =item C<$barcode> is the bar code of the book being issued.
818 =item C<$date> contains the max date of return. calculated if empty.
820 AddIssue does the following things :
821 - step 01: check that there is a borrowernumber & a barcode provided
822 - check for RENEWAL (book issued & being issued to the same patron)
823 - renewal YES = Calculate Charge & renew
825 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
827 - fill reserve if reserve to this patron
828 - cancel reserve or not, otherwise
829 * TRANSFERT PENDING ?
830 - complete the transfert
838 my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
839 my $dbh = C4::Context->dbh;
840 my $barcodecheck=CheckValidBarcode($barcode);
841 if ($borrower and $barcode and $barcodecheck ne '0'){
842 # my ($borrower, $flags) = &GetMemberDetails($borrowernumber, 0);
843 # find which item we issue
844 my $item = GetItem('', $barcode);
846 # get actual issuing if there is one
847 my $actualissue = GetItemIssue( $item->{itemnumber});
849 # get biblioinformation for this item
850 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
853 # check if we just renew the issue.
855 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
856 # we renew, do we need to add some charge ?
857 my ( $charge, $itemtype ) = GetIssuingCharges(
858 $item->{'itemnumber'},
859 $borrower->{'borrowernumber'}
863 $item->{'itemnumber'},
864 $borrower->{'borrowernumber'}, $charge
866 $item->{'charge'} = $charge;
869 C4::Context->userenv->{'branch'},
871 '', $item->{'itemnumber'},
872 $biblio->{'itemtype'}, $borrower->{'borrowernumber'}
875 $borrower->{'borrowernumber'},
876 $item->{'itemnumber'}
879 else {# it's NOT a renewal
880 if ( $actualissue->{borrowernumber}) {
881 # This book is currently on loan, but not to the person
882 # who wants to borrow it now. mark it returned before issuing to the new borrower
885 C4::Context->userenv->{'branch'}
889 # See if the item is on reserve.
890 my ( $restype, $res ) =
891 CheckReserves( $item->{'itemnumber'} );
893 my $resbor = $res->{'borrowernumber'};
894 if ( $resbor eq $borrower->{'borrowernumber'} ) {
896 # The item is reserved by the current patron
897 ModReserveFill($res);
899 elsif ( $restype eq "Waiting" ) {
902 # The item is on reserve and waiting, but has been
903 # reserved by some other patron.
904 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
905 my $branches = GetBranches();
907 $branches->{ $res->{'branchcode'} }->{'branchname'};
909 elsif ( $restype eq "Reserved" ) {
912 # The item is reserved by someone else.
913 my ( $resborrower, $flags ) =
914 GetMemberDetails( $resbor, 0 );
915 my $branches = GetBranches();
917 $branches->{ $res->{'branchcode'} }->{'branchname'};
918 if ($cancelreserve) { # cancel reserves on this item
919 CancelReserve( 0, $res->{'itemnumber'},
920 $res->{'borrowernumber'} );
923 if ($cancelreserve) {
924 CancelReserve( $res->{'biblionumber'}, 0,
925 $res->{'borrowernumber'} );
928 # set waiting reserve to first in reserve queue as book isn't waiting now
931 $res->{'biblionumber'},
932 $res->{'borrowernumber'},
938 # Starting process for transfer job (checking transfert and validate it if we have one)
939 my ($datesent) = GetTransfers($item->{'itemnumber'});
941 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
944 "UPDATE branchtransfers
945 SET datearrived = now(),
947 comments = 'Forced branchtransfert'
948 WHERE itemnumber= ? AND datearrived IS NULL"
950 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
954 # Record in the database the fact that the book was issued.
958 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
961 my $loanlength = GetLoanLength(
962 $borrower->{'categorycode'},
963 $biblio->{'itemtype'},
964 $borrower->{'branchcode'}
966 my $datedue = time + ($loanlength) * 86400;
967 my @datearr = localtime($datedue);
969 sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]);
973 $dateduef=CheckValidDatedue($dateduef,$item->{'itemnumber'},C4::Context->userenv->{'branch'});
974 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
975 if ( C4::Context->preference('ReturnBeforeExpiry')
976 && $dateduef gt $borrower->{dateexpiry} )
978 $dateduef = $borrower->{dateexpiry};
981 $borrower->{'borrowernumber'},
982 $item->{'itemnumber'},
983 strftime( "%Y-%m-%d", localtime ),$dateduef, C4::Context->userenv->{'branch'}
989 "UPDATE items SET issues=?, holdingbranch=?, itemlost=0, datelastborrowed = now() WHERE itemnumber=?");
992 C4::Context->userenv->{'branch'},
993 $item->{'itemnumber'}
996 &ModDateLastSeen( $item->{'itemnumber'} );
997 # If it costs to borrow this book, charge it to the patron's account.
998 my ( $charge, $itemtype ) = GetIssuingCharges(
999 $item->{'itemnumber'},
1000 $borrower->{'borrowernumber'}
1002 if ( $charge > 0 ) {
1004 $item->{'itemnumber'},
1005 $borrower->{'borrowernumber'}, $charge
1007 $item->{'charge'} = $charge;
1010 # Record the fact that this book was issued.
1012 C4::Context->userenv->{'branch'},
1014 '', $item->{'itemnumber'},
1015 $item->{'itemtype'}, $borrower->{'borrowernumber'}
1019 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'})
1020 if C4::Context->preference("IssueLog");
1024 =head2 GetLoanLength
1026 Get loan length for an itemtype, a borrower type and a branch
1028 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1033 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1034 my $dbh = C4::Context->dbh;
1037 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1040 # try to find issuelength & return the 1st available.
1041 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1042 $sth->execute( $borrowertype, $itemtype, $branchcode );
1043 my $loanlength = $sth->fetchrow_hashref;
1044 return $loanlength->{issuelength}
1045 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1047 $sth->execute( $borrowertype, $itemtype, "" );
1048 $loanlength = $sth->fetchrow_hashref;
1049 return $loanlength->{issuelength}
1050 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1052 $sth->execute( $borrowertype, "*", $branchcode );
1053 $loanlength = $sth->fetchrow_hashref;
1054 return $loanlength->{issuelength}
1055 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1057 $sth->execute( "*", $itemtype, $branchcode );
1058 $loanlength = $sth->fetchrow_hashref;
1059 return $loanlength->{issuelength}
1060 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1062 $sth->execute( $borrowertype, "*", "" );
1063 $loanlength = $sth->fetchrow_hashref;
1064 return $loanlength->{issuelength}
1065 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1067 $sth->execute( "*", "*", $branchcode );
1068 $loanlength = $sth->fetchrow_hashref;
1069 return $loanlength->{issuelength}
1070 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1072 $sth->execute( "*", $itemtype, "" );
1073 $loanlength = $sth->fetchrow_hashref;
1074 return $loanlength->{issuelength}
1075 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1077 $sth->execute( "*", "*", "" );
1078 $loanlength = $sth->fetchrow_hashref;
1079 return $loanlength->{issuelength}
1080 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1082 # if no rule is set => 21 days (hardcoded)
1088 ($doreturn, $messages, $iteminformation, $borrower) =
1089 &AddReturn($barcode, $branch);
1093 C<$barcode> is the bar code of the book being returned. C<$branch> is
1094 the code of the branch where the book is being returned.
1096 C<&AddReturn> returns a list of four items:
1098 C<$doreturn> is true iff the return succeeded.
1100 C<$messages> is a reference-to-hash giving the reason for failure:
1106 No item with this barcode exists. The value is C<$barcode>.
1110 The book is not currently on loan. The value is C<$barcode>.
1112 =item C<IsPermanent>
1114 The book's home branch is a permanent collection. If you have borrowed
1115 this book, you are not allowed to return it. The value is the code for
1116 the book's home branch.
1120 This book has been withdrawn/cancelled. The value should be ignored.
1124 The item was reserved. The value is a reference-to-hash whose keys are
1125 fields from the reserves table of the Koha database, and
1126 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1127 either C<Waiting>, C<Reserved>, or 0.
1131 C<$borrower> is a reference-to-hash, giving information about the
1132 patron who last borrowed the book.
1137 my ( $barcode, $branch ) = @_;
1138 my $dbh = C4::Context->dbh;
1142 my $validTransfert = 0;
1143 my $reserveDone = 0;
1145 # get information on item
1146 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1147 unless ($iteminformation->{'itemnumber'} ) {
1148 $messages->{'BadBarcode'} = $barcode;
1152 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1153 $messages->{'NotIssued'} = $barcode;
1157 # check if the book is in a permanent collection....
1158 my $hbr = $iteminformation->{'homebranch'};
1159 my $branches = GetBranches();
1160 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1161 $messages->{'IsPermanent'} = $hbr;
1164 # check that the book has been cancelled
1165 if ( $iteminformation->{'wthdrawn'} ) {
1166 $messages->{'wthdrawn'} = 1;
1170 # new op dev : if the book returned in an other branch update the holding branch
1172 # update issues, thereby returning book (should push this out into another subroutine
1173 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1175 # case of a return of document (deal with issues and holdingbranch)
1180 "UPDATE issues SET returndate = now() WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (returndate IS NULL)"
1182 $sth->execute( $borrower->{'borrowernumber'},
1183 $iteminformation->{'itemnumber'} );
1184 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1187 # continue to deal with returns cases, but not only if we have an issue
1189 # the holdingbranch is updated if the document is returned in an other location .
1190 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} )
1192 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1193 # reload iteminformation holdingbranch with the userenv value
1194 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1196 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1197 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1199 # fix up the accounts.....
1200 if ( $iteminformation->{'itemlost'} ) {
1201 $messages->{'WasLost'} = 1;
1204 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1205 # check if we have a transfer for this document
1206 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1208 # if we have a transfer to do, we update the line of transfers with the datearrived
1210 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1213 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1215 $sth->execute( $iteminformation->{'itemnumber'} );
1217 # 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'
1218 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1221 $messages->{'WrongTransfer'} = $tobranch;
1222 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1224 $validTransfert = 1;
1227 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1228 # fix up the accounts.....
1229 if ($iteminformation->{'itemlost'}) {
1230 FixAccountForLostAndReturned($iteminformation, $borrower);
1231 $messages->{'WasLost'} = 1;
1233 # fix up the overdues in accounts...
1234 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1235 $iteminformation->{'itemnumber'} );
1237 # find reserves.....
1238 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1239 my ( $resfound, $resrec ) =
1240 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1242 $resrec->{'ResFound'} = $resfound;
1243 $messages->{'ResFound'} = $resrec;
1248 # Record the fact that this book was returned.
1250 $branch, 'return', '0', '',
1251 $iteminformation->{'itemnumber'},
1252 $iteminformation->{'itemtype'},
1253 $borrower->{'borrowernumber'}
1256 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'})
1257 if C4::Context->preference("ReturnLog");
1259 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1260 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1262 if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1263 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1264 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1265 $messages->{'WasTransfered'} = 1;
1266 warn "was transfered";
1270 return ( $doreturn, $messages, $iteminformation, $borrower );
1273 =head2 FixOverduesOnReturn
1275 &FixOverduesOnReturn($brn,$itm);
1277 C<$brn> borrowernumber
1281 internal function, called only by AddReturn
1285 sub FixOverduesOnReturn {
1286 my ( $borrowernumber, $item ) = @_;
1287 my $dbh = C4::Context->dbh;
1289 # check for overdue fine
1292 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1294 $sth->execute( $borrowernumber, $item );
1296 # alter fine to show that the book has been returned
1297 if ( my $data = $sth->fetchrow_hashref ) {
1300 "UPDATE accountlines SET accounttype='F' WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accountno = ?)"
1302 $usth->execute( $borrowernumber, $item, $data->{'accountno'} );
1309 =head2 FixAccountForLostAndReturned
1311 &FixAccountForLostAndReturned($iteminfo,$borrower);
1313 Calculates the charge for a book lost and returned (Not exported & used only once)
1315 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1317 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1319 Internal function, called by AddReturn
1323 sub FixAccountForLostAndReturned {
1324 my ($iteminfo, $borrower) = @_;
1326 my $dbh = C4::Context->dbh;
1327 my $itm = $iteminfo->{'itemnumber'};
1328 # check for charge made for lost book
1329 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1330 $sth->execute($itm);
1331 if (my $data = $sth->fetchrow_hashref) {
1332 # writeoff this amount
1334 my $amount = $data->{'amount'};
1335 my $acctno = $data->{'accountno'};
1337 if ($data->{'amountoutstanding'} == $amount) {
1338 $offset = $data->{'amount'};
1341 $offset = $amount - $data->{'amountoutstanding'};
1342 $amountleft = $data->{'amountoutstanding'} - $amount;
1344 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1345 WHERE (borrowernumber = ?)
1346 AND (itemnumber = ?) AND (accountno = ?) ");
1347 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1349 #check if any credit is left if so writeoff other accounts
1350 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1351 if ($amountleft < 0){
1354 if ($amountleft > 0){
1355 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1356 AND (amountoutstanding >0) ORDER BY date");
1357 $msth->execute($data->{'borrowernumber'});
1358 # offset transactions
1361 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1362 if ($accdata->{'amountoutstanding'} < $amountleft) {
1364 $amountleft -= $accdata->{'amountoutstanding'};
1366 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1369 my $thisacct = $accdata->{'accountno'};
1370 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1371 WHERE (borrowernumber = ?)
1372 AND (accountno=?)");
1373 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1375 $usth = $dbh->prepare("INSERT INTO accountoffsets
1376 (borrowernumber, accountno, offsetaccount, offsetamount)
1379 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1384 if ($amountleft > 0){
1387 my $desc="Book Returned ".$iteminfo->{'barcode'};
1388 $usth = $dbh->prepare("INSERT INTO accountlines
1389 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1390 VALUES (?,?,now(),?,?,'CR',?)");
1391 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1393 $usth = $dbh->prepare("INSERT INTO accountoffsets
1394 (borrowernumber, accountno, offsetaccount, offsetamount)
1396 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1398 $usth = $dbh->prepare("UPDATE items SET paidfor='' WHERE itemnumber=?");
1399 $usth->execute($itm);
1408 $issues = &GetItemIssue($itemnumber);
1410 Returns patrons currently having a book. nothing if item is not issued atm
1412 C<$itemnumber> is the itemnumber
1414 Returns an array of hashes
1418 my ( $itemnumber) = @_;
1419 return unless $itemnumber;
1420 my $dbh = C4::Context->dbh;
1424 my $today = POSIX::strftime("%Y%m%d", localtime);
1426 my $sth = $dbh->prepare(
1427 "SELECT * FROM issues
1428 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1430 issues.itemnumber=? AND returndate IS NULL ");
1431 $sth->execute($itemnumber);
1432 my $data = $sth->fetchrow_hashref;
1433 my $datedue = $data->{'date_due'};
1435 if ( $datedue < $today ) {
1436 $data->{'overdue'} = 1;
1438 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1443 =head2 GetItemIssues
1445 $issues = &GetItemIssues($itemnumber, $history);
1447 Returns patrons that have issued a book
1449 C<$itemnumber> is the itemnumber
1450 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1452 Returns an array of hashes
1456 my ( $itemnumber,$history ) = @_;
1457 my $dbh = C4::Context->dbh;
1461 my $today = POSIX::strftime("%Y%m%d", localtime);
1463 my $sth = $dbh->prepare(
1464 "SELECT * FROM issues
1465 LEFT JOIN borrowers ON borrowers.borrowernumber
1466 LEFT JOIN items ON items.itemnumber=issues.itemnumber
1468 issues.itemnumber=?".($history?"":" AND returndate IS NULL ").
1469 "ORDER BY issues.date_due DESC"
1471 $sth->execute($itemnumber);
1472 while ( my $data = $sth->fetchrow_hashref ) {
1473 my $datedue = $data->{'date_due'};
1475 if ( $datedue < $today ) {
1476 $data->{'overdue'} = 1;
1478 my $itemnumber = $data->{'itemnumber'};
1479 push @GetItemIssues, $data;
1482 return ( \@GetItemIssues );
1485 =head2 GetBiblioIssues
1487 $issues = GetBiblioIssues($biblionumber);
1489 this function get all issues from a biblionumber.
1492 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1493 tables issues and the firstname,surname & cardnumber from borrowers.
1497 sub GetBiblioIssues {
1498 my $biblionumber = shift;
1499 return undef unless $biblionumber;
1500 my $dbh = C4::Context->dbh;
1502 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1504 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1505 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1506 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1507 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1508 WHERE biblio.biblionumber = ?
1509 ORDER BY issues.timestamp
1511 my $sth = $dbh->prepare($query);
1512 $sth->execute($biblionumber);
1515 while ( my $data = $sth->fetchrow_hashref ) {
1516 push @issues, $data;
1521 =head2 CanBookBeRenewed
1523 $ok = &CanBookBeRenewed($borrowernumber, $itemnumber);
1525 Find out whether a borrowed item may be renewed.
1527 C<$dbh> is a DBI handle to the Koha database.
1529 C<$borrowernumber> is the borrower number of the patron who currently
1530 has the item on loan.
1532 C<$itemnumber> is the number of the item to renew.
1534 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1535 item must currently be on loan to the specified borrower; renewals
1536 must be allowed for the item's type; and the borrower must not have
1537 already renewed the loan.
1541 sub CanBookBeRenewed {
1543 # check renewal status
1544 my ( $borrowernumber, $itemnumber ) = @_;
1545 my $dbh = C4::Context->dbh;
1549 # Look in the issues table for this item, lent to this borrower,
1550 # and not yet returned.
1552 # FIXME - I think this function could be redone to use only one SQL call.
1553 my $sth1 = $dbh->prepare(
1554 "SELECT * FROM issues
1555 WHERE borrowernumber = ?
1557 AND returndate IS NULL"
1559 $sth1->execute( $borrowernumber, $itemnumber );
1560 if ( my $data1 = $sth1->fetchrow_hashref ) {
1562 # Found a matching item
1564 # See if this item may be renewed. This query is convoluted
1565 # because it's a bit messy: given the item number, we need to find
1566 # the biblioitem, which gives us the itemtype, which tells us
1567 # whether it may be renewed.
1568 my $sth2 = $dbh->prepare(
1569 "SELECT renewalsallowed FROM items
1570 LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1571 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1572 WHERE items.itemnumber = ?
1575 $sth2->execute($itemnumber);
1576 if ( my $data2 = $sth2->fetchrow_hashref ) {
1577 $renews = $data2->{'renewalsallowed'};
1579 if ( $renews && $renews >= $data1->{'renewals'} ) {
1583 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1590 return ($renewokay);
1595 &AddRenewal($borrowernumber, $itemnumber, $datedue);
1599 C<$borrowernumber> is the borrower number of the patron who currently
1602 C<$itemnumber> is the number of the item to renew.
1604 C<$datedue> can be used to set the due date. If C<$datedue> is the
1605 empty string, C<&AddRenewal> will calculate the due date automatically
1606 from the book's item type. If you wish to set the due date manually,
1607 C<$datedue> should be in the form YYYY-MM-DD.
1613 my ( $borrowernumber, $itemnumber, $branch ,$datedue ) = @_;
1614 my $dbh = C4::Context->dbh;
1616 # If the due date wasn't specified, calculate it by adding the
1617 # book's loan length to today's date.
1618 if ( $datedue eq "" ) {
1620 my $biblio = GetBiblioFromItemNumber($itemnumber);
1621 my $borrower = GetMemberDetails( $borrowernumber, 0 );
1622 my $loanlength = GetLoanLength(
1623 $borrower->{'categorycode'},
1624 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1625 $borrower->{'branchcode'}
1627 #FIXME -- choose issuer or borrower branch.
1628 #FIXME -- where's the calendar ?
1629 my ( $due_year, $due_month, $due_day ) =
1630 Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
1631 $datedue = "$due_year-$due_month-$due_day";
1632 $datedue=CheckValidDatedue($datedue,$itemnumber,$branch);
1635 # Find the issues record for this book
1637 $dbh->prepare("SELECT * FROM issues
1638 WHERE borrowernumber=?
1640 AND returndate IS NULL"
1642 $sth->execute( $borrowernumber, $itemnumber );
1643 my $issuedata = $sth->fetchrow_hashref;
1646 # Update the issues record to have the new due date, and a new count
1647 # of how many times it has been renewed.
1648 my $renews = $issuedata->{'renewals'} + 1;
1649 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1650 WHERE borrowernumber=?
1652 AND returndate IS NULL"
1654 $sth->execute( $datedue, $renews, $borrowernumber, $itemnumber );
1658 UpdateStats( C4::Context->userenv->{'branchcode'}, 'renew', '', '', $itemnumber );
1660 # Charge a new rental fee, if applicable?
1661 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1662 if ( $charge > 0 ) {
1663 my $accountno = getnextacctno( $borrowernumber );
1664 my $item = GetBiblioFromItemNumber($itemnumber);
1665 $sth = $dbh->prepare(
1666 "INSERT INTO accountlines
1667 (borrowernumber,accountno,date,amount,
1668 description,accounttype,amountoutstanding,
1670 VALUES (?,?,now(),?,?,?,?,?)"
1672 $sth->execute( $borrowernumber, $accountno, $charge,
1673 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1674 'Rent', $charge, $itemnumber );
1679 =head2 GetIssuingCharges
1681 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1683 Calculate how much it would cost for a given patron to borrow a given
1684 item, including any applicable discounts.
1686 C<$itemnumber> is the item number of item the patron wishes to borrow.
1688 C<$borrowernumber> is the patron's borrower number.
1690 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1691 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1696 sub GetIssuingCharges {
1698 # calculate charges due
1699 my ( $itemnumber, $borrowernumber ) = @_;
1701 my $dbh = C4::Context->dbh;
1704 # Get the book's item type and rental charge (via its biblioitem).
1705 my $sth1 = $dbh->prepare(
1706 "SELECT itemtypes.itemtype,rentalcharge FROM items
1707 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1708 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1709 WHERE items.itemnumber =?
1712 $sth1->execute($itemnumber);
1713 if ( my $data1 = $sth1->fetchrow_hashref ) {
1714 $item_type = $data1->{'itemtype'};
1715 $charge = $data1->{'rentalcharge'};
1716 my $q2 = "SELECT rentaldiscount FROM borrowers
1717 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1718 WHERE borrowers.borrowernumber = ?
1719 AND issuingrules.itemtype = ?";
1720 my $sth2 = $dbh->prepare($q2);
1721 $sth2->execute( $borrowernumber, $item_type );
1722 if ( my $data2 = $sth2->fetchrow_hashref ) {
1723 my $discount = $data2->{'rentaldiscount'};
1724 if ( $discount eq 'NULL' ) {
1727 $charge = ( $charge * ( 100 - $discount ) ) / 100;
1733 return ( $charge, $item_type );
1736 =head2 AddIssuingCharge
1738 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1742 sub AddIssuingCharge {
1743 my ( $itemnumber, $borrowernumber, $charge ) = @_;
1744 my $dbh = C4::Context->dbh;
1745 my $nextaccntno = getnextacctno( $borrowernumber );
1747 INSERT INTO accountlines
1748 (borrowernumber, itemnumber, accountno,
1749 date, amount, description, accounttype,
1751 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1753 my $sth = $dbh->prepare($query);
1754 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1760 GetTransfers($itemnumber);
1765 my ($itemnumber) = @_;
1767 my $dbh = C4::Context->dbh;
1773 FROM branchtransfers
1774 WHERE itemnumber = ?
1775 AND datearrived IS NULL
1777 my $sth = $dbh->prepare($query);
1778 $sth->execute($itemnumber);
1779 my @row = $sth->fetchrow_array();
1785 =head2 GetTransfersFromTo
1787 @results = GetTransfersFromTo($frombranch,$tobranch);
1789 Returns the list of pending transfers between $from and $to branch
1793 sub GetTransfersFromTo {
1794 my ( $frombranch, $tobranch ) = @_;
1795 return unless ( $frombranch && $tobranch );
1796 my $dbh = C4::Context->dbh;
1798 SELECT itemnumber,datesent,frombranch
1799 FROM branchtransfers
1802 AND datearrived IS NULL
1804 my $sth = $dbh->prepare($query);
1805 $sth->execute( $frombranch, $tobranch );
1808 while ( my $data = $sth->fetchrow_hashref ) {
1809 push @gettransfers, $data;
1812 return (@gettransfers);
1815 =head2 DeleteTransfer
1817 &DeleteTransfer($itemnumber);
1821 sub DeleteTransfer {
1822 my ($itemnumber) = @_;
1823 my $dbh = C4::Context->dbh;
1824 my $sth = $dbh->prepare(
1825 "DELETE FROM branchtransfers
1827 AND datearrived IS NULL "
1829 $sth->execute($itemnumber);
1833 =head2 AnonymiseIssueHistory
1835 $rows = AnonymiseIssueHistory($borrowernumber,$date)
1837 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
1838 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
1840 return the number of affected rows.
1844 sub AnonymiseIssueHistory {
1846 my $borrowernumber = shift;
1847 my $dbh = C4::Context->dbh;
1850 SET borrowernumber = NULL
1851 WHERE returndate < '".$date."'
1852 AND borrowernumber IS NOT NULL
1854 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
1855 my $rows_affected = $dbh->do($query);
1856 return $rows_affected;
1859 =head2 updateWrongTransfer
1861 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
1863 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
1867 sub updateWrongTransfer {
1868 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
1869 my $dbh = C4::Context->dbh;
1870 # first step validate the actual line of transfert .
1873 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
1875 $sth->execute($FromLibrary,$itemNumber);
1878 # second step create a new line of branchtransfer to the right location .
1879 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
1881 #third step changing holdingbranch of item
1882 UpdateHoldingbranch($FromLibrary,$itemNumber);
1885 =head2 UpdateHoldingbranch
1887 $items = UpdateHoldingbranch($branch,$itmenumber);
1888 Simple methode for updating hodlingbranch in items BDD line
1891 sub UpdateHoldingbranch {
1892 my ( $branch,$itmenumber ) = @_;
1893 my $dbh = C4::Context->dbh;
1894 # first step validate the actual line of transfert .
1897 "update items set holdingbranch = ? where itemnumber= ?"
1899 $sth->execute($branch,$itmenumber);
1904 =head2 CheckValidDatedue
1906 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
1907 this function return a new date due after checked if it's a repeatable or special holiday
1908 C<$date_due> = returndate calculate with no day check
1909 C<$itemnumber> = itemnumber
1910 C<$branchcode> = localisation of issue
1912 sub CheckValidDatedue{
1913 my ($date_due,$itemnumber,$branchcode)=@_;
1914 my @datedue=split('-',$date_due);
1915 my $years=$datedue[0];
1916 my $month=$datedue[1];
1917 my $day=$datedue[2];
1919 for (my $i=0;$i<2;$i++){
1920 $dow=Day_of_Week($years,$month,$day);
1921 ($dow=0) if ($dow>6);
1922 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
1923 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1924 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1925 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
1927 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
1930 my $newdatedue=$years."-".$month."-".$day;
1933 =head2 CheckRepeatableHolidays
1935 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
1936 this function check if the date due is a repeatable holiday
1937 C<$date_due> = returndate calculate with no day check
1938 C<$itemnumber> = itemnumber
1939 C<$branchcode> = localisation of issue
1943 sub CheckRepeatableHolidays{
1944 my($itemnumber,$week_day,$branchcode)=@_;
1945 my $dbh = C4::Context->dbh;
1946 my $query = qq|SELECT count(*)
1947 FROM repeatable_holidays
1950 my $sth = $dbh->prepare($query);
1951 $sth->execute($branchcode,$week_day);
1952 my $result=$sth->fetchrow;
1958 =head2 CheckSpecialHolidays
1960 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1961 this function check if the date is a special holiday
1962 C<$years> = the years of datedue
1963 C<$month> = the month of datedue
1964 C<$day> = the day of datedue
1965 C<$itemnumber> = itemnumber
1966 C<$branchcode> = localisation of issue
1968 sub CheckSpecialHolidays{
1969 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
1970 my $dbh = C4::Context->dbh;
1971 my $query=qq|SELECT count(*)
1972 FROM `special_holidays`
1978 my $sth = $dbh->prepare($query);
1979 $sth->execute($years,$month,$day,$branchcode);
1980 my $countspecial=$sth->fetchrow ;
1982 return $countspecial;
1985 =head2 CheckRepeatableSpecialHolidays
1987 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1988 this function check if the date is a repeatble special holidays
1989 C<$month> = the month of datedue
1990 C<$day> = the day of datedue
1991 C<$itemnumber> = itemnumber
1992 C<$branchcode> = localisation of issue
1994 sub CheckRepeatableSpecialHolidays{
1995 my ($month,$day,$itemnumber,$branchcode) = @_;
1996 my $dbh = C4::Context->dbh;
1997 my $query=qq|SELECT count(*)
1998 FROM `repeatable_holidays`
2003 my $sth = $dbh->prepare($query);
2004 $sth->execute($month,$day,$branchcode);
2005 my $countspecial=$sth->fetchrow ;
2007 return $countspecial;
2012 sub CheckValidBarcode{
2014 my $dbh = C4::Context->dbh;
2015 my $query=qq|SELECT count(*)
2019 my $sth = $dbh->prepare($query);
2020 $sth->execute($barcode);
2021 my $exist=$sth->fetchrow ;
2032 Koha Developement team <info@koha.org>