1 package C4::Circulation;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
40 use POSIX qw(strftime);
41 use C4::Branch; # GetBranches
42 use C4::Log; # logaction
46 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,%EXPORT_TAGS);
48 # set the version for version checking
53 C4::Circulation - Koha circulation module
61 The functions in this module deal with circulation, issues, and
62 returns, as well as general information about the library.
63 Also deals with stocktaking.
71 # FIXME subs that should probably be elsewhere
77 # subs to deal with issuing a book
89 &AnonymiseIssueHistory
91 # subs to deal with returns
96 # subs to deal with transfers
105 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
106 # 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 ?
110 =head3 $str = &decode($chunk);
114 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
121 sub cuecatbarcodedecode {
124 my @fields = split( /\./, $barcode );
125 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
126 if ( $#results == 2 ) {
136 =head3 $str = &decode($chunk);
140 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
150 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
151 my @s = map { index( $seq, $_ ); } split( //, $encoded );
152 my $l = ( $#s + 1 ) % 4;
163 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
165 chr( ( $n >> 16 ) ^ 67 )
166 .chr( ( $n >> 8 & 255 ) ^ 67 )
167 .chr( ( $n & 255 ) ^ 67 );
170 $r = substr( $r, 0, length($r) - $l );
176 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
178 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
180 C<$newbranch> is the code for the branch to which the item should be transferred.
182 C<$barcode> is the barcode of the item to be transferred.
184 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
185 Otherwise, if an item is reserved, the transfer fails.
187 Returns three values:
191 is true if the transfer was successful.
195 is a reference-to-hash which may have any of the following keys:
201 There is no item in the catalog with the given barcode. The value is C<$barcode>.
205 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.
207 =item C<DestinationEqualsHolding>
209 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.
213 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.
217 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>.
219 =item C<WasTransferred>
221 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
228 my ( $tbr, $barcode, $ignoreRs ) = @_;
231 my $branches = GetBranches();
232 my $itemnumber = GetItemnumberFromBarcode( $barcode );
233 my $issue = GetItemIssue($itemnumber);
234 my $biblio = GetBiblioFromItemNumber($itemnumber);
237 if ( not $itemnumber ) {
238 $messages->{'BadBarcode'} = $barcode;
242 # get branches of book...
243 my $hbr = $biblio->{'homebranch'};
244 my $fbr = $biblio->{'holdingbranch'};
247 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
248 $messages->{'IsPermanent'} = $hbr;
251 # can't transfer book if is already there....
252 if ( $fbr eq $tbr ) {
253 $messages->{'DestinationEqualsHolding'} = 1;
257 # check if it is still issued to someone, return it...
258 if ($issue->{borrowernumber}) {
259 AddReturn( $barcode, $fbr );
260 $messages->{'WasReturned'} = $issue->{borrowernumber};
264 # That'll save a database query.
265 my ( $resfound, $resrec ) =
266 CheckReserves( $itemnumber );
267 if ( $resfound and not $ignoreRs ) {
268 $resrec->{'ResFound'} = $resfound;
270 # $messages->{'ResFound'} = $resrec;
274 #actually do the transfer....
276 ModItemTransfer( $itemnumber, $fbr, $tbr );
278 # don't need to update MARC anymore, we do it in batch now
279 $messages->{'WasTransfered'} = 1;
280 ModDateLastSeen( $itemnumber );
282 return ( $dotransfer, $messages, $biblio );
285 =head2 CanBookBeIssued
287 Check if a book can be issued.
289 my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($borrower,$barcode,$year,$month,$day);
293 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
295 =item C<$barcode> is the bar code of the book being issued.
297 =item C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
305 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
306 Possible values are :
312 sticky due date is invalid
316 borrower gone with no address
320 borrower declared it's card lost
326 =head3 UNKNOWN_BARCODE
340 item is restricted (set by ??)
342 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
343 Possible values are :
351 renewing, not issuing
353 =head3 ISSUED_TO_ANOTHER
355 issued to someone else.
359 reserved for someone else.
363 sticky due date is invalid
367 if the borrower borrows to much things
371 # check if a book can be issued.
375 my $borrower = shift;
376 my $biblionumber = shift;
378 my $cat_borrower = $borrower->{'categorycode'};
379 my $dbh = C4::Context->dbh;
381 # Get which branchcode we need
382 if (C4::Context->preference('CircControl') eq 'PickupLibary'){
383 $branch = C4::Context->userenv->{'branchcode'};
385 elsif (C4::Context->preference('CircControl') eq 'PatronLibary'){
386 $branch = $borrower->{'branchcode'};
390 $branch = $item->{'homebranch'};
392 my $type = (C4::Context->preference('item-level_itypes'))
393 ? $item->{'itype'} # item-level
394 : $item->{'itemtype'}; # biblio-level
398 'SELECT * FROM issuingrules
399 WHERE categorycode = ?
404 my $query2 = "SELECT COUNT(*) FROM issues i, biblioitems s1, items s2
405 WHERE i.borrowernumber = ?
406 AND i.returndate IS NULL
407 AND i.itemnumber = s2.itemnumber
408 AND s1.biblioitemnumber = s2.biblioitemnumber";
409 if (C4::Context->preference('item-level_itypes')){
410 $query2.=" AND s2.itype=? ";
412 $query2.=" AND s1.itemtype= ? ";
414 my $sth2= $dbh->prepare($query2);
417 'SELECT COUNT(*) FROM issues
418 WHERE borrowernumber = ?
419 AND returndate IS NULL'
423 # check the 3 parameters (branch / itemtype / category code
424 $sth->execute( $cat_borrower, $type, $branch );
425 my $result = $sth->fetchrow_hashref;
426 # warn "$cat_borrower, $type, $branch = ".Data::Dumper::Dumper($result);
428 if ( $result->{maxissueqty} ne '' ) {
429 # warn "checking on everything set";
430 $sth2->execute( $borrower->{'borrowernumber'}, $type );
431 my $alreadyissued = $sth2->fetchrow;
432 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
433 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/itemtype failed)" );
435 # now checking for total
436 $sth->execute( $cat_borrower, '', $branch );
437 my $result = $sth->fetchrow_hashref;
438 if ( $result->{maxissueqty} ne '*' ) {
439 $sth2->execute( $borrower->{'borrowernumber'}, $type );
440 my $alreadyissued = $sth2->fetchrow;
441 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
442 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/total failed)" );
447 # check the 2 parameters (branch / itemtype / default categorycode
448 $sth->execute( '*', $type, $branch );
449 $result = $sth->fetchrow_hashref;
450 # warn "*, $type, $branch = ".Data::Dumper::Dumper($result);
452 if ( $result->{maxissueqty} ne '' ) {
453 # warn "checking on 2 parameters (default categorycode)";
454 $sth2->execute( $borrower->{'borrowernumber'}, $type );
455 my $alreadyissued = $sth2->fetchrow;
456 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
457 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / itemtype failed)" );
459 # now checking for total
460 $sth->execute( '*', '*', $branch );
461 my $result = $sth->fetchrow_hashref;
462 if ( $result->{maxissueqty} ne '' ) {
463 $sth2->execute( $borrower->{'borrowernumber'}, $type );
464 my $alreadyissued = $sth2->fetchrow;
465 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
466 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / total failed)" );
471 # check the 1 parameters (default branch / itemtype / categorycode
472 $sth->execute( $cat_borrower, $type, '*' );
473 $result = $sth->fetchrow_hashref;
474 # warn "$cat_borrower, $type, * = ".Data::Dumper::Dumper($result);
476 if ( $result->{maxissueqty} ne '' ) {
477 # warn "checking on 1 parameter (default branch + categorycode)";
478 $sth2->execute( $borrower->{'borrowernumber'}, $type );
479 my $alreadyissued = $sth2->fetchrow;
480 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
481 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch/category/itemtype failed)" );
483 # now checking for total
484 $sth->execute( $cat_borrower, '*', '*' );
485 my $result = $sth->fetchrow_hashref;
486 if ( $result->{maxissueqty} ne '' ) {
487 $sth2->execute( $borrower->{'borrowernumber'}, $type );
488 my $alreadyissued = $sth2->fetchrow;
489 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
490 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / category / total failed)" );
495 # check the 0 parameters (default branch / itemtype / default categorycode
496 $sth->execute( '*', $type, '*' );
497 $result = $sth->fetchrow_hashref;
498 # warn "*, $type, * = ".Data::Dumper::Dumper($result);
500 if ( $result->{maxissueqty} ne '' ) {
501 # warn "checking on default branch and default categorycode";
502 $sth2->execute( $borrower->{'borrowernumber'}, $type );
503 my $alreadyissued = $sth2->fetchrow;
504 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
505 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / itemtype failed)" );
508 # now checking for total
509 $sth->execute( '*', '*', '*' );
510 $result = $sth->fetchrow_hashref;
511 if ( $result->{maxissueqty} ne '' ) {
512 warn "checking total";
513 $sth2->execute( $borrower->{'borrowernumber'}, $type );
514 my $alreadyissued = $sth2->fetchrow;
515 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
516 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / total failed)" );
520 # OK, the patron can issue !!!
526 @issues = &itemissues($biblioitemnumber, $biblio);
528 Looks up information about who has borrowed the bookZ<>(s) with the
529 given biblioitemnumber.
531 C<$biblio> is ignored.
533 C<&itemissues> returns an array of references-to-hash. The keys
534 include the fields from the C<items> table in the Koha database.
535 Additional keys include:
541 If the item is currently on loan, this gives the due date.
543 If the item is not on loan, then this is either "Available" or
544 "Cancelled", if the item has been withdrawn.
548 If the item is currently on loan, this gives the card number of the
549 patron who currently has the item.
551 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
553 These give the timestamp for the last three times the item was
556 =item C<card0>, C<card1>, C<card2>
558 The card number of the last three patrons who borrowed this item.
560 =item C<borrower0>, C<borrower1>, C<borrower2>
562 The borrower number of the last three patrons who borrowed this item.
570 my ( $bibitem, $biblio ) = @_;
571 my $dbh = C4::Context->dbh;
573 # FIXME - If this function die()s, the script will abort, and the
574 # user won't get anything; depending on how far the script has
575 # gotten, the user might get a blank page. It would be much better
576 # to at least print an error message. The easiest way to do this
577 # is to set $SIG{__DIE__}.
579 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
584 $sth->execute($bibitem) || die $sth->errstr;
586 while ( my $data = $sth->fetchrow_hashref ) {
588 # Find out who currently has this item.
589 # FIXME - Wouldn't it be better to do this as a left join of
590 # some sort? Currently, this code assumes that if
591 # fetchrow_hashref() fails, then the book is on the shelf.
592 # fetchrow_hashref() can fail for any number of reasons (e.g.,
593 # database server crash), not just because no items match the
595 my $sth2 = $dbh->prepare(
596 "SELECT * FROM issues
597 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
599 AND returndate IS NULL
603 $sth2->execute( $data->{'itemnumber'} );
604 if ( my $data2 = $sth2->fetchrow_hashref ) {
605 $data->{'date_due'} = $data2->{'date_due'};
606 $data->{'card'} = $data2->{'cardnumber'};
607 $data->{'borrower'} = $data2->{'borrowernumber'};
610 if ( $data->{'wthdrawn'} eq '1' ) {
611 $data->{'date_due'} = 'Cancelled';
614 $data->{'date_due'} = 'Available';
620 # Find the last 3 people who borrowed this item.
621 $sth2 = $dbh->prepare(
622 "SELECT * FROM issues
623 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
625 AND returndate IS NOT NULL
626 ORDER BY returndate DESC,timestamp DESC"
629 $sth2->execute( $data->{'itemnumber'} );
630 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
631 { # FIXME : error if there is less than 3 pple borrowing this item
632 if ( my $data2 = $sth2->fetchrow_hashref ) {
633 $data->{"timestamp$i2"} = $data2->{'timestamp'};
634 $data->{"card$i2"} = $data2->{'cardnumber'};
635 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
640 $results[$i] = $data;
648 =head2 CanBookBeIssued
650 $issuingimpossible, $needsconfirmation =
651 CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
652 C<$duedatespec> is a C4::Dates object.
653 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
657 sub CanBookBeIssued {
658 my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
659 my %needsconfirmation; # filled with problems that needs confirmations
660 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
661 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
662 my $issue = GetItemIssue($item->{itemnumber});
663 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
664 $item->{'itemtype'}=$biblioitem->{'itemtype'};
665 my $dbh = C4::Context->dbh;
668 # DUE DATE is OK ? -- should already have checked.
670 #$issuingimpossible{INVALID_DATE} = 1 unless ($duedate);
675 if ( $borrower->{flags}->{GNA} ) {
676 $issuingimpossible{GNA} = 1;
678 if ( $borrower->{flags}->{'LOST'} ) {
679 $issuingimpossible{CARD_LOST} = 1;
681 if ( $borrower->{flags}->{'DBARRED'} ) {
682 $issuingimpossible{DEBARRED} = 1;
684 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
685 $issuingimpossible{EXPIRED} = 1;
687 my @expirydate= split /-/,$borrower->{'dateexpiry'};
688 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
689 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
690 $issuingimpossible{EXPIRED} = 1;
699 C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
700 if ( C4::Context->preference("IssuingInProcess") ) {
701 my $amountlimit = C4::Context->preference("noissuescharge");
702 if ( $amount > $amountlimit && !$inprocess ) {
703 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
705 elsif ( $amount <= $amountlimit && !$inprocess ) {
706 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
711 $needsconfirmation{DEBT} = $amount;
716 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
718 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
719 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
724 unless ( $item->{barcode} ) {
725 $issuingimpossible{UNKNOWN_BARCODE} = 1;
727 if ( $item->{'notforloan'}
728 && $item->{'notforloan'} > 0 )
730 $issuingimpossible{NOT_FOR_LOAN} = 1;
732 elsif ( !$item->{'notforloan'} ){
733 # we have to check itemtypes.notforloan also
734 if (C4::Context->preference('item-level_itypes')){
735 # this should probably be a subroutine
736 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
737 $sth->execute($item->{'itemtype'});
738 my $notforloan=$sth->fetchrow_hashref();
740 if ($notforloan->{'notforloan'} == 1){
741 $issuingimpossible{NOT_FOR_LOAN} = 1;
744 elsif ($biblioitem->{'notforloan'} == 1){
745 $issuingimpossible{NOT_FOR_LOAN} = 1;
748 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
750 $issuingimpossible{WTHDRAWN} = 1;
752 if ( $item->{'restricted'}
753 && $item->{'restricted'} == 1 )
755 $issuingimpossible{RESTRICTED} = 1;
757 if ( C4::Context->preference("IndependantBranches") ) {
758 my $userenv = C4::Context->userenv;
759 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
760 $issuingimpossible{NOTSAMEBRANCH} = 1
761 if ( $item->{C4::Context->preference("HomeOrHoldingbranch")} ne $userenv->{branch} );
766 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
768 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
771 # Already issued to current borrower. Ask whether the loan should
773 my ($CanBookBeRenewed) = CanBookBeRenewed(
774 $borrower->{'borrowernumber'},
775 $item->{'itemnumber'}
777 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
778 $issuingimpossible{NO_MORE_RENEWALS} = 1;
781 $needsconfirmation{RENEW_ISSUE} = 1;
784 elsif ($issue->{borrowernumber}) {
786 # issued to someone else
787 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
789 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
790 $needsconfirmation{ISSUED_TO_ANOTHER} =
791 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
794 # See if the item is on reserve.
795 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
797 my $resbor = $res->{'borrowernumber'};
798 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
801 # The item is on reserve and waiting, but has been
802 # reserved by some other patron.
803 my ( $resborrower, $flags ) =
804 GetMemberDetails( $resbor, 0 );
805 my $branches = GetBranches();
807 $branches->{ $res->{'branchcode'} }->{'branchname'};
808 $needsconfirmation{RESERVE_WAITING} =
809 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
811 # CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'}); Doesn't belong in a checking subroutine.
813 elsif ( $restype eq "Reserved" ) {
815 # The item is on reserve for someone else.
816 my ( $resborrower, $flags ) =
817 GetMemberDetails( $resbor, 0 );
818 my $branches = GetBranches();
820 $branches->{ $res->{'branchcode'} }->{'branchname'};
821 $needsconfirmation{RESERVED} =
822 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
825 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
826 if ( $borrower->{'categorycode'} eq 'W' ) {
827 my %issuingimpossible;
828 return ( \%issuingimpossible, \%needsconfirmation );
830 return ( \%issuingimpossible, \%needsconfirmation );
833 return ( \%issuingimpossible, \%needsconfirmation );
839 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
841 &AddIssue($borrower,$barcode,$date)
845 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
847 =item C<$barcode> is the bar code of the book being issued.
849 =item C<$date> contains the max date of return. calculated if empty.
851 AddIssue does the following things :
852 - step 01: check that there is a borrowernumber & a barcode provided
853 - check for RENEWAL (book issued & being issued to the same patron)
854 - renewal YES = Calculate Charge & renew
856 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
858 - fill reserve if reserve to this patron
859 - cancel reserve or not, otherwise
860 * TRANSFERT PENDING ?
861 - complete the transfert
869 my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
870 my $dbh = C4::Context->dbh;
871 my $barcodecheck=CheckValidBarcode($barcode);
872 if ($borrower and $barcode and $barcodecheck ne '0'){
873 # find which item we issue
874 my $item = GetItem('', $barcode);
878 # Get which branchcode we need
879 if (C4::Context->preference('CircControl') eq 'PickupLibary'){
880 $branch = C4::Context->userenv->{'branchcode'};
882 elsif (C4::Context->preference('CircControl') eq 'PatronLibary'){
883 $branch = $borrower->{'branchcode'};
887 $branch = $item->{'homebranch'};
890 # get actual issuing if there is one
891 my $actualissue = GetItemIssue( $item->{itemnumber});
893 # get biblioinformation for this item
894 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
897 # check if we just renew the issue.
899 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
901 $borrower->{'borrowernumber'},
902 $item->{'itemnumber'},
910 if ( $actualissue->{borrowernumber}) {
911 # This book is currently on loan, but not to the person
912 # who wants to borrow it now. mark it returned before issuing to the new borrower
915 C4::Context->userenv->{'branch'}
919 # See if the item is on reserve.
920 my ( $restype, $res ) =
921 C4::Reserves::CheckReserves( $item->{'itemnumber'} );
923 my $resbor = $res->{'borrowernumber'};
924 if ( $resbor eq $borrower->{'borrowernumber'} ) {
926 # The item is reserved by the current patron
927 ModReserveFill($res);
929 elsif ( $restype eq "Waiting" ) {
932 # The item is on reserve and waiting, but has been
933 # reserved by some other patron.
934 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
935 my $branches = GetBranches();
937 $branches->{ $res->{'branchcode'} }->{'branchname'};
939 elsif ( $restype eq "Reserved" ) {
942 # The item is reserved by someone else.
943 my ( $resborrower, $flags ) =
944 GetMemberDetails( $resbor, 0 );
945 my $branches = GetBranches();
946 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
947 if ($cancelreserve) { # cancel reserves on this item
948 CancelReserve( 0, $res->{'itemnumber'},
949 $res->{'borrowernumber'} );
952 if ($cancelreserve) {
953 CancelReserve( $res->{'biblionumber'}, 0,
954 $res->{'borrowernumber'} );
957 # set waiting reserve to first in reserve queue as book isn't waiting now
959 $res->{'biblionumber'},
960 $res->{'borrowernumber'},
966 # Starting process for transfer job (checking transfert and validate it if we have one)
967 my ($datesent) = GetTransfers($item->{'itemnumber'});
969 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
972 "UPDATE branchtransfers
973 SET datearrived = now(),
975 comments = 'Forced branchtransfert'
976 WHERE itemnumber= ? AND datearrived IS NULL"
978 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
982 # Record in the database the fact that the book was issued.
986 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
993 my $itype=(C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ;
994 my $loanlength = GetLoanLength(
995 $borrower->{'categorycode'},
999 $datedue = time + ($loanlength) * 86400;
1000 my @datearr = localtime($datedue);
1001 $dateduef = C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
1002 $dateduef=CheckValidDatedue($dateduef,$item->{'itemnumber'},C4::Context->userenv->{'branch'});
1004 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
1005 if ( C4::Context->preference('ReturnBeforeExpiry') && $dateduef->output('iso') gt $borrower->{dateexpiry} ) {
1006 $dateduef = C4::Dates->new($borrower->{dateexpiry},'iso');
1010 $borrower->{'borrowernumber'},
1011 $item->{'itemnumber'},
1012 strftime( "%Y-%m-%d", localtime ),$dateduef->output('iso'), C4::Context->userenv->{'branch'}
1015 $item->{'issues'}++;
1016 ModItem({ issues => $item->{'issues'},
1017 holdingbranch => C4::Context->userenv->{'branch'},
1019 datelastborrowed => C4::Dates->new()->output('iso'),
1020 onloan => $dateduef->output('iso'),
1021 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1022 ModDateLastSeen( $item->{'itemnumber'} );
1024 # If it costs to borrow this book, charge it to the patron's account.
1025 my ( $charge, $itemtype ) = GetIssuingCharges(
1026 $item->{'itemnumber'},
1027 $borrower->{'borrowernumber'}
1029 if ( $charge > 0 ) {
1031 $item->{'itemnumber'},
1032 $borrower->{'borrowernumber'}, $charge
1034 $item->{'charge'} = $charge;
1037 # Record the fact that this book was issued.
1039 C4::Context->userenv->{'branch'},
1041 '', $item->{'itemnumber'},
1042 $item->{'itemtype'}, $borrower->{'borrowernumber'}
1046 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'})
1047 if C4::Context->preference("IssueLog");
1052 =head2 GetLoanLength
1054 Get loan length for an itemtype, a borrower type and a branch
1056 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1061 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1062 my $dbh = C4::Context->dbh;
1065 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1067 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1068 # try to find issuelength & return the 1st available.
1069 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1070 $sth->execute( $borrowertype, $itemtype, $branchcode );
1071 my $loanlength = $sth->fetchrow_hashref;
1072 return $loanlength->{issuelength}
1073 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1075 $sth->execute( $borrowertype, $itemtype, "*" );
1076 $loanlength = $sth->fetchrow_hashref;
1077 return $loanlength->{issuelength}
1078 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1080 $sth->execute( $borrowertype, "*", $branchcode );
1081 $loanlength = $sth->fetchrow_hashref;
1082 return $loanlength->{issuelength}
1083 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1085 $sth->execute( "*", $itemtype, $branchcode );
1086 $loanlength = $sth->fetchrow_hashref;
1087 return $loanlength->{issuelength}
1088 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1090 $sth->execute( $borrowertype, "*", "*" );
1091 $loanlength = $sth->fetchrow_hashref;
1092 return $loanlength->{issuelength}
1093 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1095 $sth->execute( "*", "*", $branchcode );
1096 $loanlength = $sth->fetchrow_hashref;
1097 return $loanlength->{issuelength}
1098 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1100 $sth->execute( "*", $itemtype, "*" );
1101 $loanlength = $sth->fetchrow_hashref;
1102 return $loanlength->{issuelength}
1103 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1105 $sth->execute( "*", "*", "*" );
1106 $loanlength = $sth->fetchrow_hashref;
1107 return $loanlength->{issuelength}
1108 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1110 # if no rule is set => 21 days (hardcoded)
1116 ($doreturn, $messages, $iteminformation, $borrower) =
1117 &AddReturn($barcode, $branch, $exemptfine);
1121 C<$barcode> is the bar code of the book being returned. C<$branch> is
1122 the code of the branch where the book is being returned. C<$exemptfine>
1123 indicates that overdue charges for the item will not be applied.
1125 C<&AddReturn> returns a list of four items:
1127 C<$doreturn> is true iff the return succeeded.
1129 C<$messages> is a reference-to-hash giving the reason for failure:
1135 No item with this barcode exists. The value is C<$barcode>.
1139 The book is not currently on loan. The value is C<$barcode>.
1141 =item C<IsPermanent>
1143 The book's home branch is a permanent collection. If you have borrowed
1144 this book, you are not allowed to return it. The value is the code for
1145 the book's home branch.
1149 This book has been withdrawn/cancelled. The value should be ignored.
1153 The item was reserved. The value is a reference-to-hash whose keys are
1154 fields from the reserves table of the Koha database, and
1155 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1156 either C<Waiting>, C<Reserved>, or 0.
1160 C<$borrower> is a reference-to-hash, giving information about the
1161 patron who last borrowed the book.
1166 my ( $barcode, $branch, $exemptfine ) = @_;
1167 my $dbh = C4::Context->dbh;
1171 my $validTransfert = 0;
1172 my $reserveDone = 0;
1174 # get information on item
1175 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1176 my $biblio = GetBiblioFromItemNumber($iteminformation->{'itemnumber'});
1177 unless ($iteminformation->{'itemnumber'} ) {
1178 $messages->{'BadBarcode'} = $barcode;
1182 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1183 $messages->{'NotIssued'} = $barcode;
1187 # check if the book is in a permanent collection....
1188 my $hbr = $iteminformation->{'homebranch'};
1189 my $branches = GetBranches();
1190 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1191 $messages->{'IsPermanent'} = $hbr;
1194 # if independent branches are on and returning to different branch, refuse the return
1195 if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1196 $messages->{'Wrongbranch'} = 1;
1200 # check that the book has been cancelled
1201 if ( $iteminformation->{'wthdrawn'} ) {
1202 $messages->{'wthdrawn'} = 1;
1206 # new op dev : if the book returned in an other branch update the holding branch
1208 # update issues, thereby returning book (should push this out into another subroutine
1209 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1211 # case of a return of document (deal with issues and holdingbranch)
1216 "UPDATE issues SET returndate = now() WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (returndate IS NULL)"
1218 $sth->execute( $borrower->{'borrowernumber'},
1219 $iteminformation->{'itemnumber'} );
1220 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1223 # continue to deal with returns cases, but not only if we have an issue
1225 # the holdingbranch is updated if the document is returned in an other location .
1226 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1227 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1228 # reload iteminformation holdingbranch with the userenv value
1229 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1231 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1232 ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1234 if ($iteminformation->{borrowernumber}){
1235 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1237 # fix up the accounts.....
1238 if ( $iteminformation->{'itemlost'} ) {
1239 $messages->{'WasLost'} = 1;
1242 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1243 # check if we have a transfer for this document
1244 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1246 # if we have a transfer to do, we update the line of transfers with the datearrived
1248 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1251 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1253 $sth->execute( $iteminformation->{'itemnumber'} );
1255 # 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'
1256 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1259 $messages->{'WrongTransfer'} = $tobranch;
1260 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1262 $validTransfert = 1;
1265 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1266 # fix up the accounts.....
1267 if ($iteminformation->{'itemlost'}) {
1268 FixAccountForLostAndReturned($iteminformation, $borrower);
1269 $messages->{'WasLost'} = 1;
1271 # fix up the overdues in accounts...
1272 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1273 $iteminformation->{'itemnumber'}, $exemptfine );
1275 # find reserves.....
1276 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1277 my ( $resfound, $resrec ) =
1278 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1280 $resrec->{'ResFound'} = $resfound;
1281 $messages->{'ResFound'} = $resrec;
1286 # Record the fact that this book was returned.
1288 $branch, 'return', '0', '',
1289 $iteminformation->{'itemnumber'},
1290 $iteminformation->{'itemtype'},
1291 $borrower->{'borrowernumber'}
1294 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'})
1295 if C4::Context->preference("ReturnLog");
1297 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1298 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1300 if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1301 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1302 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1303 $messages->{'WasTransfered'} = 1;
1306 $messages->{'NeedsTransfer'} = 1;
1310 return ( $doreturn, $messages, $iteminformation, $borrower );
1313 =head2 FixOverduesOnReturn
1315 &FixOverduesOnReturn($brn,$itm, $exemptfine);
1317 C<$brn> borrowernumber
1321 internal function, called only by AddReturn
1325 sub FixOverduesOnReturn {
1326 my ( $borrowernumber, $item, $exemptfine ) = @_;
1327 my $dbh = C4::Context->dbh;
1329 # check for overdue fine
1332 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1334 $sth->execute( $borrowernumber, $item );
1336 # alter fine to show that the book has been returned
1338 if ($data = $sth->fetchrow_hashref) {
1339 my $uquery =($exemptfine)? "update accountlines set accounttype='FFOR', amountoutstanding=0":"update accountlines set accounttype='F' ";
1340 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1341 my $usth = $dbh->prepare($uquery);
1342 $usth->execute($borrowernumber,$item ,$data->{'accountno'});
1350 =head2 FixAccountForLostAndReturned
1352 &FixAccountForLostAndReturned($iteminfo,$borrower);
1354 Calculates the charge for a book lost and returned (Not exported & used only once)
1356 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1358 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1360 Internal function, called by AddReturn
1364 sub FixAccountForLostAndReturned {
1365 my ($iteminfo, $borrower) = @_;
1367 my $dbh = C4::Context->dbh;
1368 my $itm = $iteminfo->{'itemnumber'};
1369 # check for charge made for lost book
1370 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1371 $sth->execute($itm);
1372 if (my $data = $sth->fetchrow_hashref) {
1373 # writeoff this amount
1375 my $amount = $data->{'amount'};
1376 my $acctno = $data->{'accountno'};
1378 if ($data->{'amountoutstanding'} == $amount) {
1379 $offset = $data->{'amount'};
1382 $offset = $amount - $data->{'amountoutstanding'};
1383 $amountleft = $data->{'amountoutstanding'} - $amount;
1385 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1386 WHERE (borrowernumber = ?)
1387 AND (itemnumber = ?) AND (accountno = ?) ");
1388 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1390 #check if any credit is left if so writeoff other accounts
1391 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1392 if ($amountleft < 0){
1395 if ($amountleft > 0){
1396 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1397 AND (amountoutstanding >0) ORDER BY date");
1398 $msth->execute($data->{'borrowernumber'});
1399 # offset transactions
1402 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1403 if ($accdata->{'amountoutstanding'} < $amountleft) {
1405 $amountleft -= $accdata->{'amountoutstanding'};
1407 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1410 my $thisacct = $accdata->{'accountno'};
1411 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1412 WHERE (borrowernumber = ?)
1413 AND (accountno=?)");
1414 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1416 $usth = $dbh->prepare("INSERT INTO accountoffsets
1417 (borrowernumber, accountno, offsetaccount, offsetamount)
1420 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1425 if ($amountleft > 0){
1428 my $desc="Item Returned ".$iteminfo->{'barcode'};
1429 $usth = $dbh->prepare("INSERT INTO accountlines
1430 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1431 VALUES (?,?,now(),?,?,'CR',?)");
1432 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1434 $usth = $dbh->prepare("INSERT INTO accountoffsets
1435 (borrowernumber, accountno, offsetaccount, offsetamount)
1437 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1439 ModItem({ paidfor => '' }, undef, $itm);
1447 $issues = &GetItemIssue($itemnumber);
1449 Returns patrons currently having a book. nothing if item is not issued atm
1451 C<$itemnumber> is the itemnumber
1453 Returns an array of hashes
1457 my ( $itemnumber) = @_;
1458 return unless $itemnumber;
1459 my $dbh = C4::Context->dbh;
1463 my $today = POSIX::strftime("%Y%m%d", localtime);
1465 my $sth = $dbh->prepare(
1466 "SELECT * FROM issues
1467 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1469 issues.itemnumber=? AND returndate IS NULL ");
1470 $sth->execute($itemnumber);
1471 my $data = $sth->fetchrow_hashref;
1472 my $datedue = $data->{'date_due'};
1474 if ( $datedue < $today ) {
1475 $data->{'overdue'} = 1;
1477 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1482 =head2 GetItemIssues
1484 $issues = &GetItemIssues($itemnumber, $history);
1486 Returns patrons that have issued a book
1488 C<$itemnumber> is the itemnumber
1489 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1491 Returns an array of hashes
1495 my ( $itemnumber,$history ) = @_;
1496 my $dbh = C4::Context->dbh;
1500 my $today = POSIX::strftime("%Y%m%d", localtime);
1502 my $sth = $dbh->prepare(
1503 "SELECT * FROM issues
1504 LEFT JOIN borrowers ON borrowers.borrowernumber
1505 LEFT JOIN items ON items.itemnumber=issues.itemnumber
1507 issues.itemnumber=?".($history?"":" AND returndate IS NULL ").
1508 "ORDER BY issues.date_due DESC"
1510 $sth->execute($itemnumber);
1511 while ( my $data = $sth->fetchrow_hashref ) {
1512 my $datedue = $data->{'date_due'};
1514 if ( $datedue < $today ) {
1515 $data->{'overdue'} = 1;
1517 my $itemnumber = $data->{'itemnumber'};
1518 push @GetItemIssues, $data;
1521 return ( \@GetItemIssues );
1524 =head2 GetBiblioIssues
1526 $issues = GetBiblioIssues($biblionumber);
1528 this function get all issues from a biblionumber.
1531 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1532 tables issues and the firstname,surname & cardnumber from borrowers.
1536 sub GetBiblioIssues {
1537 my $biblionumber = shift;
1538 return undef unless $biblionumber;
1539 my $dbh = C4::Context->dbh;
1541 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1543 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1544 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1545 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1546 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1547 WHERE biblio.biblionumber = ?
1548 ORDER BY issues.timestamp
1550 my $sth = $dbh->prepare($query);
1551 $sth->execute($biblionumber);
1554 while ( my $data = $sth->fetchrow_hashref ) {
1555 push @issues, $data;
1560 =head2 CanBookBeRenewed
1562 $ok = &CanBookBeRenewed($borrowernumber, $itemnumber);
1564 Find out whether a borrowed item may be renewed.
1566 C<$dbh> is a DBI handle to the Koha database.
1568 C<$borrowernumber> is the borrower number of the patron who currently
1569 has the item on loan.
1571 C<$itemnumber> is the number of the item to renew.
1573 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1574 item must currently be on loan to the specified borrower; renewals
1575 must be allowed for the item's type; and the borrower must not have
1576 already renewed the loan.
1580 sub CanBookBeRenewed {
1582 # check renewal status
1583 my ( $borrowernumber, $itemnumber ) = @_;
1584 my $dbh = C4::Context->dbh;
1588 # Look in the issues table for this item, lent to this borrower,
1589 # and not yet returned.
1591 # FIXME - I think this function could be redone to use only one SQL call.
1592 my $sth1 = $dbh->prepare(
1593 "SELECT * FROM issues
1594 WHERE borrowernumber = ?
1596 AND returndate IS NULL"
1598 $sth1->execute( $borrowernumber, $itemnumber );
1599 if ( my $data1 = $sth1->fetchrow_hashref ) {
1601 # Found a matching item
1603 # See if this item may be renewed. This query is convoluted
1604 # because it's a bit messy: given the item number, we need to find
1605 # the biblioitem, which gives us the itemtype, which tells us
1606 # whether it may be renewed.
1607 my $sth2 = $dbh->prepare(
1608 "SELECT renewalsallowed FROM items
1609 LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1610 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1611 WHERE items.itemnumber = ?
1614 $sth2->execute($itemnumber);
1615 if ( my $data2 = $sth2->fetchrow_hashref ) {
1616 $renews = $data2->{'renewalsallowed'};
1618 if ( $renews && $renews >= $data1->{'renewals'} ) {
1622 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1629 return ($renewokay);
1634 &AddRenewal($borrowernumber, $itemnumber, $datedue);
1638 C<$borrowernumber> is the borrower number of the patron who currently
1641 C<$itemnumber> is the number of the item to renew.
1643 C<$datedue> can be used to set the due date. If C<$datedue> is the
1644 empty string, C<&AddRenewal> will calculate the due date automatically
1645 from the book's item type. If you wish to set the due date manually,
1646 C<$datedue> should be in the form YYYY-MM-DD.
1652 my ( $borrowernumber, $itemnumber, $branch ,$datedue ) = @_;
1653 my $dbh = C4::Context->dbh;
1655 my $biblio = GetBiblioFromItemNumber($itemnumber);
1656 # If the due date wasn't specified, calculate it by adding the
1657 # book's loan length to today's date.
1658 unless ( $datedue ) {
1661 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
1662 my $loanlength = GetLoanLength(
1663 $borrower->{'categorycode'},
1664 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1665 $borrower->{'branchcode'}
1667 #FIXME -- choose issuer or borrower branch.
1668 #FIXME -- where's the calendar ?
1669 #FIXME -- $debug-ify the (0)
1670 my @darray = Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
1671 $datedue = C4::Dates->new( sprintf("%04d-%02d-%02d",@darray[0..2]), 'iso');
1672 (0) and print STDERR "C4::Dates->new->output = " . C4::Dates->new()->output()
1673 . "\ndatedue->output = " . $datedue->output()
1674 . "\n(Y,M,D) = " . join ',', @darray;
1675 $datedue=CheckValidDatedue($datedue,$itemnumber,$branch);
1678 # Find the issues record for this book
1680 $dbh->prepare("SELECT * FROM issues
1681 WHERE borrowernumber=?
1683 AND returndate IS NULL"
1685 $sth->execute( $borrowernumber, $itemnumber );
1686 my $issuedata = $sth->fetchrow_hashref;
1689 # Update the issues record to have the new due date, and a new count
1690 # of how many times it has been renewed.
1691 my $renews = $issuedata->{'renewals'} + 1;
1692 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1693 WHERE borrowernumber=?
1695 AND returndate IS NULL"
1697 $sth->execute( $datedue->output('iso'), $renews, $borrowernumber, $itemnumber );
1700 # Update the renewal count on the item, and tell zebra to reindex
1701 $renews = $biblio->{'renewals'} + 1;
1702 ModItem({ renewals => $renews }, $biblio->{'biblionumber'}, $itemnumber);
1704 # Charge a new rental fee, if applicable?
1705 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1706 if ( $charge > 0 ) {
1707 my $accountno = getnextacctno( $borrowernumber );
1708 my $item = GetBiblioFromItemNumber($itemnumber);
1709 $sth = $dbh->prepare(
1710 "INSERT INTO accountlines
1711 (borrowernumber,accountno,date,amount,
1712 description,accounttype,amountoutstanding,
1714 VALUES (?,?,now(),?,?,?,?,?)"
1716 $sth->execute( $borrowernumber, $accountno, $charge,
1717 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1718 'Rent', $charge, $itemnumber );
1722 UpdateStats( $branch, 'renew', $charge, '', $itemnumber );
1726 # check renewal status
1727 my ($bornum,$itemno)=@_;
1728 my $dbh = C4::Context->dbh;
1730 my $renewsallowed = 0;
1732 # Look in the issues table for this item, lent to this borrower,
1733 # and not yet returned.
1735 # FIXME - I think this function could be redone to use only one SQL call.
1736 my $sth = $dbh->prepare("select * from issues
1737 where (borrowernumber = ?)
1738 and (itemnumber = ?)
1739 and returndate is null");
1740 $sth->execute($bornum,$itemno);
1741 my $data = $sth->fetchrow_hashref;
1742 $renewcount = $data->{'renewals'} if $data->{'renewals'};
1743 my $sth2 = $dbh->prepare("select renewalsallowed from items,biblioitems,itemtypes
1744 where (items.itemnumber = ?)
1745 and (items.biblioitemnumber = biblioitems.biblioitemnumber)
1746 and (biblioitems.itemtype = itemtypes.itemtype)");
1747 $sth2->execute($itemno);
1748 my $data2 = $sth2->fetchrow_hashref();
1749 $renewsallowed = $data2->{'renewalsallowed'};
1750 $renewsleft = $renewsallowed - $renewcount;
1751 warn "Renewcount:$renewcount RenewsAll:$renewsallowed RenewLeft:$renewsleft";
1752 return ($renewcount,$renewsallowed,$renewsleft);
1754 =head2 GetIssuingCharges
1756 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1758 Calculate how much it would cost for a given patron to borrow a given
1759 item, including any applicable discounts.
1761 C<$itemnumber> is the item number of item the patron wishes to borrow.
1763 C<$borrowernumber> is the patron's borrower number.
1765 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1766 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1771 sub GetIssuingCharges {
1773 # calculate charges due
1774 my ( $itemnumber, $borrowernumber ) = @_;
1776 my $dbh = C4::Context->dbh;
1779 # Get the book's item type and rental charge (via its biblioitem).
1780 my $qcharge = "SELECT itemtypes.itemtype,rentalcharge FROM items
1781 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1782 $qcharge .= (C4::Context->preference('item-level_itypes'))
1783 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1784 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1786 $qcharge .= "WHERE items.itemnumber =?";
1788 my $sth1 = $dbh->prepare($qcharge);
1789 $sth1->execute($itemnumber);
1790 if ( my $data1 = $sth1->fetchrow_hashref ) {
1791 $item_type = $data1->{'itemtype'};
1792 $charge = $data1->{'rentalcharge'};
1793 my $q2 = "SELECT rentaldiscount FROM borrowers
1794 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1795 WHERE borrowers.borrowernumber = ?
1796 AND issuingrules.itemtype = ?";
1797 my $sth2 = $dbh->prepare($q2);
1798 $sth2->execute( $borrowernumber, $item_type );
1799 if ( my $data2 = $sth2->fetchrow_hashref ) {
1800 my $discount = $data2->{'rentaldiscount'};
1801 if ( $discount eq 'NULL' ) {
1804 $charge = ( $charge * ( 100 - $discount ) ) / 100;
1810 return ( $charge, $item_type );
1813 =head2 AddIssuingCharge
1815 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1819 sub AddIssuingCharge {
1820 my ( $itemnumber, $borrowernumber, $charge ) = @_;
1821 my $dbh = C4::Context->dbh;
1822 my $nextaccntno = getnextacctno( $borrowernumber );
1824 INSERT INTO accountlines
1825 (borrowernumber, itemnumber, accountno,
1826 date, amount, description, accounttype,
1828 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1830 my $sth = $dbh->prepare($query);
1831 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1837 GetTransfers($itemnumber);
1842 my ($itemnumber) = @_;
1844 my $dbh = C4::Context->dbh;
1850 FROM branchtransfers
1851 WHERE itemnumber = ?
1852 AND datearrived IS NULL
1854 my $sth = $dbh->prepare($query);
1855 $sth->execute($itemnumber);
1856 my @row = $sth->fetchrow_array();
1862 =head2 GetTransfersFromTo
1864 @results = GetTransfersFromTo($frombranch,$tobranch);
1866 Returns the list of pending transfers between $from and $to branch
1870 sub GetTransfersFromTo {
1871 my ( $frombranch, $tobranch ) = @_;
1872 return unless ( $frombranch && $tobranch );
1873 my $dbh = C4::Context->dbh;
1875 SELECT itemnumber,datesent,frombranch
1876 FROM branchtransfers
1879 AND datearrived IS NULL
1881 my $sth = $dbh->prepare($query);
1882 $sth->execute( $frombranch, $tobranch );
1885 while ( my $data = $sth->fetchrow_hashref ) {
1886 push @gettransfers, $data;
1889 return (@gettransfers);
1892 =head2 DeleteTransfer
1894 &DeleteTransfer($itemnumber);
1898 sub DeleteTransfer {
1899 my ($itemnumber) = @_;
1900 my $dbh = C4::Context->dbh;
1901 my $sth = $dbh->prepare(
1902 "DELETE FROM branchtransfers
1904 AND datearrived IS NULL "
1906 $sth->execute($itemnumber);
1910 =head2 AnonymiseIssueHistory
1912 $rows = AnonymiseIssueHistory($borrowernumber,$date)
1914 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
1915 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
1917 return the number of affected rows.
1921 sub AnonymiseIssueHistory {
1923 my $borrowernumber = shift;
1924 my $dbh = C4::Context->dbh;
1927 SET borrowernumber = NULL
1928 WHERE returndate < '".$date."'
1929 AND borrowernumber IS NOT NULL
1931 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
1932 my $rows_affected = $dbh->do($query);
1933 return $rows_affected;
1936 =head2 updateWrongTransfer
1938 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
1940 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
1944 sub updateWrongTransfer {
1945 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
1946 my $dbh = C4::Context->dbh;
1947 # first step validate the actual line of transfert .
1950 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
1952 $sth->execute($FromLibrary,$itemNumber);
1955 # second step create a new line of branchtransfer to the right location .
1956 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
1958 #third step changing holdingbranch of item
1959 UpdateHoldingbranch($FromLibrary,$itemNumber);
1962 =head2 UpdateHoldingbranch
1964 $items = UpdateHoldingbranch($branch,$itmenumber);
1965 Simple methode for updating hodlingbranch in items BDD line
1968 sub UpdateHoldingbranch {
1969 my ( $branch,$itemnumber ) = @_;
1970 ModItem({ holdingbranch => $branch }, undef, $itemnumber);
1973 =head2 CheckValidDatedue
1975 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
1976 this function return a new date due after checked if it's a repeatable or special holiday
1977 C<$date_due> = returndate calculate with no day check
1978 C<$itemnumber> = itemnumber
1979 C<$branchcode> = localisation of issue
1981 # Why not create calendar object? -
1982 # TODO add 'duedate' option to useDaysMode .
1983 sub CheckValidDatedue {
1984 my ($date_due,$itemnumber,$branchcode)=@_;
1985 my @datedue=split('-',$date_due->output('iso'));
1986 my $years=$datedue[0];
1987 my $month=$datedue[1];
1988 my $day=$datedue[2];
1989 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
1991 for (my $i=0;$i<2;$i++){
1992 $dow=Day_of_Week($years,$month,$day);
1993 ($dow=0) if ($dow>6);
1994 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
1995 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1996 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1997 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
1999 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2002 my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2005 =head2 CheckRepeatableHolidays
2007 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2008 this function check if the date due is a repeatable holiday
2009 C<$date_due> = returndate calculate with no day check
2010 C<$itemnumber> = itemnumber
2011 C<$branchcode> = localisation of issue
2015 sub CheckRepeatableHolidays{
2016 my($itemnumber,$week_day,$branchcode)=@_;
2017 my $dbh = C4::Context->dbh;
2018 my $query = qq|SELECT count(*)
2019 FROM repeatable_holidays
2022 my $sth = $dbh->prepare($query);
2023 $sth->execute($branchcode,$week_day);
2024 my $result=$sth->fetchrow;
2030 =head2 CheckSpecialHolidays
2032 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2033 this function check if the date is a special holiday
2034 C<$years> = the years of datedue
2035 C<$month> = the month of datedue
2036 C<$day> = the day of datedue
2037 C<$itemnumber> = itemnumber
2038 C<$branchcode> = localisation of issue
2040 sub CheckSpecialHolidays{
2041 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2042 my $dbh = C4::Context->dbh;
2043 my $query=qq|SELECT count(*)
2044 FROM `special_holidays`
2050 my $sth = $dbh->prepare($query);
2051 $sth->execute($years,$month,$day,$branchcode);
2052 my $countspecial=$sth->fetchrow ;
2054 return $countspecial;
2057 =head2 CheckRepeatableSpecialHolidays
2059 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2060 this function check if the date is a repeatble special holidays
2061 C<$month> = the month of datedue
2062 C<$day> = the day of datedue
2063 C<$itemnumber> = itemnumber
2064 C<$branchcode> = localisation of issue
2066 sub CheckRepeatableSpecialHolidays{
2067 my ($month,$day,$itemnumber,$branchcode) = @_;
2068 my $dbh = C4::Context->dbh;
2069 my $query=qq|SELECT count(*)
2070 FROM `repeatable_holidays`
2075 my $sth = $dbh->prepare($query);
2076 $sth->execute($month,$day,$branchcode);
2077 my $countspecial=$sth->fetchrow ;
2079 return $countspecial;
2084 sub CheckValidBarcode{
2086 my $dbh = C4::Context->dbh;
2087 my $query=qq|SELECT count(*)
2091 my $sth = $dbh->prepare($query);
2092 $sth->execute($barcode);
2093 my $exist=$sth->fetchrow ;
2104 Koha Developement team <info@koha.org>