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 # why pass biblionumber when we already have the the biblio data in the item hash?
380 # $dbh->prepare('SELECT itemtype FROM biblioitems WHERE biblionumber = ?');
381 # $sth->execute($biblionumber);
382 # my $type = $sth->fetchrow;
384 my $type = (C4::Context->preference('item-level_itype'))
385 ? $item->{'itype'} # item-level
386 : $item->{'itemtype'}; # biblio-level
390 'SELECT * FROM issuingrules
391 WHERE categorycode = ?
396 my $query2 = "SELECT COUNT(*) FROM issues i, biblioitems s1, items s2
397 WHERE i.borrowernumber = ?
398 AND i.returndate IS NULL
399 AND i.itemnumber = s2.itemnumber
400 AND s1.biblioitemnumber = s2.biblioitemnumber"
401 . (C4::Context->preference('item-level_itype'))
403 : " AND s1.itemtype= ? ";
404 my $sth2= $dbh->prepare($query2);
407 'SELECT COUNT(*) FROM issues
408 WHERE borrowernumber = ?
409 AND returndate IS NULL'
413 # check the 3 parameters (branch / itemtype / category code
414 $sth->execute( $cat_borrower, $type, $branch_borrower );
415 my $result = $sth->fetchrow_hashref;
416 # warn "$cat_borrower, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
418 if ( $result->{maxissueqty} ne '' ) {
419 # warn "checking on everything set";
420 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
421 my $alreadyissued = $sth2->fetchrow;
422 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
423 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/itemtype failed)" );
425 # now checking for total
426 $sth->execute( $cat_borrower, '', $branch_borrower );
427 my $result = $sth->fetchrow_hashref;
428 if ( $result->{maxissueqty} ne '*' ) {
429 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
430 my $alreadyissued = $sth2->fetchrow;
431 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
432 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/total failed)" );
437 # check the 2 parameters (branch / itemtype / default categorycode
438 $sth->execute( '*', $type, $branch_borrower );
439 my $result = $sth->fetchrow_hashref;
440 # warn "*, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
442 if ( $result->{maxissueqty} ne '' ) {
443 # warn "checking on 2 parameters (default categorycode)";
444 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
445 my $alreadyissued = $sth2->fetchrow;
446 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
447 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / itemtype failed)" );
449 # now checking for total
450 $sth->execute( '*', '*', $branch_borrower );
451 my $result = $sth->fetchrow_hashref;
452 if ( $result->{maxissueqty} ne '' ) {
453 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
454 my $alreadyissued = $sth2->fetchrow;
455 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
456 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / total failed)" );
461 # check the 1 parameters (default branch / itemtype / categorycode
462 $sth->execute( $cat_borrower, $type, '*' );
463 my $result = $sth->fetchrow_hashref;
464 # warn "$cat_borrower, $type, * = ".Data::Dumper::Dumper($result);
466 if ( $result->{maxissueqty} ne '' ) {
467 # warn "checking on 1 parameter (default branch + categorycode)";
468 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
469 my $alreadyissued = $sth2->fetchrow;
470 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
471 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch/category/itemtype failed)" );
473 # now checking for total
474 $sth->execute( $cat_borrower, '*', '*' );
475 my $result = $sth->fetchrow_hashref;
476 if ( $result->{maxissueqty} ne '' ) {
477 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
478 my $alreadyissued = $sth2->fetchrow;
479 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
480 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / category / total failed)" );
485 # check the 0 parameters (default branch / itemtype / default categorycode
486 $sth->execute( '*', $type, '*' );
487 my $result = $sth->fetchrow_hashref;
488 # warn "*, $type, * = ".Data::Dumper::Dumper($result);
490 if ( $result->{maxissueqty} ne '' ) {
491 # warn "checking on default branch and default categorycode";
492 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
493 my $alreadyissued = $sth2->fetchrow;
494 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
495 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / itemtype failed)" );
497 # now checking for total
498 $sth->execute( '*', '*', '*' );
499 my $result = $sth->fetchrow_hashref;
500 if ( $result->{maxissueqty} ne '' ) {
501 $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
502 my $alreadyissued = $sth2->fetchrow;
503 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
504 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / total failed)" );
509 #OK, the patron can issue !!!
515 @issues = &itemissues($biblioitemnumber, $biblio);
517 Looks up information about who has borrowed the bookZ<>(s) with the
518 given biblioitemnumber.
520 C<$biblio> is ignored.
522 C<&itemissues> returns an array of references-to-hash. The keys
523 include the fields from the C<items> table in the Koha database.
524 Additional keys include:
530 If the item is currently on loan, this gives the due date.
532 If the item is not on loan, then this is either "Available" or
533 "Cancelled", if the item has been withdrawn.
537 If the item is currently on loan, this gives the card number of the
538 patron who currently has the item.
540 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
542 These give the timestamp for the last three times the item was
545 =item C<card0>, C<card1>, C<card2>
547 The card number of the last three patrons who borrowed this item.
549 =item C<borrower0>, C<borrower1>, C<borrower2>
551 The borrower number of the last three patrons who borrowed this item.
559 my ( $bibitem, $biblio ) = @_;
560 my $dbh = C4::Context->dbh;
562 # FIXME - If this function die()s, the script will abort, and the
563 # user won't get anything; depending on how far the script has
564 # gotten, the user might get a blank page. It would be much better
565 # to at least print an error message. The easiest way to do this
566 # is to set $SIG{__DIE__}.
568 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
573 $sth->execute($bibitem) || die $sth->errstr;
575 while ( my $data = $sth->fetchrow_hashref ) {
577 # Find out who currently has this item.
578 # FIXME - Wouldn't it be better to do this as a left join of
579 # some sort? Currently, this code assumes that if
580 # fetchrow_hashref() fails, then the book is on the shelf.
581 # fetchrow_hashref() can fail for any number of reasons (e.g.,
582 # database server crash), not just because no items match the
584 my $sth2 = $dbh->prepare(
585 "SELECT * FROM issues
586 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
588 AND returndate IS NULL
592 $sth2->execute( $data->{'itemnumber'} );
593 if ( my $data2 = $sth2->fetchrow_hashref ) {
594 $data->{'date_due'} = $data2->{'date_due'};
595 $data->{'card'} = $data2->{'cardnumber'};
596 $data->{'borrower'} = $data2->{'borrowernumber'};
599 if ( $data->{'wthdrawn'} eq '1' ) {
600 $data->{'date_due'} = 'Cancelled';
603 $data->{'date_due'} = 'Available';
609 # Find the last 3 people who borrowed this item.
610 $sth2 = $dbh->prepare(
611 "SELECT * FROM issues
612 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
614 AND returndate IS NOT NULL
615 ORDER BY returndate DESC,timestamp DESC"
618 # $sth2 = $dbh->prepare("
621 # LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
622 # WHERE itemnumber = ?
623 # AND returndate is not NULL
624 # ORDER BY returndate DESC,timestamp DESC
627 $sth2->execute( $data->{'itemnumber'} );
628 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
629 { # FIXME : error if there is less than 3 pple borrowing this item
630 if ( my $data2 = $sth2->fetchrow_hashref ) {
631 $data->{"timestamp$i2"} = $data2->{'timestamp'};
632 $data->{"card$i2"} = $data2->{'cardnumber'};
633 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
638 $results[$i] = $data;
646 =head2 CanBookBeIssued
648 $issuingimpossible, $needsconfirmation =
649 CanBookBeIssued( $borrower, $barcode, $year, $month, $day, $inprocess );
651 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
655 sub CanBookBeIssued {
656 my ( $borrower, $barcode, $year, $month, $day, $inprocess ) = @_;
657 my %needsconfirmation; # filled with problems that needs confirmations
658 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
659 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
660 my $issue = GetItemIssue($item->{itemnumber});
661 my $dbh = C4::Context->dbh;
666 my ( $duedate, $invalidduedate ) = fixdate( $year, $month, $day );
667 $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
672 if ( $borrower->{flags}->{GNA} ) {
673 $issuingimpossible{GNA} = 1;
675 if ( $borrower->{flags}->{'LOST'} ) {
676 $issuingimpossible{CARD_LOST} = 1;
678 if ( $borrower->{flags}->{'DBARRED'} ) {
679 $issuingimpossible{DEBARRED} = 1;
681 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
682 $issuingimpossible{EXPIRED} = 1;
684 my @expirydate= split /-/,$borrower->{'dateexpiry'};
685 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
686 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
687 $issuingimpossible{EXPIRED} = 1;
696 GetMemberAccountRecords( $borrower->{'borrowernumber'}, $duedate );
697 if ( C4::Context->preference("IssuingInProcess") ) {
698 my $amountlimit = C4::Context->preference("noissuescharge");
699 if ( $amount > $amountlimit && !$inprocess ) {
700 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
702 elsif ( $amount <= $amountlimit && !$inprocess ) {
703 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
708 $needsconfirmation{DEBT} = $amount;
713 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
715 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
716 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
721 unless ( $item->{barcode} ) {
722 $issuingimpossible{UNKNOWN_BARCODE} = 1;
724 if ( $item->{'notforloan'}
725 && $item->{'notforloan'} > 0 )
727 $issuingimpossible{NOT_FOR_LOAN} = 1;
729 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
731 $issuingimpossible{WTHDRAWN} = 1;
733 if ( $item->{'restricted'}
734 && $item->{'restricted'} == 1 )
736 $issuingimpossible{RESTRICTED} = 1;
738 if ( C4::Context->preference("IndependantBranches") ) {
739 my $userenv = C4::Context->userenv;
740 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
741 $issuingimpossible{NOTSAMEBRANCH} = 1
742 if ( $item->{'holdingbranch'} ne $userenv->{branch} );
747 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
749 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
752 # Already issued to current borrower. Ask whether the loan should
754 my ($CanBookBeRenewed) = CanBookBeRenewed(
755 $borrower->{'borrowernumber'},
756 $item->{'itemnumber'}
758 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
759 $issuingimpossible{NO_MORE_RENEWALS} = 1;
762 $needsconfirmation{RENEW_ISSUE} = 1;
765 elsif ($issue->{borrowernumber}) {
767 # issued to someone else
768 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
770 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
771 $needsconfirmation{ISSUED_TO_ANOTHER} =
772 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
775 # See if the item is on reserve.
776 my ( $restype, $res ) = CheckReserves( $item->{'itemnumber'} );
778 my $resbor = $res->{'borrowernumber'};
779 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
782 # The item is on reserve and waiting, but has been
783 # reserved by some other patron.
784 my ( $resborrower, $flags ) =
785 GetMemberDetails( $resbor, 0 );
786 my $branches = GetBranches();
788 $branches->{ $res->{'branchcode'} }->{'branchname'};
789 $needsconfirmation{RESERVE_WAITING} =
790 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
792 # CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'}); Doesn't belong in a checking subroutine.
794 elsif ( $restype eq "Reserved" ) {
796 # The item is on reserve for someone else.
797 my ( $resborrower, $flags ) =
798 GetMemberDetails( $resbor, 0 );
799 my $branches = GetBranches();
801 $branches->{ $res->{'branchcode'} }->{'branchname'};
802 $needsconfirmation{RESERVED} =
803 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
806 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
807 if ( $borrower->{'categorycode'} eq 'W' ) {
808 my %issuingimpossible;
809 return ( \%issuingimpossible, \%needsconfirmation );
811 return ( \%issuingimpossible, \%needsconfirmation );
814 return ( \%issuingimpossible, \%needsconfirmation );
820 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
822 &AddIssue($borrower,$barcode,$date)
826 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
828 =item C<$barcode> is the bar code of the book being issued.
830 =item C<$date> contains the max date of return. calculated if empty.
832 AddIssue does the following things :
833 - step 01: check that there is a borrowernumber & a barcode provided
834 - check for RENEWAL (book issued & being issued to the same patron)
835 - renewal YES = Calculate Charge & renew
837 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
839 - fill reserve if reserve to this patron
840 - cancel reserve or not, otherwise
841 * TRANSFERT PENDING ?
842 - complete the transfert
850 my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
851 my $dbh = C4::Context->dbh;
852 my $barcodecheck=CheckValidBarcode($barcode);
853 if ($borrower and $barcode and $barcodecheck ne '0'){
854 # my ($borrower, $flags) = &GetMemberDetails($borrowernumber, 0);
855 # find which item we issue
856 my $item = GetItem('', $barcode);
858 # get actual issuing if there is one
859 my $actualissue = GetItemIssue( $item->{itemnumber});
861 # get biblioinformation for this item
862 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
865 # check if we just renew the issue.
867 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
868 # we renew, do we need to add some charge ?
869 my ( $charge, $itemtype ) = GetIssuingCharges(
870 $item->{'itemnumber'},
871 $borrower->{'borrowernumber'}
875 $item->{'itemnumber'},
876 $borrower->{'borrowernumber'}, $charge
878 $item->{'charge'} = $charge;
881 C4::Context->userenv->{'branch'},
883 '', $item->{'itemnumber'},
884 $biblio->{'itemtype'}, $borrower->{'borrowernumber'}
887 $borrower->{'borrowernumber'},
888 $item->{'itemnumber'}
891 else {# it's NOT a renewal
892 if ( $actualissue->{borrowernumber}) {
893 # This book is currently on loan, but not to the person
894 # who wants to borrow it now. mark it returned before issuing to the new borrower
897 C4::Context->userenv->{'branch'}
901 # See if the item is on reserve.
902 my ( $restype, $res ) =
903 CheckReserves( $item->{'itemnumber'} );
905 my $resbor = $res->{'borrowernumber'};
906 if ( $resbor eq $borrower->{'borrowernumber'} ) {
908 # The item is reserved by the current patron
909 ModReserveFill($res);
911 elsif ( $restype eq "Waiting" ) {
914 # The item is on reserve and waiting, but has been
915 # reserved by some other patron.
916 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
917 my $branches = GetBranches();
919 $branches->{ $res->{'branchcode'} }->{'branchname'};
921 elsif ( $restype eq "Reserved" ) {
924 # The item is reserved by someone else.
925 my ( $resborrower, $flags ) =
926 GetMemberDetails( $resbor, 0 );
927 my $branches = GetBranches();
929 $branches->{ $res->{'branchcode'} }->{'branchname'};
930 if ($cancelreserve) { # cancel reserves on this item
931 CancelReserve( 0, $res->{'itemnumber'},
932 $res->{'borrowernumber'} );
935 if ($cancelreserve) {
936 CancelReserve( $res->{'biblionumber'}, 0,
937 $res->{'borrowernumber'} );
940 # set waiting reserve to first in reserve queue as book isn't waiting now
943 $res->{'biblionumber'},
944 $res->{'borrowernumber'},
950 # Starting process for transfer job (checking transfert and validate it if we have one)
951 my ($datesent) = GetTransfers($item->{'itemnumber'});
953 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
956 "UPDATE branchtransfers
957 SET datearrived = now(),
959 comments = 'Forced branchtransfert'
960 WHERE itemnumber= ? AND datearrived IS NULL"
962 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
966 # Record in the database the fact that the book was issued.
970 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
973 my $loanlength = GetLoanLength(
974 $borrower->{'categorycode'},
975 $biblio->{'itemtype'},
976 $borrower->{'branchcode'}
978 my $datedue = time + ($loanlength) * 86400;
979 my @datearr = localtime($datedue);
981 sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]);
985 $dateduef=CheckValidDatedue($dateduef,$item->{'itemnumber'},C4::Context->userenv->{'branch'});
986 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
987 if ( C4::Context->preference('ReturnBeforeExpiry')
988 && $dateduef gt $borrower->{dateexpiry} )
990 $dateduef = $borrower->{dateexpiry};
993 $borrower->{'borrowernumber'},
994 $item->{'itemnumber'},
995 strftime( "%Y-%m-%d", localtime ),$dateduef, C4::Context->userenv->{'branch'}
1001 "UPDATE items SET issues=?, holdingbranch=?, itemlost=0, datelastborrowed = now() WHERE itemnumber=?");
1004 C4::Context->userenv->{'branch'},
1005 $item->{'itemnumber'}
1008 &ModDateLastSeen( $item->{'itemnumber'} );
1009 # If it costs to borrow this book, charge it to the patron's account.
1010 my ( $charge, $itemtype ) = GetIssuingCharges(
1011 $item->{'itemnumber'},
1012 $borrower->{'borrowernumber'}
1014 if ( $charge > 0 ) {
1016 $item->{'itemnumber'},
1017 $borrower->{'borrowernumber'}, $charge
1019 $item->{'charge'} = $charge;
1022 # Record the fact that this book was issued.
1024 C4::Context->userenv->{'branch'},
1026 '', $item->{'itemnumber'},
1027 $item->{'itemtype'}, $borrower->{'borrowernumber'}
1031 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'})
1032 if C4::Context->preference("IssueLog");
1036 =head2 GetLoanLength
1038 Get loan length for an itemtype, a borrower type and a branch
1040 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1045 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1046 my $dbh = C4::Context->dbh;
1049 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=?"
1052 # try to find issuelength & return the 1st available.
1053 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1054 $sth->execute( $borrowertype, $itemtype, $branchcode );
1055 my $loanlength = $sth->fetchrow_hashref;
1056 return $loanlength->{issuelength}
1057 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1059 $sth->execute( $borrowertype, $itemtype, "" );
1060 $loanlength = $sth->fetchrow_hashref;
1061 return $loanlength->{issuelength}
1062 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1064 $sth->execute( $borrowertype, "*", $branchcode );
1065 $loanlength = $sth->fetchrow_hashref;
1066 return $loanlength->{issuelength}
1067 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1069 $sth->execute( "*", $itemtype, $branchcode );
1070 $loanlength = $sth->fetchrow_hashref;
1071 return $loanlength->{issuelength}
1072 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1074 $sth->execute( $borrowertype, "*", "" );
1075 $loanlength = $sth->fetchrow_hashref;
1076 return $loanlength->{issuelength}
1077 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1079 $sth->execute( "*", "*", $branchcode );
1080 $loanlength = $sth->fetchrow_hashref;
1081 return $loanlength->{issuelength}
1082 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1084 $sth->execute( "*", $itemtype, "" );
1085 $loanlength = $sth->fetchrow_hashref;
1086 return $loanlength->{issuelength}
1087 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1089 $sth->execute( "*", "*", "" );
1090 $loanlength = $sth->fetchrow_hashref;
1091 return $loanlength->{issuelength}
1092 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1094 # if no rule is set => 21 days (hardcoded)
1100 ($doreturn, $messages, $iteminformation, $borrower) =
1101 &AddReturn($barcode, $branch);
1105 C<$barcode> is the bar code of the book being returned. C<$branch> is
1106 the code of the branch where the book is being returned.
1108 C<&AddReturn> returns a list of four items:
1110 C<$doreturn> is true iff the return succeeded.
1112 C<$messages> is a reference-to-hash giving the reason for failure:
1118 No item with this barcode exists. The value is C<$barcode>.
1122 The book is not currently on loan. The value is C<$barcode>.
1124 =item C<IsPermanent>
1126 The book's home branch is a permanent collection. If you have borrowed
1127 this book, you are not allowed to return it. The value is the code for
1128 the book's home branch.
1132 This book has been withdrawn/cancelled. The value should be ignored.
1136 The item was reserved. The value is a reference-to-hash whose keys are
1137 fields from the reserves table of the Koha database, and
1138 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1139 either C<Waiting>, C<Reserved>, or 0.
1143 C<$borrower> is a reference-to-hash, giving information about the
1144 patron who last borrowed the book.
1149 my ( $barcode, $branch ) = @_;
1150 my $dbh = C4::Context->dbh;
1154 my $validTransfert = 0;
1155 my $reserveDone = 0;
1157 # get information on item
1158 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1159 unless ($iteminformation->{'itemnumber'} ) {
1160 $messages->{'BadBarcode'} = $barcode;
1164 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1165 $messages->{'NotIssued'} = $barcode;
1169 # check if the book is in a permanent collection....
1170 my $hbr = $iteminformation->{'homebranch'};
1171 my $branches = GetBranches();
1172 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1173 $messages->{'IsPermanent'} = $hbr;
1176 # check that the book has been cancelled
1177 if ( $iteminformation->{'wthdrawn'} ) {
1178 $messages->{'wthdrawn'} = 1;
1182 # new op dev : if the book returned in an other branch update the holding branch
1184 # update issues, thereby returning book (should push this out into another subroutine
1185 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1187 # case of a return of document (deal with issues and holdingbranch)
1192 "UPDATE issues SET returndate = now() WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (returndate IS NULL)"
1194 $sth->execute( $borrower->{'borrowernumber'},
1195 $iteminformation->{'itemnumber'} );
1196 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1199 # continue to deal with returns cases, but not only if we have an issue
1201 # the holdingbranch is updated if the document is returned in an other location .
1202 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} )
1204 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1205 # reload iteminformation holdingbranch with the userenv value
1206 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1208 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1209 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1211 # fix up the accounts.....
1212 if ( $iteminformation->{'itemlost'} ) {
1213 $messages->{'WasLost'} = 1;
1216 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1217 # check if we have a transfer for this document
1218 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1220 # if we have a transfer to do, we update the line of transfers with the datearrived
1222 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1225 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1227 $sth->execute( $iteminformation->{'itemnumber'} );
1229 # 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'
1230 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1233 $messages->{'WrongTransfer'} = $tobranch;
1234 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1236 $validTransfert = 1;
1239 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1240 # fix up the accounts.....
1241 if ($iteminformation->{'itemlost'}) {
1242 FixAccountForLostAndReturned($iteminformation, $borrower);
1243 $messages->{'WasLost'} = 1;
1245 # fix up the overdues in accounts...
1246 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1247 $iteminformation->{'itemnumber'} );
1249 # find reserves.....
1250 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1251 my ( $resfound, $resrec ) =
1252 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1254 $resrec->{'ResFound'} = $resfound;
1255 $messages->{'ResFound'} = $resrec;
1260 # Record the fact that this book was returned.
1262 $branch, 'return', '0', '',
1263 $iteminformation->{'itemnumber'},
1264 $iteminformation->{'itemtype'},
1265 $borrower->{'borrowernumber'}
1268 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'})
1269 if C4::Context->preference("ReturnLog");
1271 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1272 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1274 if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1275 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1276 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1277 $messages->{'WasTransfered'} = 1;
1278 warn "was transfered";
1282 return ( $doreturn, $messages, $iteminformation, $borrower );
1285 =head2 FixOverduesOnReturn
1287 &FixOverduesOnReturn($brn,$itm);
1289 C<$brn> borrowernumber
1293 internal function, called only by AddReturn
1297 sub FixOverduesOnReturn {
1298 my ( $borrowernumber, $item ) = @_;
1299 my $dbh = C4::Context->dbh;
1301 # check for overdue fine
1304 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1306 $sth->execute( $borrowernumber, $item );
1308 # alter fine to show that the book has been returned
1309 if ( my $data = $sth->fetchrow_hashref ) {
1312 "UPDATE accountlines SET accounttype='F' WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accountno = ?)"
1314 $usth->execute( $borrowernumber, $item, $data->{'accountno'} );
1321 =head2 FixAccountForLostAndReturned
1323 &FixAccountForLostAndReturned($iteminfo,$borrower);
1325 Calculates the charge for a book lost and returned (Not exported & used only once)
1327 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1329 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1331 Internal function, called by AddReturn
1335 sub FixAccountForLostAndReturned {
1336 my ($iteminfo, $borrower) = @_;
1338 my $dbh = C4::Context->dbh;
1339 my $itm = $iteminfo->{'itemnumber'};
1340 # check for charge made for lost book
1341 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1342 $sth->execute($itm);
1343 if (my $data = $sth->fetchrow_hashref) {
1344 # writeoff this amount
1346 my $amount = $data->{'amount'};
1347 my $acctno = $data->{'accountno'};
1349 if ($data->{'amountoutstanding'} == $amount) {
1350 $offset = $data->{'amount'};
1353 $offset = $amount - $data->{'amountoutstanding'};
1354 $amountleft = $data->{'amountoutstanding'} - $amount;
1356 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1357 WHERE (borrowernumber = ?)
1358 AND (itemnumber = ?) AND (accountno = ?) ");
1359 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1361 #check if any credit is left if so writeoff other accounts
1362 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1363 if ($amountleft < 0){
1366 if ($amountleft > 0){
1367 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1368 AND (amountoutstanding >0) ORDER BY date");
1369 $msth->execute($data->{'borrowernumber'});
1370 # offset transactions
1373 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1374 if ($accdata->{'amountoutstanding'} < $amountleft) {
1376 $amountleft -= $accdata->{'amountoutstanding'};
1378 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1381 my $thisacct = $accdata->{'accountno'};
1382 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1383 WHERE (borrowernumber = ?)
1384 AND (accountno=?)");
1385 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1387 $usth = $dbh->prepare("INSERT INTO accountoffsets
1388 (borrowernumber, accountno, offsetaccount, offsetamount)
1391 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1396 if ($amountleft > 0){
1399 my $desc="Book Returned ".$iteminfo->{'barcode'};
1400 $usth = $dbh->prepare("INSERT INTO accountlines
1401 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1402 VALUES (?,?,now(),?,?,'CR',?)");
1403 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1405 $usth = $dbh->prepare("INSERT INTO accountoffsets
1406 (borrowernumber, accountno, offsetaccount, offsetamount)
1408 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1410 $usth = $dbh->prepare("UPDATE items SET paidfor='' WHERE itemnumber=?");
1411 $usth->execute($itm);
1420 $issues = &GetItemIssue($itemnumber);
1422 Returns patrons currently having a book. nothing if item is not issued atm
1424 C<$itemnumber> is the itemnumber
1426 Returns an array of hashes
1430 my ( $itemnumber) = @_;
1431 return unless $itemnumber;
1432 my $dbh = C4::Context->dbh;
1436 my $today = POSIX::strftime("%Y%m%d", localtime);
1438 my $sth = $dbh->prepare(
1439 "SELECT * FROM issues
1440 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1442 issues.itemnumber=? AND returndate IS NULL ");
1443 $sth->execute($itemnumber);
1444 my $data = $sth->fetchrow_hashref;
1445 my $datedue = $data->{'date_due'};
1447 if ( $datedue < $today ) {
1448 $data->{'overdue'} = 1;
1450 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1455 =head2 GetItemIssues
1457 $issues = &GetItemIssues($itemnumber, $history);
1459 Returns patrons that have issued a book
1461 C<$itemnumber> is the itemnumber
1462 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1464 Returns an array of hashes
1468 my ( $itemnumber,$history ) = @_;
1469 my $dbh = C4::Context->dbh;
1473 my $today = POSIX::strftime("%Y%m%d", localtime);
1475 my $sth = $dbh->prepare(
1476 "SELECT * FROM issues
1477 LEFT JOIN borrowers ON borrowers.borrowernumber
1478 LEFT JOIN items ON items.itemnumber=issues.itemnumber
1480 issues.itemnumber=?".($history?"":" AND returndate IS NULL ").
1481 "ORDER BY issues.date_due DESC"
1483 $sth->execute($itemnumber);
1484 while ( my $data = $sth->fetchrow_hashref ) {
1485 my $datedue = $data->{'date_due'};
1487 if ( $datedue < $today ) {
1488 $data->{'overdue'} = 1;
1490 my $itemnumber = $data->{'itemnumber'};
1491 push @GetItemIssues, $data;
1494 return ( \@GetItemIssues );
1497 =head2 GetBiblioIssues
1499 $issues = GetBiblioIssues($biblionumber);
1501 this function get all issues from a biblionumber.
1504 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1505 tables issues and the firstname,surname & cardnumber from borrowers.
1509 sub GetBiblioIssues {
1510 my $biblionumber = shift;
1511 return undef unless $biblionumber;
1512 my $dbh = C4::Context->dbh;
1514 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1516 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1517 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1518 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1519 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1520 WHERE biblio.biblionumber = ?
1521 ORDER BY issues.timestamp
1523 my $sth = $dbh->prepare($query);
1524 $sth->execute($biblionumber);
1527 while ( my $data = $sth->fetchrow_hashref ) {
1528 push @issues, $data;
1533 =head2 CanBookBeRenewed
1535 $ok = &CanBookBeRenewed($borrowernumber, $itemnumber);
1537 Find out whether a borrowed item may be renewed.
1539 C<$dbh> is a DBI handle to the Koha database.
1541 C<$borrowernumber> is the borrower number of the patron who currently
1542 has the item on loan.
1544 C<$itemnumber> is the number of the item to renew.
1546 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1547 item must currently be on loan to the specified borrower; renewals
1548 must be allowed for the item's type; and the borrower must not have
1549 already renewed the loan.
1553 sub CanBookBeRenewed {
1555 # check renewal status
1556 my ( $borrowernumber, $itemnumber ) = @_;
1557 my $dbh = C4::Context->dbh;
1561 # Look in the issues table for this item, lent to this borrower,
1562 # and not yet returned.
1564 # FIXME - I think this function could be redone to use only one SQL call.
1565 my $sth1 = $dbh->prepare(
1566 "SELECT * FROM issues
1567 WHERE borrowernumber = ?
1569 AND returndate IS NULL"
1571 $sth1->execute( $borrowernumber, $itemnumber );
1572 if ( my $data1 = $sth1->fetchrow_hashref ) {
1574 # Found a matching item
1576 # See if this item may be renewed. This query is convoluted
1577 # because it's a bit messy: given the item number, we need to find
1578 # the biblioitem, which gives us the itemtype, which tells us
1579 # whether it may be renewed.
1580 my $sth2 = $dbh->prepare(
1581 "SELECT renewalsallowed FROM items
1582 LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1583 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1584 WHERE items.itemnumber = ?
1587 $sth2->execute($itemnumber);
1588 if ( my $data2 = $sth2->fetchrow_hashref ) {
1589 $renews = $data2->{'renewalsallowed'};
1591 if ( $renews && $renews >= $data1->{'renewals'} ) {
1595 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1602 return ($renewokay);
1607 &AddRenewal($borrowernumber, $itemnumber, $datedue);
1611 C<$borrowernumber> is the borrower number of the patron who currently
1614 C<$itemnumber> is the number of the item to renew.
1616 C<$datedue> can be used to set the due date. If C<$datedue> is the
1617 empty string, C<&AddRenewal> will calculate the due date automatically
1618 from the book's item type. If you wish to set the due date manually,
1619 C<$datedue> should be in the form YYYY-MM-DD.
1625 my ( $borrowernumber, $itemnumber, $branch ,$datedue ) = @_;
1626 my $dbh = C4::Context->dbh;
1628 # If the due date wasn't specified, calculate it by adding the
1629 # book's loan length to today's date.
1630 if ( $datedue eq "" ) {
1632 my $biblio = GetBiblioFromItemNumber($itemnumber);
1633 my $borrower = GetMemberDetails( $borrowernumber, 0 );
1634 my $loanlength = GetLoanLength(
1635 $borrower->{'categorycode'},
1636 $biblio->{'itemtype'},
1637 $borrower->{'branchcode'}
1639 my ( $due_year, $due_month, $due_day ) =
1640 Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
1641 $datedue = "$due_year-$due_month-$due_day";
1642 $datedue=CheckValidDatedue($datedue,$itemnumber,$branch);
1645 # Find the issues record for this book
1647 $dbh->prepare("SELECT * FROM issues
1648 WHERE borrowernumber=?
1650 AND returndate IS NULL"
1652 $sth->execute( $borrowernumber, $itemnumber );
1653 my $issuedata = $sth->fetchrow_hashref;
1656 # Update the issues record to have the new due date, and a new count
1657 # of how many times it has been renewed.
1658 my $renews = $issuedata->{'renewals'} + 1;
1659 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1660 WHERE borrowernumber=?
1662 AND returndate IS NULL"
1664 $sth->execute( $datedue, $renews, $borrowernumber, $itemnumber );
1668 UpdateStats( C4::Context->userenv->{'branchcode'}, 'renew', '', '', $itemnumber );
1670 # Charge a new rental fee, if applicable?
1671 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1672 if ( $charge > 0 ) {
1673 my $accountno = getnextacctno( $borrowernumber );
1674 my $item = GetBiblioFromItemNumber($itemnumber);
1675 $sth = $dbh->prepare(
1676 "INSERT INTO accountlines
1677 (borrowernumber,accountno,date,amount,
1678 description,accounttype,amountoutstanding,
1680 VALUES (?,?,now(),?,?,?,?,?)"
1682 $sth->execute( $borrowernumber, $accountno, $charge,
1683 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1684 'Rent', $charge, $itemnumber );
1689 =head2 GetIssuingCharges
1691 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1693 Calculate how much it would cost for a given patron to borrow a given
1694 item, including any applicable discounts.
1696 C<$itemnumber> is the item number of item the patron wishes to borrow.
1698 C<$borrowernumber> is the patron's borrower number.
1700 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1701 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1706 sub GetIssuingCharges {
1708 # calculate charges due
1709 my ( $itemnumber, $borrowernumber ) = @_;
1711 my $dbh = C4::Context->dbh;
1714 # Get the book's item type and rental charge (via its biblioitem).
1715 my $sth1 = $dbh->prepare(
1716 "SELECT itemtypes.itemtype,rentalcharge FROM items
1717 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1718 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1719 WHERE items.itemnumber =?
1722 $sth1->execute($itemnumber);
1723 if ( my $data1 = $sth1->fetchrow_hashref ) {
1724 $item_type = $data1->{'itemtype'};
1725 $charge = $data1->{'rentalcharge'};
1726 my $q2 = "SELECT rentaldiscount FROM borrowers
1727 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1728 WHERE borrowers.borrowernumber = ?
1729 AND issuingrules.itemtype = ?";
1730 my $sth2 = $dbh->prepare($q2);
1731 $sth2->execute( $borrowernumber, $item_type );
1732 if ( my $data2 = $sth2->fetchrow_hashref ) {
1733 my $discount = $data2->{'rentaldiscount'};
1734 if ( $discount eq 'NULL' ) {
1737 $charge = ( $charge * ( 100 - $discount ) ) / 100;
1743 return ( $charge, $item_type );
1746 =head2 AddIssuingCharge
1748 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1752 sub AddIssuingCharge {
1753 my ( $itemnumber, $borrowernumber, $charge ) = @_;
1754 my $dbh = C4::Context->dbh;
1755 my $nextaccntno = getnextacctno( $borrowernumber );
1757 INSERT INTO accountlines
1758 (borrowernumber, itemnumber, accountno,
1759 date, amount, description, accounttype,
1761 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1763 my $sth = $dbh->prepare($query);
1764 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1770 GetTransfers($itemnumber);
1775 my ($itemnumber) = @_;
1777 my $dbh = C4::Context->dbh;
1783 FROM branchtransfers
1784 WHERE itemnumber = ?
1785 AND datearrived IS NULL
1787 my $sth = $dbh->prepare($query);
1788 $sth->execute($itemnumber);
1789 my @row = $sth->fetchrow_array();
1795 =head2 GetTransfersFromTo
1797 @results = GetTransfersFromTo($frombranch,$tobranch);
1799 Returns the list of pending transfers between $from and $to branch
1803 sub GetTransfersFromTo {
1804 my ( $frombranch, $tobranch ) = @_;
1805 return unless ( $frombranch && $tobranch );
1806 my $dbh = C4::Context->dbh;
1808 SELECT itemnumber,datesent,frombranch
1809 FROM branchtransfers
1812 AND datearrived IS NULL
1814 my $sth = $dbh->prepare($query);
1815 $sth->execute( $frombranch, $tobranch );
1818 while ( my $data = $sth->fetchrow_hashref ) {
1819 push @gettransfers, $data;
1822 return (@gettransfers);
1825 =head2 DeleteTransfer
1827 &DeleteTransfer($itemnumber);
1831 sub DeleteTransfer {
1832 my ($itemnumber) = @_;
1833 my $dbh = C4::Context->dbh;
1834 my $sth = $dbh->prepare(
1835 "DELETE FROM branchtransfers
1837 AND datearrived IS NULL "
1839 $sth->execute($itemnumber);
1843 =head2 AnonymiseIssueHistory
1845 $rows = AnonymiseIssueHistory($borrowernumber,$date)
1847 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
1848 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
1850 return the number of affected rows.
1854 sub AnonymiseIssueHistory {
1856 my $borrowernumber = shift;
1857 my $dbh = C4::Context->dbh;
1860 SET borrowernumber = NULL
1861 WHERE returndate < '".$date."'
1862 AND borrowernumber IS NOT NULL
1864 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
1865 my $rows_affected = $dbh->do($query);
1866 return $rows_affected;
1869 =head2 updateWrongTransfer
1871 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
1873 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
1877 sub updateWrongTransfer {
1878 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
1879 my $dbh = C4::Context->dbh;
1880 # first step validate the actual line of transfert .
1883 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
1885 $sth->execute($FromLibrary,$itemNumber);
1888 # second step create a new line of branchtransfer to the right location .
1889 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
1891 #third step changing holdingbranch of item
1892 UpdateHoldingbranch($FromLibrary,$itemNumber);
1895 =head2 UpdateHoldingbranch
1897 $items = UpdateHoldingbranch($branch,$itmenumber);
1898 Simple methode for updating hodlingbranch in items BDD line
1901 sub UpdateHoldingbranch {
1902 my ( $branch,$itmenumber ) = @_;
1903 my $dbh = C4::Context->dbh;
1904 # first step validate the actual line of transfert .
1907 "update items set holdingbranch = ? where itemnumber= ?"
1909 $sth->execute($branch,$itmenumber);
1914 =head2 CheckValidDatedue
1916 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
1917 this function return a new date due after checked if it's a repeatable or special holiday
1918 C<$date_due> = returndate calculate with no day check
1919 C<$itemnumber> = itemnumber
1920 C<$branchcode> = localisation of issue
1922 sub CheckValidDatedue{
1923 my ($date_due,$itemnumber,$branchcode)=@_;
1924 my @datedue=split('-',$date_due);
1925 my $years=$datedue[0];
1926 my $month=$datedue[1];
1927 my $day=$datedue[2];
1929 for (my $i=0;$i<2;$i++){
1930 $dow=Day_of_Week($years,$month,$day);
1931 ($dow=0) if ($dow>6);
1932 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
1933 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1934 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1935 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
1937 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
1940 my $newdatedue=$years."-".$month."-".$day;
1943 =head2 CheckRepeatableHolidays
1945 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
1946 this function check if the date due is a repeatable holiday
1947 C<$date_due> = returndate calculate with no day check
1948 C<$itemnumber> = itemnumber
1949 C<$branchcode> = localisation of issue
1953 sub CheckRepeatableHolidays{
1954 my($itemnumber,$week_day,$branchcode)=@_;
1955 my $dbh = C4::Context->dbh;
1956 my $query = qq|SELECT count(*)
1957 FROM repeatable_holidays
1960 my $sth = $dbh->prepare($query);
1961 $sth->execute($branchcode,$week_day);
1962 my $result=$sth->fetchrow;
1968 =head2 CheckSpecialHolidays
1970 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1971 this function check if the date is a special holiday
1972 C<$years> = the years of datedue
1973 C<$month> = the month of datedue
1974 C<$day> = the day of datedue
1975 C<$itemnumber> = itemnumber
1976 C<$branchcode> = localisation of issue
1978 sub CheckSpecialHolidays{
1979 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
1980 my $dbh = C4::Context->dbh;
1981 my $query=qq|SELECT count(*)
1982 FROM `special_holidays`
1988 my $sth = $dbh->prepare($query);
1989 $sth->execute($years,$month,$day,$branchcode);
1990 my $countspecial=$sth->fetchrow ;
1992 return $countspecial;
1995 =head2 CheckRepeatableSpecialHolidays
1997 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1998 this function check if the date is a repeatble special holidays
1999 C<$month> = the month of datedue
2000 C<$day> = the day of datedue
2001 C<$itemnumber> = itemnumber
2002 C<$branchcode> = localisation of issue
2004 sub CheckRepeatableSpecialHolidays{
2005 my ($month,$day,$itemnumber,$branchcode) = @_;
2006 my $dbh = C4::Context->dbh;
2007 my $query=qq|SELECT count(*)
2008 FROM `repeatable_holidays`
2013 my $sth = $dbh->prepare($query);
2014 $sth->execute($month,$day,$branchcode);
2015 my $countspecial=$sth->fetchrow ;
2017 return $countspecial;
2022 sub CheckValidBarcode{
2024 my $dbh = C4::Context->dbh;
2025 my $query=qq|SELECT count(*)
2029 my $sth = $dbh->prepare($query);
2030 $sth->execute($barcode);
2031 my $exist=$sth->fetchrow ;
2042 Koha Developement team <info@koha.org>