1 package C4::Circulation;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
42 use POSIX qw(strftime);
43 use C4::Branch; # GetBranches
44 use C4::Log; # logaction
48 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
51 # set the version for version checking
55 # FIXME subs that should probably be elsewhere
61 # subs to deal with issuing a book
74 &AnonymiseIssueHistory
77 # subs to deal with returns
83 # subs to deal with transfers
95 C4::Circulation - Koha circulation module
103 The functions in this module deal with circulation, issues, and
104 returns, as well as general information about the library.
105 Also deals with stocktaking.
111 =head3 $str = &decode($chunk);
115 =item Generic filter function for barcode string.
121 # 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 ?
122 # FIXME -- the &decode fcn below should be wrapped into this one.
126 my $filter = C4::Context->preference('itemBarcodeInputFilter');
127 if($filter eq 'whitespace') {
130 } elsif($filter eq 'cuecat') {
132 my @fields = split( /\./, $barcode );
133 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
134 if ( $#results == 2 ) {
140 } elsif($filter eq 'T-prefix') {
141 my $num = ( $barcode =~ /^[Tt] /) ? substr($barcode,2) + 0 : $barcode;
142 return sprintf( "T%07d",$num);
148 =head3 $str = &decode($chunk);
152 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
162 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
163 my @s = map { index( $seq, $_ ); } split( //, $encoded );
164 my $l = ( $#s + 1 ) % 4;
175 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
177 chr( ( $n >> 16 ) ^ 67 )
178 .chr( ( $n >> 8 & 255 ) ^ 67 )
179 .chr( ( $n & 255 ) ^ 67 );
182 $r = substr( $r, 0, length($r) - $l );
188 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
190 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
192 C<$newbranch> is the code for the branch to which the item should be transferred.
194 C<$barcode> is the barcode of the item to be transferred.
196 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
197 Otherwise, if an item is reserved, the transfer fails.
199 Returns three values:
203 is true if the transfer was successful.
207 is a reference-to-hash which may have any of the following keys:
213 There is no item in the catalog with the given barcode. The value is C<$barcode>.
217 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.
219 =item C<DestinationEqualsHolding>
221 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.
225 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.
229 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>.
231 =item C<WasTransferred>
233 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
240 my ( $tbr, $barcode, $ignoreRs ) = @_;
243 my $branches = GetBranches();
244 my $itemnumber = GetItemnumberFromBarcode( $barcode );
245 my $issue = GetItemIssue($itemnumber);
246 my $biblio = GetBiblioFromItemNumber($itemnumber);
249 if ( not $itemnumber ) {
250 $messages->{'BadBarcode'} = $barcode;
254 # get branches of book...
255 my $hbr = $biblio->{'homebranch'};
256 my $fbr = $biblio->{'holdingbranch'};
259 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
260 $messages->{'IsPermanent'} = $hbr;
263 # can't transfer book if is already there....
264 if ( $fbr eq $tbr ) {
265 $messages->{'DestinationEqualsHolding'} = 1;
269 # check if it is still issued to someone, return it...
270 if ($issue->{borrowernumber}) {
271 AddReturn( $barcode, $fbr );
272 $messages->{'WasReturned'} = $issue->{borrowernumber};
276 # That'll save a database query.
277 my ( $resfound, $resrec ) =
278 CheckReserves( $itemnumber );
279 if ( $resfound and not $ignoreRs ) {
280 $resrec->{'ResFound'} = $resfound;
282 # $messages->{'ResFound'} = $resrec;
286 #actually do the transfer....
288 ModItemTransfer( $itemnumber, $fbr, $tbr );
290 # don't need to update MARC anymore, we do it in batch now
291 $messages->{'WasTransfered'} = 1;
292 ModDateLastSeen( $itemnumber );
294 return ( $dotransfer, $messages, $biblio );
297 =head2 CanBookBeIssued
299 Check if a book can be issued.
301 my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($borrower,$barcode,$year,$month,$day);
305 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
307 =item C<$barcode> is the bar code of the book being issued.
309 =item C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
317 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
318 Possible values are :
324 sticky due date is invalid
328 borrower gone with no address
332 borrower declared it's card lost
338 =head3 UNKNOWN_BARCODE
352 item is restricted (set by ??)
354 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
355 Possible values are :
363 renewing, not issuing
365 =head3 ISSUED_TO_ANOTHER
367 issued to someone else.
371 reserved for someone else.
375 sticky due date is invalid
379 if the borrower borrows to much things
383 # check if a book can be issued.
387 my $borrower = shift;
388 my $biblionumber = shift;
390 my $cat_borrower = $borrower->{'categorycode'};
391 my $dbh = C4::Context->dbh;
393 # Get which branchcode we need
394 if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
395 $branch = C4::Context->userenv->{'branch'};
397 elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
398 $branch = $borrower->{'branchcode'};
402 $branch = $item->{'homebranch'};
404 my $type = (C4::Context->preference('item-level_itypes'))
405 ? $item->{'itype'} # item-level
406 : $item->{'itemtype'}; # biblio-level
410 'SELECT * FROM issuingrules
411 WHERE categorycode = ?
416 my $query2 = "SELECT COUNT(*) FROM issues i, biblioitems s1, items s2
417 WHERE i.borrowernumber = ?
418 AND i.itemnumber = s2.itemnumber
419 AND s1.biblioitemnumber = s2.biblioitemnumber";
420 if (C4::Context->preference('item-level_itypes')){
421 $query2.=" AND s2.itype=? ";
423 $query2.=" AND s1.itemtype= ? ";
425 my $sth2= $dbh->prepare($query2);
428 'SELECT COUNT(*) FROM issues
429 WHERE borrowernumber = ?'
433 # check the 3 parameters (branch / itemtype / category code
434 $sth->execute( $cat_borrower, $type, $branch );
435 my $result = $sth->fetchrow_hashref;
436 # warn "$cat_borrower, $type, $branch = ".Data::Dumper::Dumper($result);
438 if ( $result->{maxissueqty} ne '' ) {
439 # warn "checking on everything set";
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/category/itemtype failed)" );
445 # now checking for total
446 $sth->execute( $cat_borrower, '*', $branch );
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/category/total failed)" );
457 # check the 2 parameters (branch / itemtype / default categorycode
458 $sth->execute( '*', $type, $branch );
459 $result = $sth->fetchrow_hashref;
460 # warn "*, $type, $branch = ".Data::Dumper::Dumper($result);
462 if ( $result->{maxissueqty} ne '' ) {
463 # warn "checking on 2 parameters (default 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 branch / default category / itemtype failed)" );
469 # now checking for total
470 $sth->execute( '*', '*', $branch );
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 branch / default category / total failed)" );
481 # check the 1 parameters (default branch / itemtype / categorycode
482 $sth->execute( $cat_borrower, $type, '*' );
483 $result = $sth->fetchrow_hashref;
484 # warn "$cat_borrower, $type, * = ".Data::Dumper::Dumper($result);
486 if ( $result->{maxissueqty} ne '' ) {
487 # warn "checking on 1 parameter (default branch + 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/category/itemtype failed)" );
493 # now checking for total
494 $sth->execute( $cat_borrower, '*', '*' );
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 / category / total failed)" );
505 # check the 0 parameters (default branch / itemtype / default categorycode
506 $sth->execute( '*', $type, '*' );
507 $result = $sth->fetchrow_hashref;
508 # warn "*, $type, * = ".Data::Dumper::Dumper($result);
510 if ( $result->{maxissueqty} ne '' ) {
511 # warn "checking on default branch and default categorycode";
512 $sth2->execute( $borrower->{'borrowernumber'}, $type );
513 my $alreadyissued = $sth2->fetchrow;
514 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
515 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / itemtype failed)" );
518 # now checking for total
519 $sth->execute( '*', '*', '*' );
520 $result = $sth->fetchrow_hashref;
521 if ( $result->{maxissueqty} ne '' ) {
522 warn "checking total";
523 $sth2->execute( $borrower->{'borrowernumber'}, $type );
524 my $alreadyissued = $sth2->fetchrow;
525 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
526 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / total failed)" );
530 # OK, the patron can issue !!!
536 @issues = &itemissues($biblioitemnumber, $biblio);
538 Looks up information about who has borrowed the bookZ<>(s) with the
539 given biblioitemnumber.
541 C<$biblio> is ignored.
543 C<&itemissues> returns an array of references-to-hash. The keys
544 include the fields from the C<items> table in the Koha database.
545 Additional keys include:
551 If the item is currently on loan, this gives the due date.
553 If the item is not on loan, then this is either "Available" or
554 "Cancelled", if the item has been withdrawn.
558 If the item is currently on loan, this gives the card number of the
559 patron who currently has the item.
561 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
563 These give the timestamp for the last three times the item was
566 =item C<card0>, C<card1>, C<card2>
568 The card number of the last three patrons who borrowed this item.
570 =item C<borrower0>, C<borrower1>, C<borrower2>
572 The borrower number of the last three patrons who borrowed this item.
580 my ( $bibitem, $biblio ) = @_;
581 my $dbh = C4::Context->dbh;
583 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
588 $sth->execute($bibitem) || die $sth->errstr;
590 while ( my $data = $sth->fetchrow_hashref ) {
592 # Find out who currently has this item.
593 # FIXME - Wouldn't it be better to do this as a left join of
594 # some sort? Currently, this code assumes that if
595 # fetchrow_hashref() fails, then the book is on the shelf.
596 # fetchrow_hashref() can fail for any number of reasons (e.g.,
597 # database server crash), not just because no items match the
599 my $sth2 = $dbh->prepare(
600 "SELECT * FROM issues
601 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
606 $sth2->execute( $data->{'itemnumber'} );
607 if ( my $data2 = $sth2->fetchrow_hashref ) {
608 $data->{'date_due'} = $data2->{'date_due'};
609 $data->{'card'} = $data2->{'cardnumber'};
610 $data->{'borrower'} = $data2->{'borrowernumber'};
613 $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
618 # Find the last 3 people who borrowed this item.
619 $sth2 = $dbh->prepare(
620 "SELECT * FROM old_issues
621 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
623 ORDER BY returndate DESC,timestamp DESC"
626 $sth2->execute( $data->{'itemnumber'} );
627 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
628 { # FIXME : error if there is less than 3 pple borrowing this item
629 if ( my $data2 = $sth2->fetchrow_hashref ) {
630 $data->{"timestamp$i2"} = $data2->{'timestamp'};
631 $data->{"card$i2"} = $data2->{'cardnumber'};
632 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
637 $results[$i] = $data;
645 =head2 CanBookBeIssued
647 ( $issuingimpossible, $needsconfirmation ) =
648 CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
649 C<$duedatespec> is a C4::Dates object.
650 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
654 sub CanBookBeIssued {
655 my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
656 my %needsconfirmation; # filled with problems that needs confirmations
657 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
658 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
659 my $issue = GetItemIssue($item->{itemnumber});
660 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
661 $item->{'itemtype'}=$item->{'itype'};
662 my $dbh = C4::Context->dbh;
665 # DUE DATE is OK ? -- should already have checked.
667 #$issuingimpossible{INVALID_DATE} = 1 unless ($duedate);
672 if ( $borrower->{'category_type'} eq 'X' && ( $item->{barcode} )) {
673 # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
674 &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
675 return( { STATS => 1 }, {});
677 if ( $borrower->{flags}->{GNA} ) {
678 $issuingimpossible{GNA} = 1;
680 if ( $borrower->{flags}->{'LOST'} ) {
681 $issuingimpossible{CARD_LOST} = 1;
683 if ( $borrower->{flags}->{'DBARRED'} ) {
684 $issuingimpossible{DEBARRED} = 1;
686 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
687 $issuingimpossible{EXPIRED} = 1;
689 my @expirydate= split /-/,$borrower->{'dateexpiry'};
690 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
691 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
692 $issuingimpossible{EXPIRED} = 1;
701 C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
702 if ( C4::Context->preference("IssuingInProcess") ) {
703 my $amountlimit = C4::Context->preference("noissuescharge");
704 if ( $amount > $amountlimit && !$inprocess ) {
705 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
707 elsif ( $amount <= $amountlimit && !$inprocess ) {
708 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
713 $needsconfirmation{DEBT} = $amount;
718 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
720 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
721 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
726 unless ( $item->{barcode} ) {
727 $issuingimpossible{UNKNOWN_BARCODE} = 1;
729 if ( $item->{'notforloan'}
730 && $item->{'notforloan'} > 0 )
732 $issuingimpossible{NOT_FOR_LOAN} = 1;
734 elsif ( !$item->{'notforloan'} ){
735 # we have to check itemtypes.notforloan also
736 if (C4::Context->preference('item-level_itypes')){
737 # this should probably be a subroutine
738 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
739 $sth->execute($item->{'itemtype'});
740 my $notforloan=$sth->fetchrow_hashref();
742 if ($notforloan->{'notforloan'} == 1){
743 $issuingimpossible{NOT_FOR_LOAN} = 1;
746 elsif ($biblioitem->{'notforloan'} == 1){
747 $issuingimpossible{NOT_FOR_LOAN} = 1;
750 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
752 $issuingimpossible{WTHDRAWN} = 1;
754 if ( $item->{'restricted'}
755 && $item->{'restricted'} == 1 )
757 $issuingimpossible{RESTRICTED} = 1;
759 if ( C4::Context->preference("IndependantBranches") ) {
760 my $userenv = C4::Context->userenv;
761 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
762 $issuingimpossible{NOTSAMEBRANCH} = 1
763 if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
768 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
770 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
773 # Already issued to current borrower. Ask whether the loan should
775 my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
776 $borrower->{'borrowernumber'},
777 $item->{'itemnumber'}
779 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
780 $issuingimpossible{NO_MORE_RENEWALS} = 1;
783 $needsconfirmation{RENEW_ISSUE} = 1;
786 elsif ($issue->{borrowernumber}) {
788 # issued to someone else
789 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
791 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
792 $needsconfirmation{ISSUED_TO_ANOTHER} =
793 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
796 # See if the item is on reserve.
797 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
799 my $resbor = $res->{'borrowernumber'};
800 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
801 my $branches = GetBranches();
802 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
803 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
805 # The item is on reserve and waiting, but has been
806 # reserved by some other patron.
807 $needsconfirmation{RESERVE_WAITING} =
808 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
810 elsif ( $restype eq "Reserved" ) {
811 # The item is on reserve for someone else.
812 $needsconfirmation{RESERVED} =
813 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
816 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
817 if ( $borrower->{'categorycode'} eq 'W' ) {
819 return ( \%emptyhash, \%needsconfirmation );
822 return ( \%issuingimpossible, \%needsconfirmation );
827 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
829 &AddIssue($borrower,$barcode,$date)
833 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
835 =item C<$barcode> is the bar code of the book being issued.
837 =item C<$date> contains the max date of return. calculated if empty.
839 AddIssue does the following things :
840 - step 01: check that there is a borrowernumber & a barcode provided
841 - check for RENEWAL (book issued & being issued to the same patron)
842 - renewal YES = Calculate Charge & renew
844 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
846 - fill reserve if reserve to this patron
847 - cancel reserve or not, otherwise
848 * TRANSFERT PENDING ?
849 - complete the transfert
857 my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
858 my $dbh = C4::Context->dbh;
859 my $barcodecheck=CheckValidBarcode($barcode);
860 if ($borrower and $barcode and $barcodecheck ne '0'){
861 # find which item we issue
862 my $item = GetItem('', $barcode);
866 # Get which branchcode we need
867 if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
868 $branch = C4::Context->userenv->{'branch'};
870 elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
871 $branch = $borrower->{'branchcode'};
875 $branch = $item->{'homebranch'};
878 # get actual issuing if there is one
879 my $actualissue = GetItemIssue( $item->{itemnumber});
881 # get biblioinformation for this item
882 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
885 # check if we just renew the issue.
887 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
889 $borrower->{'borrowernumber'},
890 $item->{'itemnumber'},
898 if ( $actualissue->{borrowernumber}) {
899 # This book is currently on loan, but not to the person
900 # who wants to borrow it now. mark it returned before issuing to the new borrower
903 C4::Context->userenv->{'branch'}
907 # See if the item is on reserve.
908 my ( $restype, $res ) =
909 C4::Reserves::CheckReserves( $item->{'itemnumber'} );
911 my $resbor = $res->{'borrowernumber'};
912 if ( $resbor eq $borrower->{'borrowernumber'} ) {
914 # The item is reserved by the current patron
915 ModReserveFill($res);
917 elsif ( $restype eq "Waiting" ) {
920 # The item is on reserve and waiting, but has been
921 # reserved by some other patron.
922 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
923 my $branches = GetBranches();
925 $branches->{ $res->{'branchcode'} }->{'branchname'};
927 elsif ( $restype eq "Reserved" ) {
930 # The item is reserved by someone else.
931 my ( $resborrower, $flags ) =
932 GetMemberDetails( $resbor, 0 );
933 my $branches = GetBranches();
934 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
935 if ($cancelreserve) { # cancel reserves on this item
936 CancelReserve( 0, $res->{'itemnumber'},
937 $res->{'borrowernumber'} );
940 if ($cancelreserve) {
941 CancelReserve( $res->{'biblionumber'}, 0,
942 $res->{'borrowernumber'} );
945 # set waiting reserve to first in reserve queue as book isn't waiting now
947 $res->{'biblionumber'},
948 $res->{'borrowernumber'},
954 # Starting process for transfer job (checking transfert and validate it if we have one)
955 my ($datesent) = GetTransfers($item->{'itemnumber'});
957 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
960 "UPDATE branchtransfers
961 SET datearrived = now(),
963 comments = 'Forced branchtransfer'
964 WHERE itemnumber= ? AND datearrived IS NULL"
966 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
970 # Record in the database the fact that the book was issued.
974 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
981 my $itype=(C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ;
982 my $loanlength = GetLoanLength(
983 $borrower->{'categorycode'},
987 $dateduef = CalcDateDue(C4::Dates->new(),$loanlength,$branch);
988 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
989 if ( C4::Context->preference('ReturnBeforeExpiry') && $dateduef->output('iso') gt $borrower->{dateexpiry} ) {
990 $dateduef = C4::Dates->new($borrower->{dateexpiry},'iso');
994 $borrower->{'borrowernumber'},
995 $item->{'itemnumber'},
996 strftime( "%Y-%m-%d", localtime ),$dateduef->output('iso'), C4::Context->userenv->{'branch'}
1000 ModItem({ issues => $item->{'issues'},
1001 holdingbranch => C4::Context->userenv->{'branch'},
1003 datelastborrowed => C4::Dates->new()->output('iso'),
1004 onloan => $dateduef->output('iso'),
1005 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1006 ModDateLastSeen( $item->{'itemnumber'} );
1008 # If it costs to borrow this book, charge it to the patron's account.
1009 my ( $charge, $itemtype ) = GetIssuingCharges(
1010 $item->{'itemnumber'},
1011 $borrower->{'borrowernumber'}
1013 if ( $charge > 0 ) {
1015 $item->{'itemnumber'},
1016 $borrower->{'borrowernumber'}, $charge
1018 $item->{'charge'} = $charge;
1021 # Record the fact that this book was issued.
1023 C4::Context->userenv->{'branch'},
1025 '', $item->{'itemnumber'},
1026 $item->{'itemtype'}, $borrower->{'borrowernumber'}
1030 logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'})
1031 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=? and issuelength is not null"
1051 # warn "in get loan lenght $borrowertype $itemtype $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)
1098 =head2 GetIssuingRule
1100 FIXME - This is a copy-paste of GetLoanLength
1101 as a stop-gap. Do not wish to change API for GetLoanLength
1102 this close to release, however, Overdues::GetIssuingRules is broken.
1104 Get the issuing rule for an itemtype, a borrower type and a branch
1105 Returns a hashref from the issuingrules table.
1107 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1111 sub GetIssuingRule {
1112 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1113 my $dbh = C4::Context->dbh;
1114 my $sth = $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null" );
1117 $sth->execute( $borrowertype, $itemtype, $branchcode );
1118 $irule = $sth->fetchrow_hashref;
1119 return $irule if defined($irule) ;
1121 $sth->execute( $borrowertype, $itemtype, "*" );
1122 $irule = $sth->fetchrow_hashref;
1123 return $irule if defined($irule) ;
1125 $sth->execute( $borrowertype, "*", $branchcode );
1126 $irule = $sth->fetchrow_hashref;
1127 return $irule if defined($irule) ;
1129 $sth->execute( "*", $itemtype, $branchcode );
1130 $irule = $sth->fetchrow_hashref;
1131 return $irule if defined($irule) ;
1133 $sth->execute( $borrowertype, "*", "*" );
1134 $irule = $sth->fetchrow_hashref;
1135 return $irule if defined($irule) ;
1137 $sth->execute( "*", "*", $branchcode );
1138 $irule = $sth->fetchrow_hashref;
1139 return $irule if defined($irule) ;
1141 $sth->execute( "*", $itemtype, "*" );
1142 $irule = $sth->fetchrow_hashref;
1143 return $irule if defined($irule) ;
1145 $sth->execute( "*", "*", "*" );
1146 $irule = $sth->fetchrow_hashref;
1147 return $irule if defined($irule) ;
1149 # if no rule matches,
1155 ($doreturn, $messages, $iteminformation, $borrower) =
1156 &AddReturn($barcode, $branch, $exemptfine, $dropbox);
1160 C<$barcode> is the bar code of the book being returned. C<$branch> is
1161 the code of the branch where the book is being returned. C<$exemptfine>
1162 indicates that overdue charges for the item will be removed. C<$dropbox>
1163 indicates that the check-in date is assumed to be yesterday. If overdue
1164 charges are applied and C<$dropbox> is true, the last charge will be removed.
1166 C<&AddReturn> returns a list of four items:
1168 C<$doreturn> is true iff the return succeeded.
1170 C<$messages> is a reference-to-hash giving the reason for failure:
1176 No item with this barcode exists. The value is C<$barcode>.
1180 The book is not currently on loan. The value is C<$barcode>.
1182 =item C<IsPermanent>
1184 The book's home branch is a permanent collection. If you have borrowed
1185 this book, you are not allowed to return it. The value is the code for
1186 the book's home branch.
1190 This book has been withdrawn/cancelled. The value should be ignored.
1194 The item was reserved. The value is a reference-to-hash whose keys are
1195 fields from the reserves table of the Koha database, and
1196 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1197 either C<Waiting>, C<Reserved>, or 0.
1201 C<$borrower> is a reference-to-hash, giving information about the
1202 patron who last borrowed the book.
1207 my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1208 my $dbh = C4::Context->dbh;
1212 my $validTransfert = 0;
1213 my $reserveDone = 0;
1215 # get information on item
1216 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1217 my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1218 # use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);
1219 unless ($iteminformation->{'itemnumber'} ) {
1220 $messages->{'BadBarcode'} = $barcode;
1224 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1225 $messages->{'NotIssued'} = $barcode;
1226 # even though item is not on loan, it may still
1227 # be transferred; therefore, get current branch information
1228 my $curr_iteminfo = GetItem($iteminformation->{'itemnumber'});
1229 $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
1230 $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
1234 # check if the book is in a permanent collection....
1235 my $hbr = $iteminformation->{C4::Context->preference("HomeOrHoldingBranch")};
1236 my $branches = GetBranches();
1237 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1238 $messages->{'IsPermanent'} = $hbr;
1241 # if independent branches are on and returning to different branch, refuse the return
1242 if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1243 $messages->{'Wrongbranch'} = 1;
1247 # check that the book has been cancelled
1248 if ( $iteminformation->{'wthdrawn'} ) {
1249 $messages->{'wthdrawn'} = 1;
1253 # new op dev : if the book returned in an other branch update the holding branch
1255 # update issues, thereby returning book (should push this out into another subroutine
1256 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1258 # case of a return of document (deal with issues and holdingbranch)
1262 # don't allow dropbox mode to create an invalid entry in issues ( issuedate > returndate)
1263 undef($dropbox) if ( $iteminformation->{'issuedate'} eq C4::Dates->today('iso') );
1265 MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'},$dropbox);
1266 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1269 # continue to deal with returns cases, but not only if we have an issue
1271 # the holdingbranch is updated if the document is returned in an other location .
1272 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1273 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1274 # reload iteminformation holdingbranch with the userenv value
1275 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1277 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1278 ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1280 if ($iteminformation->{borrowernumber}){
1281 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1283 # fix up the accounts.....
1284 if ( $iteminformation->{'itemlost'} ) {
1285 $messages->{'WasLost'} = 1;
1288 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1289 # check if we have a transfer for this document
1290 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1292 # if we have a transfer to do, we update the line of transfers with the datearrived
1294 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1297 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1299 $sth->execute( $iteminformation->{'itemnumber'} );
1301 # 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'
1302 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1305 $messages->{'WrongTransfer'} = $tobranch;
1306 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1308 $validTransfert = 1;
1311 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1312 # fix up the accounts.....
1313 if ($iteminformation->{'itemlost'}) {
1314 FixAccountForLostAndReturned($iteminformation, $borrower);
1315 $messages->{'WasLost'} = 1;
1317 # fix up the overdues in accounts...
1318 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1319 $iteminformation->{'itemnumber'}, $exemptfine, $dropbox );
1321 # find reserves.....
1322 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1323 my ( $resfound, $resrec ) =
1324 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1326 $resrec->{'ResFound'} = $resfound;
1327 $messages->{'ResFound'} = $resrec;
1332 # Record the fact that this book was returned.
1334 $branch, 'return', '0', '',
1335 $iteminformation->{'itemnumber'},
1336 $biblio->{'itemtype'},
1337 $borrower->{'borrowernumber'}
1340 logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'})
1341 if C4::Context->preference("ReturnLog");
1343 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1344 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1346 if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1347 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1348 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1349 $messages->{'WasTransfered'} = 1;
1352 $messages->{'NeedsTransfer'} = 1;
1356 return ( $doreturn, $messages, $iteminformation, $borrower );
1359 =head2 MarkIssueReturned
1363 MarkIssueReturned($borrowernumber, $itemnumber);
1367 Unconditionally marks an issue as being returned by
1368 moving the C<issues> row to C<old_issues> and
1369 setting C<returndate> to the current date, or
1370 yesterday if C<dropbox> is true. Assumes you've
1371 already checked that yesterday > issuedate.
1373 Ideally, this function would be internal to C<C4::Circulation>,
1374 not exported, but it is currently needed by one
1375 routine in C<C4::Accounts>.
1379 sub MarkIssueReturned {
1380 my ($borrowernumber, $itemnumber, $dropbox) = @_;
1381 my $dbh = C4::Context->dbh;
1382 my $query = "UPDATE issues SET returndate=";
1383 my @bind = ($borrowernumber,$itemnumber);
1385 my @datearr = localtime( time() );
1386 my @yesterdayarr = Add_Delta_Days( $datearr[5] + 1900 , $datearr[4] + 1, $datearr[3] , -1 );
1387 unshift @bind, sprintf("%0.4d-%0.2d-%0.2d",@yesterdayarr) ;
1390 $query .= " now() ";
1392 $query .= " WHERE borrowernumber = ? AND itemnumber = ?";
1394 my $sth_upd = $dbh->prepare($query);
1395 $sth_upd->execute(@bind);
1396 my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues
1397 WHERE borrowernumber = ?
1398 AND itemnumber = ?");
1399 $sth_copy->execute($borrowernumber, $itemnumber);
1400 my $sth_del = $dbh->prepare("DELETE FROM issues
1401 WHERE borrowernumber = ?
1402 AND itemnumber = ?");
1403 $sth_del->execute($borrowernumber, $itemnumber);
1406 =head2 FixOverduesOnReturn
1408 &FixOverduesOnReturn($brn,$itm, $exemptfine);
1410 C<$brn> borrowernumber
1414 internal function, called only by AddReturn
1418 sub FixOverduesOnReturn {
1419 my ( $borrowernumber, $item, $exemptfine ) = @_;
1420 my $dbh = C4::Context->dbh;
1422 # check for overdue fine
1425 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1427 $sth->execute( $borrowernumber, $item );
1429 # alter fine to show that the book has been returned
1431 if ($data = $sth->fetchrow_hashref) {
1432 my $uquery =($exemptfine)? "update accountlines set accounttype='FFOR', amountoutstanding=0":"update accountlines set accounttype='F' ";
1433 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1434 my $usth = $dbh->prepare($uquery);
1435 $usth->execute($borrowernumber,$item ,$data->{'accountno'});
1443 =head2 FixAccountForLostAndReturned
1445 &FixAccountForLostAndReturned($iteminfo,$borrower);
1447 Calculates the charge for a book lost and returned (Not exported & used only once)
1449 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1451 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1453 Internal function, called by AddReturn
1457 sub FixAccountForLostAndReturned {
1458 my ($iteminfo, $borrower) = @_;
1460 my $dbh = C4::Context->dbh;
1461 my $itm = $iteminfo->{'itemnumber'};
1462 # check for charge made for lost book
1463 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1464 $sth->execute($itm);
1465 if (my $data = $sth->fetchrow_hashref) {
1466 # writeoff this amount
1468 my $amount = $data->{'amount'};
1469 my $acctno = $data->{'accountno'};
1471 if ($data->{'amountoutstanding'} == $amount) {
1472 $offset = $data->{'amount'};
1475 $offset = $amount - $data->{'amountoutstanding'};
1476 $amountleft = $data->{'amountoutstanding'} - $amount;
1478 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1479 WHERE (borrowernumber = ?)
1480 AND (itemnumber = ?) AND (accountno = ?) ");
1481 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1483 #check if any credit is left if so writeoff other accounts
1484 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1485 if ($amountleft < 0){
1488 if ($amountleft > 0){
1489 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1490 AND (amountoutstanding >0) ORDER BY date");
1491 $msth->execute($data->{'borrowernumber'});
1492 # offset transactions
1495 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1496 if ($accdata->{'amountoutstanding'} < $amountleft) {
1498 $amountleft -= $accdata->{'amountoutstanding'};
1500 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1503 my $thisacct = $accdata->{'accountno'};
1504 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1505 WHERE (borrowernumber = ?)
1506 AND (accountno=?)");
1507 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1509 $usth = $dbh->prepare("INSERT INTO accountoffsets
1510 (borrowernumber, accountno, offsetaccount, offsetamount)
1513 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1518 if ($amountleft > 0){
1521 my $desc="Item Returned ".$iteminfo->{'barcode'};
1522 $usth = $dbh->prepare("INSERT INTO accountlines
1523 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1524 VALUES (?,?,now(),?,?,'CR',?)");
1525 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1527 $usth = $dbh->prepare("INSERT INTO accountoffsets
1528 (borrowernumber, accountno, offsetaccount, offsetamount)
1530 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1532 ModItem({ paidfor => '' }, undef, $itm);
1540 $issues = &GetItemIssue($itemnumber);
1542 Returns patrons currently having a book. nothing if item is not issued atm
1544 C<$itemnumber> is the itemnumber
1546 Returns an array of hashes
1551 my ( $itemnumber) = @_;
1552 return unless $itemnumber;
1553 my $dbh = C4::Context->dbh;
1557 my $today = POSIX::strftime("%Y%m%d", localtime);
1559 my $sth = $dbh->prepare(
1560 "SELECT * FROM issues
1561 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1563 issues.itemnumber=?");
1564 $sth->execute($itemnumber);
1565 my $data = $sth->fetchrow_hashref;
1566 my $datedue = $data->{'date_due'};
1568 if ( $datedue < $today ) {
1569 $data->{'overdue'} = 1;
1571 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1576 =head2 GetItemIssues
1578 $issues = &GetItemIssues($itemnumber, $history);
1580 Returns patrons that have issued a book
1582 C<$itemnumber> is the itemnumber
1583 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1585 Returns an array of hashes
1590 my ( $itemnumber,$history ) = @_;
1591 my $dbh = C4::Context->dbh;
1595 my $today = POSIX::strftime("%Y%m%d", localtime);
1597 my $sql = "SELECT * FROM issues
1598 JOIN borrowers USING (borrowernumber)
1599 JOIN items USING (itemnumber)
1600 WHERE issues.itemnumber = ? ";
1603 SELECT * FROM old_issues
1604 LEFT JOIN borrowers USING (borrowernumber)
1605 JOIN items USING (itemnumber)
1606 WHERE old_issues.itemnumber = ? ";
1608 $sql .= "ORDER BY date_due DESC";
1609 my $sth = $dbh->prepare($sql);
1611 $sth->execute($itemnumber, $itemnumber);
1613 $sth->execute($itemnumber);
1615 while ( my $data = $sth->fetchrow_hashref ) {
1616 my $datedue = $data->{'date_due'};
1618 if ( $datedue < $today ) {
1619 $data->{'overdue'} = 1;
1621 my $itemnumber = $data->{'itemnumber'};
1622 push @GetItemIssues, $data;
1625 return ( \@GetItemIssues );
1628 =head2 GetBiblioIssues
1630 $issues = GetBiblioIssues($biblionumber);
1632 this function get all issues from a biblionumber.
1635 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1636 tables issues and the firstname,surname & cardnumber from borrowers.
1640 sub GetBiblioIssues {
1641 my $biblionumber = shift;
1642 return undef unless $biblionumber;
1643 my $dbh = C4::Context->dbh;
1645 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1647 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1648 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1649 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1650 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1651 WHERE biblio.biblionumber = ?
1653 SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1655 LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1656 LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1657 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1658 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1659 WHERE biblio.biblionumber = ?
1662 my $sth = $dbh->prepare($query);
1663 $sth->execute($biblionumber, $biblionumber);
1666 while ( my $data = $sth->fetchrow_hashref ) {
1667 push @issues, $data;
1672 =head2 CanBookBeRenewed
1674 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber);
1676 Find out whether a borrowed item may be renewed.
1678 C<$dbh> is a DBI handle to the Koha database.
1680 C<$borrowernumber> is the borrower number of the patron who currently
1681 has the item on loan.
1683 C<$itemnumber> is the number of the item to renew.
1685 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1686 item must currently be on loan to the specified borrower; renewals
1687 must be allowed for the item's type; and the borrower must not have
1688 already renewed the loan. $error will contain the reason the renewal can not proceed
1692 sub CanBookBeRenewed {
1694 # check renewal status
1695 my ( $borrowernumber, $itemnumber ) = @_;
1696 my $dbh = C4::Context->dbh;
1701 # Look in the issues table for this item, lent to this borrower,
1702 # and not yet returned.
1704 # FIXME - I think this function could be redone to use only one SQL call.
1705 my $sth1 = $dbh->prepare(
1706 "SELECT * FROM issues
1707 WHERE borrowernumber = ?
1710 $sth1->execute( $borrowernumber, $itemnumber );
1711 if ( my $data1 = $sth1->fetchrow_hashref ) {
1713 # Found a matching item
1715 # See if this item may be renewed. This query is convoluted
1716 # because it's a bit messy: given the item number, we need to find
1717 # the biblioitem, which gives us the itemtype, which tells us
1718 # whether it may be renewed.
1719 my $query = "SELECT renewalsallowed FROM items ";
1720 $query .= (C4::Context->preference('item-level_itypes'))
1721 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1722 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1723 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1724 $query .= "WHERE items.itemnumber = ?";
1725 my $sth2 = $dbh->prepare($query);
1726 $sth2->execute($itemnumber);
1727 if ( my $data2 = $sth2->fetchrow_hashref ) {
1728 $renews = $data2->{'renewalsallowed'};
1730 if ( $renews && $renews > $data1->{'renewals'} ) {
1737 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1745 return ($renewokay,$error);
1750 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue]);
1754 C<$borrowernumber> is the borrower number of the patron who currently
1757 C<$itemnumber> is the number of the item to renew.
1759 C<$branch> is the library branch. Defaults to the homebranch of the ITEM.
1761 C<$datedue> can be a C4::Dates object used to set the due date.
1763 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
1764 from the book's item type.
1769 my $borrowernumber = shift or return undef;
1770 my $itemnumber = shift or return undef;
1771 my $item = GetItem($itemnumber) or return undef;
1772 my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
1773 my $branch = (@_) ? shift : $item->{homebranch}; # opac-renew doesn't send branch
1775 # If the due date wasn't specified, calculate it by adding the
1776 # book's loan length to today's date.
1777 unless (@_ and $datedue = shift and $datedue->output('iso')) {
1779 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1780 my $loanlength = GetLoanLength(
1781 $borrower->{'categorycode'},
1782 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1783 $item->{homebranch} # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
1785 #FIXME -- use circControl?
1786 $datedue = CalcDateDue(C4::Dates->new(),$loanlength,$branch); # this branch is the transactional branch.
1787 # The question of whether to use item's homebranch calendar is open.
1790 my $dbh = C4::Context->dbh;
1791 # Find the issues record for this book
1793 $dbh->prepare("SELECT * FROM issues
1794 WHERE borrowernumber=?
1797 $sth->execute( $borrowernumber, $itemnumber );
1798 my $issuedata = $sth->fetchrow_hashref;
1801 # Update the issues record to have the new due date, and a new count
1802 # of how many times it has been renewed.
1803 my $renews = $issuedata->{'renewals'} + 1;
1804 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1805 WHERE borrowernumber=?
1808 $sth->execute( $datedue->output('iso'), $renews, $borrowernumber, $itemnumber );
1811 # Update the renewal count on the item, and tell zebra to reindex
1812 $renews = $biblio->{'renewals'} + 1;
1813 ModItem({ renewals => $renews }, $biblio->{'biblionumber'}, $itemnumber);
1815 # Charge a new rental fee, if applicable?
1816 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1817 if ( $charge > 0 ) {
1818 my $accountno = getnextacctno( $borrowernumber );
1819 my $item = GetBiblioFromItemNumber($itemnumber);
1820 $sth = $dbh->prepare(
1821 "INSERT INTO accountlines
1823 borrowernumber, accountno, amount,
1825 accounttype, amountoutstanding, itemnumber
1827 VALUES (now(),?,?,?,?,?,?,?)"
1829 $sth->execute( $borrowernumber, $accountno, $charge,
1830 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1831 'Rent', $charge, $itemnumber );
1835 UpdateStats( $branch, 'renew', $charge, '', $itemnumber );
1839 # check renewal status
1840 my ($bornum,$itemno)=@_;
1841 my $dbh = C4::Context->dbh;
1843 my $renewsallowed = 0;
1845 # Look in the issues table for this item, lent to this borrower,
1846 # and not yet returned.
1848 # FIXME - I think this function could be redone to use only one SQL call.
1849 my $sth = $dbh->prepare("select * from issues
1850 where (borrowernumber = ?)
1851 and (itemnumber = ?)");
1852 $sth->execute($bornum,$itemno);
1853 my $data = $sth->fetchrow_hashref;
1854 $renewcount = $data->{'renewals'} if $data->{'renewals'};
1856 my $query = "SELECT renewalsallowed FROM items ";
1857 $query .= (C4::Context->preference('item-level_itypes'))
1858 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1859 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1860 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1861 $query .= "WHERE items.itemnumber = ?";
1862 my $sth2 = $dbh->prepare($query);
1863 $sth2->execute($itemno);
1864 my $data2 = $sth2->fetchrow_hashref();
1865 $renewsallowed = $data2->{'renewalsallowed'};
1866 $renewsleft = $renewsallowed - $renewcount;
1867 return ($renewcount,$renewsallowed,$renewsleft);
1870 =head2 GetIssuingCharges
1872 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1874 Calculate how much it would cost for a given patron to borrow a given
1875 item, including any applicable discounts.
1877 C<$itemnumber> is the item number of item the patron wishes to borrow.
1879 C<$borrowernumber> is the patron's borrower number.
1881 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1882 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1887 sub GetIssuingCharges {
1889 # calculate charges due
1890 my ( $itemnumber, $borrowernumber ) = @_;
1892 my $dbh = C4::Context->dbh;
1895 # Get the book's item type and rental charge (via its biblioitem).
1896 my $qcharge = "SELECT itemtypes.itemtype,rentalcharge FROM items
1897 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1898 $qcharge .= (C4::Context->preference('item-level_itypes'))
1899 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1900 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1902 $qcharge .= "WHERE items.itemnumber =?";
1904 my $sth1 = $dbh->prepare($qcharge);
1905 $sth1->execute($itemnumber);
1906 if ( my $data1 = $sth1->fetchrow_hashref ) {
1907 $item_type = $data1->{'itemtype'};
1908 $charge = $data1->{'rentalcharge'};
1909 my $q2 = "SELECT rentaldiscount FROM borrowers
1910 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1911 WHERE borrowers.borrowernumber = ?
1912 AND issuingrules.itemtype = ?";
1913 my $sth2 = $dbh->prepare($q2);
1914 $sth2->execute( $borrowernumber, $item_type );
1915 if ( my $data2 = $sth2->fetchrow_hashref ) {
1916 my $discount = $data2->{'rentaldiscount'};
1917 if ( $discount eq 'NULL' ) {
1920 $charge = ( $charge * ( 100 - $discount ) ) / 100;
1926 return ( $charge, $item_type );
1929 =head2 AddIssuingCharge
1931 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1935 sub AddIssuingCharge {
1936 my ( $itemnumber, $borrowernumber, $charge ) = @_;
1937 my $dbh = C4::Context->dbh;
1938 my $nextaccntno = getnextacctno( $borrowernumber );
1940 INSERT INTO accountlines
1941 (borrowernumber, itemnumber, accountno,
1942 date, amount, description, accounttype,
1944 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1946 my $sth = $dbh->prepare($query);
1947 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1953 GetTransfers($itemnumber);
1958 my ($itemnumber) = @_;
1960 my $dbh = C4::Context->dbh;
1966 FROM branchtransfers
1967 WHERE itemnumber = ?
1968 AND datearrived IS NULL
1970 my $sth = $dbh->prepare($query);
1971 $sth->execute($itemnumber);
1972 my @row = $sth->fetchrow_array();
1978 =head2 GetTransfersFromTo
1980 @results = GetTransfersFromTo($frombranch,$tobranch);
1982 Returns the list of pending transfers between $from and $to branch
1986 sub GetTransfersFromTo {
1987 my ( $frombranch, $tobranch ) = @_;
1988 return unless ( $frombranch && $tobranch );
1989 my $dbh = C4::Context->dbh;
1991 SELECT itemnumber,datesent,frombranch
1992 FROM branchtransfers
1995 AND datearrived IS NULL
1997 my $sth = $dbh->prepare($query);
1998 $sth->execute( $frombranch, $tobranch );
2001 while ( my $data = $sth->fetchrow_hashref ) {
2002 push @gettransfers, $data;
2005 return (@gettransfers);
2008 =head2 DeleteTransfer
2010 &DeleteTransfer($itemnumber);
2014 sub DeleteTransfer {
2015 my ($itemnumber) = @_;
2016 my $dbh = C4::Context->dbh;
2017 my $sth = $dbh->prepare(
2018 "DELETE FROM branchtransfers
2020 AND datearrived IS NULL "
2022 $sth->execute($itemnumber);
2026 =head2 AnonymiseIssueHistory
2028 $rows = AnonymiseIssueHistory($borrowernumber,$date)
2030 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
2031 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
2033 return the number of affected rows.
2037 sub AnonymiseIssueHistory {
2039 my $borrowernumber = shift;
2040 my $dbh = C4::Context->dbh;
2043 SET borrowernumber = NULL
2044 WHERE returndate < '".$date."'
2045 AND borrowernumber IS NOT NULL
2047 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
2048 my $rows_affected = $dbh->do($query);
2049 return $rows_affected;
2052 =head2 updateWrongTransfer
2054 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
2056 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
2060 sub updateWrongTransfer {
2061 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2062 my $dbh = C4::Context->dbh;
2063 # first step validate the actual line of transfert .
2066 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2068 $sth->execute($FromLibrary,$itemNumber);
2071 # second step create a new line of branchtransfer to the right location .
2072 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2074 #third step changing holdingbranch of item
2075 UpdateHoldingbranch($FromLibrary,$itemNumber);
2078 =head2 UpdateHoldingbranch
2080 $items = UpdateHoldingbranch($branch,$itmenumber);
2081 Simple methode for updating hodlingbranch in items BDD line
2085 sub UpdateHoldingbranch {
2086 my ( $branch,$itemnumber ) = @_;
2087 ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2092 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2093 this function calculates the due date given the loan length ,
2094 checking against the holidays calendar as per the 'useDaysMode' syspref.
2095 C<$startdate> = C4::Dates object representing start date of loan period (assumed to be today)
2096 C<$branch> = location whose calendar to use
2097 C<$loanlength> = loan length prior to adjustment
2101 my ($startdate,$loanlength,$branch) = @_;
2102 if(C4::Context->preference('useDaysMode') eq 'Days') { # ignoring calendar
2103 my $datedue = time + ($loanlength) * 86400;
2104 #FIXME - assumes now even though we take a startdate
2105 my @datearr = localtime($datedue);
2106 return C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2108 my $calendar = C4::Calendar->new( branchcode => $branch );
2109 my $datedue = $calendar->addDate($startdate, $loanlength);
2114 =head2 CheckValidDatedue
2115 This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2116 To be replaced by CalcDateDue() once C4::Calendar use is tested.
2118 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2119 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2120 C<$date_due> = returndate calculate with no day check
2121 C<$itemnumber> = itemnumber
2122 C<$branchcode> = location of issue (affected by 'CircControl' syspref)
2123 C<$loanlength> = loan length prior to adjustment
2126 sub CheckValidDatedue {
2127 my ($date_due,$itemnumber,$branchcode)=@_;
2128 my @datedue=split('-',$date_due->output('iso'));
2129 my $years=$datedue[0];
2130 my $month=$datedue[1];
2131 my $day=$datedue[2];
2132 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2134 for (my $i=0;$i<2;$i++){
2135 $dow=Day_of_Week($years,$month,$day);
2136 ($dow=0) if ($dow>6);
2137 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2138 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2139 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2140 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2142 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2145 my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2150 =head2 CheckRepeatableHolidays
2152 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2153 this function checks if the date due is a repeatable holiday
2154 C<$date_due> = returndate calculate with no day check
2155 C<$itemnumber> = itemnumber
2156 C<$branchcode> = localisation of issue
2160 sub CheckRepeatableHolidays{
2161 my($itemnumber,$week_day,$branchcode)=@_;
2162 my $dbh = C4::Context->dbh;
2163 my $query = qq|SELECT count(*)
2164 FROM repeatable_holidays
2167 my $sth = $dbh->prepare($query);
2168 $sth->execute($branchcode,$week_day);
2169 my $result=$sth->fetchrow;
2175 =head2 CheckSpecialHolidays
2177 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2178 this function check if the date is a special holiday
2179 C<$years> = the years of datedue
2180 C<$month> = the month of datedue
2181 C<$day> = the day of datedue
2182 C<$itemnumber> = itemnumber
2183 C<$branchcode> = localisation of issue
2187 sub CheckSpecialHolidays{
2188 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2189 my $dbh = C4::Context->dbh;
2190 my $query=qq|SELECT count(*)
2191 FROM `special_holidays`
2197 my $sth = $dbh->prepare($query);
2198 $sth->execute($years,$month,$day,$branchcode);
2199 my $countspecial=$sth->fetchrow ;
2201 return $countspecial;
2204 =head2 CheckRepeatableSpecialHolidays
2206 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2207 this function check if the date is a repeatble special holidays
2208 C<$month> = the month of datedue
2209 C<$day> = the day of datedue
2210 C<$itemnumber> = itemnumber
2211 C<$branchcode> = localisation of issue
2215 sub CheckRepeatableSpecialHolidays{
2216 my ($month,$day,$itemnumber,$branchcode) = @_;
2217 my $dbh = C4::Context->dbh;
2218 my $query=qq|SELECT count(*)
2219 FROM `repeatable_holidays`
2224 my $sth = $dbh->prepare($query);
2225 $sth->execute($month,$day,$branchcode);
2226 my $countspecial=$sth->fetchrow ;
2228 return $countspecial;
2233 sub CheckValidBarcode{
2235 my $dbh = C4::Context->dbh;
2236 my $query=qq|SELECT count(*)
2240 my $sth = $dbh->prepare($query);
2241 $sth->execute($barcode);
2242 my $exist=$sth->fetchrow ;
2253 Koha Developement team <info@koha.org>