1 package C4::Circulation;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
39 use POSIX qw(strftime);
40 use C4::Branch; # GetBranches
41 use C4::Log; # logaction
43 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,%EXPORT_TAGS);
45 # set the version for version checking
50 C4::Circulation - Koha circulation module
58 The functions in this module deal with circulation, issues, and
59 returns, as well as general information about the library.
60 Also deals with stocktaking.
68 # FIXME subs that should probably be elsewhere
74 # subs to deal with issuing a book
85 &AnonymiseIssueHistory
87 # subs to deal with returns
92 # subs to deal with transfers
101 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
102 # FIXME From Paul : i don't understand what this sub does & why it has to be called on every circ. Speak of this with chris maybe ?
106 =head3 $str = &decode($chunk);
110 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
117 sub cuecatbarcodedecode {
120 my @fields = split( /\./, $barcode );
121 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
122 if ( $#results == 2 ) {
132 =head3 $str = &decode($chunk);
136 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
146 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
147 my @s = map { index( $seq, $_ ); } split( //, $encoded );
148 my $l = ( $#s + 1 ) % 4;
159 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
161 chr( ( $n >> 16 ) ^ 67 )
162 .chr( ( $n >> 8 & 255 ) ^ 67 )
163 .chr( ( $n & 255 ) ^ 67 );
166 $r = substr( $r, 0, length($r) - $l );
172 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
174 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
176 C<$newbranch> is the code for the branch to which the item should be transferred.
178 C<$barcode> is the barcode of the item to be transferred.
180 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
181 Otherwise, if an item is reserved, the transfer fails.
183 Returns three values:
187 is true if the transfer was successful.
191 is a reference-to-hash which may have any of the following keys:
197 There is no item in the catalog with the given barcode. The value is C<$barcode>.
201 The item's home branch is permanent. This doesn't prevent the item from being transferred, though. The value is the code of the item's home branch.
203 =item C<DestinationEqualsHolding>
205 The item is already at the branch to which it is being transferred. The transfer is nonetheless considered to have failed. The value should be ignored.
209 The item was on loan, and C<&transferbook> automatically returned it before transferring it. The value is the borrower number of the patron who had the item.
213 The item was reserved. The value is a reference-to-hash whose keys are fields from the reserves table of the Koha database, and C<biblioitemnumber>. It also has the key C<ResFound>, whose value is either C<Waiting> or C<Reserved>.
215 =item C<WasTransferred>
217 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
224 my ( $tbr, $barcode, $ignoreRs ) = @_;
227 my $branches = GetBranches();
228 my $itemnumber = GetItemnumberFromBarcode( $barcode );
229 my $issue = GetItemIssue($itemnumber);
230 my $biblio = GetBiblioFromItemNumber($itemnumber);
233 if ( not $itemnumber ) {
234 $messages->{'BadBarcode'} = $barcode;
238 # get branches of book...
239 my $hbr = $biblio->{'homebranch'};
240 my $fbr = $biblio->{'holdingbranch'};
243 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
244 $messages->{'IsPermanent'} = $hbr;
247 # can't transfer book if is already there....
248 if ( $fbr eq $tbr ) {
249 $messages->{'DestinationEqualsHolding'} = 1;
253 # check if it is still issued to someone, return it...
254 if ($issue->{borrowernumber}) {
255 AddReturn( $barcode, $fbr );
256 $messages->{'WasReturned'} = $issue->{borrowernumber};
260 # That'll save a database query.
261 my ( $resfound, $resrec ) =
262 CheckReserves( $itemnumber );
263 if ( $resfound and not $ignoreRs ) {
264 $resrec->{'ResFound'} = $resfound;
266 # $messages->{'ResFound'} = $resrec;
270 #actually do the transfer....
272 ModItemTransfer( $itemnumber, $fbr, $tbr );
274 # don't need to update MARC anymore, we do it in batch now
275 $messages->{'WasTransfered'} = 1;
276 ModDateLastSeen( $itemnumber );
278 return ( $dotransfer, $messages, $biblio );
281 =head2 CanBookBeIssued
283 Check if a book can be issued.
285 my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($borrower,$barcode,$year,$month,$day);
289 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
291 =item C<$barcode> is the bar code of the book being issued.
293 =item C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
301 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
302 Possible values are :
308 sticky due date is invalid
312 borrower gone with no address
316 borrower declared it's card lost
322 =head3 UNKNOWN_BARCODE
336 item is restricted (set by ??)
338 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
339 Possible values are :
347 renewing, not issuing
349 =head3 ISSUED_TO_ANOTHER
351 issued to someone else.
355 reserved for someone else.
359 sticky due date is invalid
363 if the borrower borrows to much things
367 # check if a book can be issued.
371 my $borrower = shift;
372 my $biblionumber = shift;
374 my $cat_borrower = $borrower->{'categorycode'};
375 my $branch_borrower = $borrower->{'branchcode'};
376 my $dbh = C4::Context->dbh;
378 my $branch_issuer = C4::Context->userenv->{'branchcode'};
379 #TODO : specify issuer or borrower for circrule.
380 my $type = (C4::Context->preference('item-level_itypes'))
381 ? $item->{'itype'} # item-level
382 : $item->{'itemtype'}; # biblio-level
386 'SELECT * FROM issuingrules
387 WHERE categorycode = ?
392 my $query2 = "SELECT COUNT(*) FROM issues i, biblioitems s1, items s2
393 WHERE i.borrowernumber = ?
394 AND i.returndate IS NULL
395 AND i.itemnumber = s2.itemnumber
396 AND s1.biblioitemnumber = s2.biblioitemnumber"
397 . (C4::Context->preference('item-level_itypes'))
399 : " AND s1.itemtype= ? ";
400 my $sth2= $dbh->prepare($query2);
403 'SELECT COUNT(*) FROM issues
404 WHERE borrowernumber = ?
405 AND returndate IS NULL'
409 # check the 3 parameters (branch / itemtype / category code
410 $sth->execute( $cat_borrower, $type, $branch_borrower );
411 my $result = $sth->fetchrow_hashref;
412 # warn "$cat_borrower, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
414 if ( $result->{maxissueqty} ne '' ) {
415 # warn "checking on everything set";
416 $sth2->execute( $borrower->{'borrowernumber'}, $type );
417 my $alreadyissued = $sth2->fetchrow;
418 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
419 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/itemtype failed)" );
421 # now checking for total
422 $sth->execute( $cat_borrower, '', $branch_borrower );
423 my $result = $sth->fetchrow_hashref;
424 if ( $result->{maxissueqty} ne '*' ) {
425 $sth2->execute( $borrower->{'borrowernumber'}, $type );
426 my $alreadyissued = $sth2->fetchrow;
427 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
428 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/total failed)" );
433 # check the 2 parameters (branch / itemtype / default categorycode
434 $sth->execute( '*', $type, $branch_borrower );
435 my $result = $sth->fetchrow_hashref;
436 # warn "*, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
438 if ( $result->{maxissueqty} ne '' ) {
439 # warn "checking on 2 parameters (default categorycode)";
440 $sth2->execute( $borrower->{'borrowernumber'}, $type );
441 my $alreadyissued = $sth2->fetchrow;
442 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
443 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / itemtype failed)" );
445 # now checking for total
446 $sth->execute( '*', '*', $branch_borrower );
447 my $result = $sth->fetchrow_hashref;
448 if ( $result->{maxissueqty} ne '' ) {
449 $sth2->execute( $borrower->{'borrowernumber'}, $type );
450 my $alreadyissued = $sth2->fetchrow;
451 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
452 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / total failed)" );
457 # check the 1 parameters (default branch / itemtype / categorycode
458 $sth->execute( $cat_borrower, $type, '*' );
459 my $result = $sth->fetchrow_hashref;
460 # warn "$cat_borrower, $type, * = ".Data::Dumper::Dumper($result);
462 if ( $result->{maxissueqty} ne '' ) {
463 # warn "checking on 1 parameter (default branch + categorycode)";
464 $sth2->execute( $borrower->{'borrowernumber'}, $type );
465 my $alreadyissued = $sth2->fetchrow;
466 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
467 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch/category/itemtype failed)" );
469 # now checking for total
470 $sth->execute( $cat_borrower, '*', '*' );
471 my $result = $sth->fetchrow_hashref;
472 if ( $result->{maxissueqty} ne '' ) {
473 $sth2->execute( $borrower->{'borrowernumber'}, $type );
474 my $alreadyissued = $sth2->fetchrow;
475 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
476 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / category / total failed)" );
481 # check the 0 parameters (default branch / itemtype / default categorycode
482 $sth->execute( '*', $type, '*' );
483 my $result = $sth->fetchrow_hashref;
484 # warn "*, $type, * = ".Data::Dumper::Dumper($result);
486 if ( $result->{maxissueqty} ne '' ) {
487 # warn "checking on default branch and default categorycode";
488 $sth2->execute( $borrower->{'borrowernumber'}, $type );
489 my $alreadyissued = $sth2->fetchrow;
490 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
491 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / itemtype failed)" );
493 # now checking for total
494 $sth->execute( '*', '*', '*' );
495 my $result = $sth->fetchrow_hashref;
496 if ( $result->{maxissueqty} ne '' ) {
497 $sth2->execute( $borrower->{'borrowernumber'}, $type );
498 my $alreadyissued = $sth2->fetchrow;
499 if ( $result->{'maxissueqty'} <= $alreadyissued ) {
500 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / total failed)" );
505 #OK, the patron can issue !!!
511 @issues = &itemissues($biblioitemnumber, $biblio);
513 Looks up information about who has borrowed the bookZ<>(s) with the
514 given biblioitemnumber.
516 C<$biblio> is ignored.
518 C<&itemissues> returns an array of references-to-hash. The keys
519 include the fields from the C<items> table in the Koha database.
520 Additional keys include:
526 If the item is currently on loan, this gives the due date.
528 If the item is not on loan, then this is either "Available" or
529 "Cancelled", if the item has been withdrawn.
533 If the item is currently on loan, this gives the card number of the
534 patron who currently has the item.
536 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
538 These give the timestamp for the last three times the item was
541 =item C<card0>, C<card1>, C<card2>
543 The card number of the last three patrons who borrowed this item.
545 =item C<borrower0>, C<borrower1>, C<borrower2>
547 The borrower number of the last three patrons who borrowed this item.
555 my ( $bibitem, $biblio ) = @_;
556 my $dbh = C4::Context->dbh;
558 # FIXME - If this function die()s, the script will abort, and the
559 # user won't get anything; depending on how far the script has
560 # gotten, the user might get a blank page. It would be much better
561 # to at least print an error message. The easiest way to do this
562 # is to set $SIG{__DIE__}.
564 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
569 $sth->execute($bibitem) || die $sth->errstr;
571 while ( my $data = $sth->fetchrow_hashref ) {
573 # Find out who currently has this item.
574 # FIXME - Wouldn't it be better to do this as a left join of
575 # some sort? Currently, this code assumes that if
576 # fetchrow_hashref() fails, then the book is on the shelf.
577 # fetchrow_hashref() can fail for any number of reasons (e.g.,
578 # database server crash), not just because no items match the
580 my $sth2 = $dbh->prepare(
581 "SELECT * FROM issues
582 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
584 AND returndate IS NULL
588 $sth2->execute( $data->{'itemnumber'} );
589 if ( my $data2 = $sth2->fetchrow_hashref ) {
590 $data->{'date_due'} = $data2->{'date_due'};
591 $data->{'card'} = $data2->{'cardnumber'};
592 $data->{'borrower'} = $data2->{'borrowernumber'};
595 if ( $data->{'wthdrawn'} eq '1' ) {
596 $data->{'date_due'} = 'Cancelled';
599 $data->{'date_due'} = 'Available';
605 # Find the last 3 people who borrowed this item.
606 $sth2 = $dbh->prepare(
607 "SELECT * FROM issues
608 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
610 AND returndate IS NOT NULL
611 ORDER BY returndate DESC,timestamp DESC"
614 $sth2->execute( $data->{'itemnumber'} );
615 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
616 { # FIXME : error if there is less than 3 pple borrowing this item
617 if ( my $data2 = $sth2->fetchrow_hashref ) {
618 $data->{"timestamp$i2"} = $data2->{'timestamp'};
619 $data->{"card$i2"} = $data2->{'cardnumber'};
620 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
625 $results[$i] = $data;
633 =head2 CanBookBeIssued
635 $issuingimpossible, $needsconfirmation =
636 CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
637 C<$duedatespec> is a C4::Dates object.
638 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
642 sub CanBookBeIssued {
643 my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
644 my %needsconfirmation; # filled with problems that needs confirmations
645 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
646 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
647 my $issue = GetItemIssue($item->{itemnumber});
648 my $dbh = C4::Context->dbh;
651 # DUE DATE is OK ? -- should already have checked.
653 #$issuingimpossible{INVALID_DATE} = 1 unless ($duedate);
658 if ( $borrower->{flags}->{GNA} ) {
659 $issuingimpossible{GNA} = 1;
661 if ( $borrower->{flags}->{'LOST'} ) {
662 $issuingimpossible{CARD_LOST} = 1;
664 if ( $borrower->{flags}->{'DBARRED'} ) {
665 $issuingimpossible{DEBARRED} = 1;
667 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
668 $issuingimpossible{EXPIRED} = 1;
670 my @expirydate= split /-/,$borrower->{'dateexpiry'};
671 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
672 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
673 $issuingimpossible{EXPIRED} = 1;
682 C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
683 if ( C4::Context->preference("IssuingInProcess") ) {
684 my $amountlimit = C4::Context->preference("noissuescharge");
685 if ( $amount > $amountlimit && !$inprocess ) {
686 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
688 elsif ( $amount <= $amountlimit && !$inprocess ) {
689 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
694 $needsconfirmation{DEBT} = $amount;
699 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
702 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
703 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
708 unless ( $item->{barcode} ) {
709 $issuingimpossible{UNKNOWN_BARCODE} = 1;
711 if ( $item->{'notforloan'}
712 && $item->{'notforloan'} > 0 )
714 $issuingimpossible{NOT_FOR_LOAN} = 1;
716 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
718 $issuingimpossible{WTHDRAWN} = 1;
720 if ( $item->{'restricted'}
721 && $item->{'restricted'} == 1 )
723 $issuingimpossible{RESTRICTED} = 1;
725 if ( C4::Context->preference("IndependantBranches") ) {
726 my $userenv = C4::Context->userenv;
727 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
728 $issuingimpossible{NOTSAMEBRANCH} = 1
729 if ( $item->{C4::Context->preference("HomeOrHoldingbranch")} ne $userenv->{branch} );
734 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
736 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
739 # Already issued to current borrower. Ask whether the loan should
741 my ($CanBookBeRenewed) = CanBookBeRenewed(
742 $borrower->{'borrowernumber'},
743 $item->{'itemnumber'}
745 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
746 $issuingimpossible{NO_MORE_RENEWALS} = 1;
749 $needsconfirmation{RENEW_ISSUE} = 1;
752 elsif ($issue->{borrowernumber}) {
754 # issued to someone else
755 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
757 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
758 $needsconfirmation{ISSUED_TO_ANOTHER} =
759 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
762 # See if the item is on reserve.
763 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
765 my $resbor = $res->{'borrowernumber'};
766 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
769 # The item is on reserve and waiting, but has been
770 # reserved by some other patron.
771 my ( $resborrower, $flags ) =
772 GetMemberDetails( $resbor, 0 );
773 my $branches = GetBranches();
775 $branches->{ $res->{'branchcode'} }->{'branchname'};
776 $needsconfirmation{RESERVE_WAITING} =
777 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
779 # CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'}); Doesn't belong in a checking subroutine.
781 elsif ( $restype eq "Reserved" ) {
783 # The item is on reserve for someone else.
784 my ( $resborrower, $flags ) =
785 GetMemberDetails( $resbor, 0 );
786 my $branches = GetBranches();
788 $branches->{ $res->{'branchcode'} }->{'branchname'};
789 $needsconfirmation{RESERVED} =
790 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
793 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
794 if ( $borrower->{'categorycode'} eq 'W' ) {
795 my %issuingimpossible;
796 return ( \%issuingimpossible, \%needsconfirmation );
798 return ( \%issuingimpossible, \%needsconfirmation );
801 return ( \%issuingimpossible, \%needsconfirmation );
807 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
809 &AddIssue($borrower,$barcode,$date)
813 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
815 =item C<$barcode> is the bar code of the book being issued.
817 =item C<$date> contains the max date of return. calculated if empty.
819 AddIssue does the following things :
820 - step 01: check that there is a borrowernumber & a barcode provided
821 - check for RENEWAL (book issued & being issued to the same patron)
822 - renewal YES = Calculate Charge & renew
824 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
826 - fill reserve if reserve to this patron
827 - cancel reserve or not, otherwise
828 * TRANSFERT PENDING ?
829 - complete the transfert
837 my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
838 my $dbh = C4::Context->dbh;
839 my $barcodecheck=CheckValidBarcode($barcode);
840 if ($borrower and $barcode and $barcodecheck ne '0'){
841 # my ($borrower, $flags) = &GetMemberDetails($borrowernumber, 0);
842 # find which item we issue
843 my $item = GetItem('', $barcode);
847 # get actual issuing if there is one
848 my $actualissue = GetItemIssue( $item->{itemnumber});
850 # get biblioinformation for this item
851 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
854 # check if we just renew the issue.
856 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
858 $borrower->{'borrowernumber'},
859 $item->{'itemnumber'}
863 else {# it's NOT a renewal
864 if ( $actualissue->{borrowernumber}) {
865 # This book is currently on loan, but not to the person
866 # who wants to borrow it now. mark it returned before issuing to the new borrower
869 C4::Context->userenv->{'branch'}
873 # See if the item is on reserve.
874 my ( $restype, $res ) =
875 C4::Reserves::CheckReserves( $item->{'itemnumber'} );
877 my $resbor = $res->{'borrowernumber'};
878 if ( $resbor eq $borrower->{'borrowernumber'} ) {
880 # The item is reserved by the current patron
881 ModReserveFill($res);
883 elsif ( $restype eq "Waiting" ) {
886 # The item is on reserve and waiting, but has been
887 # reserved by some other patron.
888 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
889 my $branches = GetBranches();
891 $branches->{ $res->{'branchcode'} }->{'branchname'};
893 elsif ( $restype eq "Reserved" ) {
896 # The item is reserved by someone else.
897 my ( $resborrower, $flags ) =
898 GetMemberDetails( $resbor, 0 );
899 my $branches = GetBranches();
901 $branches->{ $res->{'branchcode'} }->{'branchname'};
902 if ($cancelreserve) { # cancel reserves on this item
903 CancelReserve( 0, $res->{'itemnumber'},
904 $res->{'borrowernumber'} );
907 if ($cancelreserve) {
908 CancelReserve( $res->{'biblionumber'}, 0,
909 $res->{'borrowernumber'} );
912 # set waiting reserve to first in reserve queue as book isn't waiting now
915 $res->{'biblionumber'},
916 $res->{'borrowernumber'},
922 # Starting process for transfer job (checking transfert and validate it if we have one)
923 my ($datesent) = GetTransfers($item->{'itemnumber'});
925 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
928 "UPDATE branchtransfers
929 SET datearrived = now(),
931 comments = 'Forced branchtransfert'
932 WHERE itemnumber= ? AND datearrived IS NULL"
934 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
938 # Record in the database the fact that the book was issued.
942 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
949 my $itype=(C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ;
950 my $loanlength = GetLoanLength(
951 $borrower->{'categorycode'},
953 $borrower->{'branchcode'}
955 $datedue = time + ($loanlength) * 86400;
956 my @datearr = localtime($datedue);
957 $dateduef = C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
958 $dateduef=CheckValidDatedue($dateduef,$item->{'itemnumber'},C4::Context->userenv->{'branch'});
960 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
961 if ( C4::Context->preference('ReturnBeforeExpiry') && $dateduef gt $borrower->{dateexpiry} ) {
962 $dateduef = $borrower->{dateexpiry};
966 $borrower->{'borrowernumber'},
967 $item->{'itemnumber'},
968 strftime( "%Y-%m-%d", localtime ),$dateduef->output('iso'), C4::Context->userenv->{'branch'}
974 "UPDATE items SET issues=?, holdingbranch=?, itemlost=0, datelastborrowed = now() WHERE itemnumber=?");
977 C4::Context->userenv->{'branch'},
978 $item->{'itemnumber'}
981 &ModDateLastSeen( $item->{'itemnumber'} );
982 # If it costs to borrow this book, charge it to the patron's account.
983 my ( $charge, $itemtype ) = GetIssuingCharges(
984 $item->{'itemnumber'},
985 $borrower->{'borrowernumber'}
989 $item->{'itemnumber'},
990 $borrower->{'borrowernumber'}, $charge
992 $item->{'charge'} = $charge;
995 # Record the fact that this book was issued.
997 C4::Context->userenv->{'branch'},
999 '', $item->{'itemnumber'},
1000 $item->{'itemtype'}, $borrower->{'borrowernumber'}
1004 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'})
1005 if C4::Context->preference("IssueLog");
1010 =head2 GetLoanLength
1012 Get loan length for an itemtype, a borrower type and a branch
1014 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1019 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1020 my $dbh = C4::Context->dbh;
1023 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1026 # try to find issuelength & return the 1st available.
1027 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1028 $sth->execute( $borrowertype, $itemtype, $branchcode );
1029 my $loanlength = $sth->fetchrow_hashref;
1030 return $loanlength->{issuelength}
1031 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1033 $sth->execute( $borrowertype, $itemtype, "*" );
1034 $loanlength = $sth->fetchrow_hashref;
1035 return $loanlength->{issuelength}
1036 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1038 $sth->execute( $borrowertype, "*", $branchcode );
1039 $loanlength = $sth->fetchrow_hashref;
1040 return $loanlength->{issuelength}
1041 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1043 $sth->execute( "*", $itemtype, $branchcode );
1044 $loanlength = $sth->fetchrow_hashref;
1045 return $loanlength->{issuelength}
1046 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1048 $sth->execute( $borrowertype, "*", "*" );
1049 $loanlength = $sth->fetchrow_hashref;
1050 return $loanlength->{issuelength}
1051 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1053 $sth->execute( "*", "*", $branchcode );
1054 $loanlength = $sth->fetchrow_hashref;
1055 return $loanlength->{issuelength}
1056 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1058 $sth->execute( "*", $itemtype, "*" );
1059 $loanlength = $sth->fetchrow_hashref;
1060 return $loanlength->{issuelength}
1061 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1063 $sth->execute( "*", "*", "*" );
1064 $loanlength = $sth->fetchrow_hashref;
1065 return $loanlength->{issuelength}
1066 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1068 # if no rule is set => 21 days (hardcoded)
1074 ($doreturn, $messages, $iteminformation, $borrower) =
1075 &AddReturn($barcode, $branch);
1079 C<$barcode> is the bar code of the book being returned. C<$branch> is
1080 the code of the branch where the book is being returned.
1082 C<&AddReturn> returns a list of four items:
1084 C<$doreturn> is true iff the return succeeded.
1086 C<$messages> is a reference-to-hash giving the reason for failure:
1092 No item with this barcode exists. The value is C<$barcode>.
1096 The book is not currently on loan. The value is C<$barcode>.
1098 =item C<IsPermanent>
1100 The book's home branch is a permanent collection. If you have borrowed
1101 this book, you are not allowed to return it. The value is the code for
1102 the book's home branch.
1106 This book has been withdrawn/cancelled. The value should be ignored.
1110 The item was reserved. The value is a reference-to-hash whose keys are
1111 fields from the reserves table of the Koha database, and
1112 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1113 either C<Waiting>, C<Reserved>, or 0.
1117 C<$borrower> is a reference-to-hash, giving information about the
1118 patron who last borrowed the book.
1123 my ( $barcode, $branch ) = @_;
1124 my $dbh = C4::Context->dbh;
1128 my $validTransfert = 0;
1129 my $reserveDone = 0;
1131 # get information on item
1132 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1133 unless ($iteminformation->{'itemnumber'} ) {
1134 $messages->{'BadBarcode'} = $barcode;
1138 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1139 $messages->{'NotIssued'} = $barcode;
1143 # check if the book is in a permanent collection....
1144 my $hbr = $iteminformation->{'homebranch'};
1145 my $branches = GetBranches();
1146 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1147 $messages->{'IsPermanent'} = $hbr;
1150 # check that the book has been cancelled
1151 if ( $iteminformation->{'wthdrawn'} ) {
1152 $messages->{'wthdrawn'} = 1;
1156 # new op dev : if the book returned in an other branch update the holding branch
1158 # update issues, thereby returning book (should push this out into another subroutine
1159 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1161 # case of a return of document (deal with issues and holdingbranch)
1166 "UPDATE issues SET returndate = now() WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (returndate IS NULL)"
1168 $sth->execute( $borrower->{'borrowernumber'},
1169 $iteminformation->{'itemnumber'} );
1170 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1173 # continue to deal with returns cases, but not only if we have an issue
1175 # the holdingbranch is updated if the document is returned in an other location .
1176 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} )
1178 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1179 # reload iteminformation holdingbranch with the userenv value
1180 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1182 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1183 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1185 # fix up the accounts.....
1186 if ( $iteminformation->{'itemlost'} ) {
1187 $messages->{'WasLost'} = 1;
1190 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1191 # check if we have a transfer for this document
1192 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1194 # if we have a transfer to do, we update the line of transfers with the datearrived
1196 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1199 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1201 $sth->execute( $iteminformation->{'itemnumber'} );
1203 # 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'
1204 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1207 $messages->{'WrongTransfer'} = $tobranch;
1208 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1210 $validTransfert = 1;
1213 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1214 # fix up the accounts.....
1215 if ($iteminformation->{'itemlost'}) {
1216 FixAccountForLostAndReturned($iteminformation, $borrower);
1217 $messages->{'WasLost'} = 1;
1219 # fix up the overdues in accounts...
1220 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1221 $iteminformation->{'itemnumber'} );
1223 # find reserves.....
1224 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1225 my ( $resfound, $resrec ) =
1226 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1228 $resrec->{'ResFound'} = $resfound;
1229 $messages->{'ResFound'} = $resrec;
1234 # Record the fact that this book was returned.
1236 $branch, 'return', '0', '',
1237 $iteminformation->{'itemnumber'},
1238 $iteminformation->{'itemtype'},
1239 $borrower->{'borrowernumber'}
1242 &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'})
1243 if C4::Context->preference("ReturnLog");
1245 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1246 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1248 if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1249 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1250 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1251 $messages->{'WasTransfered'} = 1;
1252 warn "was transfered";
1256 return ( $doreturn, $messages, $iteminformation, $borrower );
1259 =head2 FixOverduesOnReturn
1261 &FixOverduesOnReturn($brn,$itm);
1263 C<$brn> borrowernumber
1267 internal function, called only by AddReturn
1271 sub FixOverduesOnReturn {
1272 my ( $borrowernumber, $item ) = @_;
1273 my $dbh = C4::Context->dbh;
1275 # check for overdue fine
1278 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1280 $sth->execute( $borrowernumber, $item );
1282 # alter fine to show that the book has been returned
1283 if ( my $data = $sth->fetchrow_hashref ) {
1286 "UPDATE accountlines SET accounttype='F' WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accountno = ?)"
1288 $usth->execute( $borrowernumber, $item, $data->{'accountno'} );
1295 =head2 FixAccountForLostAndReturned
1297 &FixAccountForLostAndReturned($iteminfo,$borrower);
1299 Calculates the charge for a book lost and returned (Not exported & used only once)
1301 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1303 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1305 Internal function, called by AddReturn
1309 sub FixAccountForLostAndReturned {
1310 my ($iteminfo, $borrower) = @_;
1312 my $dbh = C4::Context->dbh;
1313 my $itm = $iteminfo->{'itemnumber'};
1314 # check for charge made for lost book
1315 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1316 $sth->execute($itm);
1317 if (my $data = $sth->fetchrow_hashref) {
1318 # writeoff this amount
1320 my $amount = $data->{'amount'};
1321 my $acctno = $data->{'accountno'};
1323 if ($data->{'amountoutstanding'} == $amount) {
1324 $offset = $data->{'amount'};
1327 $offset = $amount - $data->{'amountoutstanding'};
1328 $amountleft = $data->{'amountoutstanding'} - $amount;
1330 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1331 WHERE (borrowernumber = ?)
1332 AND (itemnumber = ?) AND (accountno = ?) ");
1333 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1335 #check if any credit is left if so writeoff other accounts
1336 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1337 if ($amountleft < 0){
1340 if ($amountleft > 0){
1341 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1342 AND (amountoutstanding >0) ORDER BY date");
1343 $msth->execute($data->{'borrowernumber'});
1344 # offset transactions
1347 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1348 if ($accdata->{'amountoutstanding'} < $amountleft) {
1350 $amountleft -= $accdata->{'amountoutstanding'};
1352 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1355 my $thisacct = $accdata->{'accountno'};
1356 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1357 WHERE (borrowernumber = ?)
1358 AND (accountno=?)");
1359 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1361 $usth = $dbh->prepare("INSERT INTO accountoffsets
1362 (borrowernumber, accountno, offsetaccount, offsetamount)
1365 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1370 if ($amountleft > 0){
1373 my $desc="Book Returned ".$iteminfo->{'barcode'};
1374 $usth = $dbh->prepare("INSERT INTO accountlines
1375 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1376 VALUES (?,?,now(),?,?,'CR',?)");
1377 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1379 $usth = $dbh->prepare("INSERT INTO accountoffsets
1380 (borrowernumber, accountno, offsetaccount, offsetamount)
1382 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1384 $usth = $dbh->prepare("UPDATE items SET paidfor='' WHERE itemnumber=?");
1385 $usth->execute($itm);
1394 $issues = &GetItemIssue($itemnumber);
1396 Returns patrons currently having a book. nothing if item is not issued atm
1398 C<$itemnumber> is the itemnumber
1400 Returns an array of hashes
1404 my ( $itemnumber) = @_;
1405 return unless $itemnumber;
1406 my $dbh = C4::Context->dbh;
1410 my $today = POSIX::strftime("%Y%m%d", localtime);
1412 my $sth = $dbh->prepare(
1413 "SELECT * FROM issues
1414 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1416 issues.itemnumber=? AND returndate IS NULL ");
1417 $sth->execute($itemnumber);
1418 my $data = $sth->fetchrow_hashref;
1419 my $datedue = $data->{'date_due'};
1421 if ( $datedue < $today ) {
1422 $data->{'overdue'} = 1;
1424 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1429 =head2 GetItemIssues
1431 $issues = &GetItemIssues($itemnumber, $history);
1433 Returns patrons that have issued a book
1435 C<$itemnumber> is the itemnumber
1436 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1438 Returns an array of hashes
1442 my ( $itemnumber,$history ) = @_;
1443 my $dbh = C4::Context->dbh;
1447 my $today = POSIX::strftime("%Y%m%d", localtime);
1449 my $sth = $dbh->prepare(
1450 "SELECT * FROM issues
1451 LEFT JOIN borrowers ON borrowers.borrowernumber
1452 LEFT JOIN items ON items.itemnumber=issues.itemnumber
1454 issues.itemnumber=?".($history?"":" AND returndate IS NULL ").
1455 "ORDER BY issues.date_due DESC"
1457 $sth->execute($itemnumber);
1458 while ( my $data = $sth->fetchrow_hashref ) {
1459 my $datedue = $data->{'date_due'};
1461 if ( $datedue < $today ) {
1462 $data->{'overdue'} = 1;
1464 my $itemnumber = $data->{'itemnumber'};
1465 push @GetItemIssues, $data;
1468 return ( \@GetItemIssues );
1471 =head2 GetBiblioIssues
1473 $issues = GetBiblioIssues($biblionumber);
1475 this function get all issues from a biblionumber.
1478 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1479 tables issues and the firstname,surname & cardnumber from borrowers.
1483 sub GetBiblioIssues {
1484 my $biblionumber = shift;
1485 return undef unless $biblionumber;
1486 my $dbh = C4::Context->dbh;
1488 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1490 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1491 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1492 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1493 LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1494 WHERE biblio.biblionumber = ?
1495 ORDER BY issues.timestamp
1497 my $sth = $dbh->prepare($query);
1498 $sth->execute($biblionumber);
1501 while ( my $data = $sth->fetchrow_hashref ) {
1502 push @issues, $data;
1507 =head2 CanBookBeRenewed
1509 $ok = &CanBookBeRenewed($borrowernumber, $itemnumber);
1511 Find out whether a borrowed item may be renewed.
1513 C<$dbh> is a DBI handle to the Koha database.
1515 C<$borrowernumber> is the borrower number of the patron who currently
1516 has the item on loan.
1518 C<$itemnumber> is the number of the item to renew.
1520 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1521 item must currently be on loan to the specified borrower; renewals
1522 must be allowed for the item's type; and the borrower must not have
1523 already renewed the loan.
1527 sub CanBookBeRenewed {
1529 # check renewal status
1530 my ( $borrowernumber, $itemnumber ) = @_;
1531 my $dbh = C4::Context->dbh;
1535 # Look in the issues table for this item, lent to this borrower,
1536 # and not yet returned.
1538 # FIXME - I think this function could be redone to use only one SQL call.
1539 my $sth1 = $dbh->prepare(
1540 "SELECT * FROM issues
1541 WHERE borrowernumber = ?
1543 AND returndate IS NULL"
1545 $sth1->execute( $borrowernumber, $itemnumber );
1546 if ( my $data1 = $sth1->fetchrow_hashref ) {
1548 # Found a matching item
1550 # See if this item may be renewed. This query is convoluted
1551 # because it's a bit messy: given the item number, we need to find
1552 # the biblioitem, which gives us the itemtype, which tells us
1553 # whether it may be renewed.
1554 my $sth2 = $dbh->prepare(
1555 "SELECT renewalsallowed FROM items
1556 LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1557 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1558 WHERE items.itemnumber = ?
1561 $sth2->execute($itemnumber);
1562 if ( my $data2 = $sth2->fetchrow_hashref ) {
1563 $renews = $data2->{'renewalsallowed'};
1565 if ( $renews && $renews >= $data1->{'renewals'} ) {
1569 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1576 return ($renewokay);
1581 &AddRenewal($borrowernumber, $itemnumber, $datedue);
1585 C<$borrowernumber> is the borrower number of the patron who currently
1588 C<$itemnumber> is the number of the item to renew.
1590 C<$datedue> can be used to set the due date. If C<$datedue> is the
1591 empty string, C<&AddRenewal> will calculate the due date automatically
1592 from the book's item type. If you wish to set the due date manually,
1593 C<$datedue> should be in the form YYYY-MM-DD.
1599 my ( $borrowernumber, $itemnumber, $branch ,$datedue ) = @_;
1600 my $dbh = C4::Context->dbh;
1602 # If the due date wasn't specified, calculate it by adding the
1603 # book's loan length to today's date.
1604 unless ( $datedue ) {
1606 my $biblio = GetBiblioFromItemNumber($itemnumber);
1607 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
1608 my $loanlength = GetLoanLength(
1609 $borrower->{'categorycode'},
1610 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1611 $borrower->{'branchcode'}
1613 #FIXME -- choose issuer or borrower branch.
1614 #FIXME -- where's the calendar ?
1615 my ( $due_year, $due_month, $due_day ) =
1616 Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
1617 $datedue = C4::Dates->new( "$due_year-$due_month-$due_day",'iso');
1618 $datedue=CheckValidDatedue($datedue,$itemnumber,$branch);
1621 # Find the issues record for this book
1623 $dbh->prepare("SELECT * FROM issues
1624 WHERE borrowernumber=?
1626 AND returndate IS NULL"
1628 $sth->execute( $borrowernumber, $itemnumber );
1629 my $issuedata = $sth->fetchrow_hashref;
1632 # Update the issues record to have the new due date, and a new count
1633 # of how many times it has been renewed.
1634 my $renews = $issuedata->{'renewals'} + 1;
1635 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1636 WHERE borrowernumber=?
1638 AND returndate IS NULL"
1640 $sth->execute( $datedue->output('iso'), $renews, $borrowernumber, $itemnumber );
1645 # Charge a new rental fee, if applicable?
1646 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1647 if ( $charge > 0 ) {
1648 my $accountno = getnextacctno( $borrowernumber );
1649 my $item = GetBiblioFromItemNumber($itemnumber);
1650 $sth = $dbh->prepare(
1651 "INSERT INTO accountlines
1652 (borrowernumber,accountno,date,amount,
1653 description,accounttype,amountoutstanding,
1655 VALUES (?,?,now(),?,?,?,?,?)"
1657 $sth->execute( $borrowernumber, $accountno, $charge,
1658 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1659 'Rent', $charge, $itemnumber );
1662 UpdateStats( C4::Context->userenv->{'branchcode'}, 'renew', $charge, '', $itemnumber );
1665 =head2 GetIssuingCharges
1667 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1669 Calculate how much it would cost for a given patron to borrow a given
1670 item, including any applicable discounts.
1672 C<$itemnumber> is the item number of item the patron wishes to borrow.
1674 C<$borrowernumber> is the patron's borrower number.
1676 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1677 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1682 sub GetIssuingCharges {
1684 # calculate charges due
1685 my ( $itemnumber, $borrowernumber ) = @_;
1687 my $dbh = C4::Context->dbh;
1690 # Get the book's item type and rental charge (via its biblioitem).
1691 my $qcharge = "SELECT itemtypes.itemtype,rentalcharge FROM items
1692 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1693 $qcharge .= (C4::Context->preference('item-level_itypes'))
1694 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1695 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1697 $qcharge .= "WHERE items.itemnumber =?";
1699 my $sth1 = $dbh->prepare($qcharge);
1700 $sth1->execute($itemnumber);
1701 if ( my $data1 = $sth1->fetchrow_hashref ) {
1702 $item_type = $data1->{'itemtype'};
1703 $charge = $data1->{'rentalcharge'};
1704 my $q2 = "SELECT rentaldiscount FROM borrowers
1705 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1706 WHERE borrowers.borrowernumber = ?
1707 AND issuingrules.itemtype = ?";
1708 my $sth2 = $dbh->prepare($q2);
1709 $sth2->execute( $borrowernumber, $item_type );
1710 if ( my $data2 = $sth2->fetchrow_hashref ) {
1711 my $discount = $data2->{'rentaldiscount'};
1712 if ( $discount eq 'NULL' ) {
1715 $charge = ( $charge * ( 100 - $discount ) ) / 100;
1721 return ( $charge, $item_type );
1724 =head2 AddIssuingCharge
1726 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1730 sub AddIssuingCharge {
1731 my ( $itemnumber, $borrowernumber, $charge ) = @_;
1732 my $dbh = C4::Context->dbh;
1733 my $nextaccntno = getnextacctno( $borrowernumber );
1735 INSERT INTO accountlines
1736 (borrowernumber, itemnumber, accountno,
1737 date, amount, description, accounttype,
1739 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1741 my $sth = $dbh->prepare($query);
1742 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1748 GetTransfers($itemnumber);
1753 my ($itemnumber) = @_;
1755 my $dbh = C4::Context->dbh;
1761 FROM branchtransfers
1762 WHERE itemnumber = ?
1763 AND datearrived IS NULL
1765 my $sth = $dbh->prepare($query);
1766 $sth->execute($itemnumber);
1767 my @row = $sth->fetchrow_array();
1773 =head2 GetTransfersFromTo
1775 @results = GetTransfersFromTo($frombranch,$tobranch);
1777 Returns the list of pending transfers between $from and $to branch
1781 sub GetTransfersFromTo {
1782 my ( $frombranch, $tobranch ) = @_;
1783 return unless ( $frombranch && $tobranch );
1784 my $dbh = C4::Context->dbh;
1786 SELECT itemnumber,datesent,frombranch
1787 FROM branchtransfers
1790 AND datearrived IS NULL
1792 my $sth = $dbh->prepare($query);
1793 $sth->execute( $frombranch, $tobranch );
1796 while ( my $data = $sth->fetchrow_hashref ) {
1797 push @gettransfers, $data;
1800 return (@gettransfers);
1803 =head2 DeleteTransfer
1805 &DeleteTransfer($itemnumber);
1809 sub DeleteTransfer {
1810 my ($itemnumber) = @_;
1811 my $dbh = C4::Context->dbh;
1812 my $sth = $dbh->prepare(
1813 "DELETE FROM branchtransfers
1815 AND datearrived IS NULL "
1817 $sth->execute($itemnumber);
1821 =head2 AnonymiseIssueHistory
1823 $rows = AnonymiseIssueHistory($borrowernumber,$date)
1825 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
1826 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
1828 return the number of affected rows.
1832 sub AnonymiseIssueHistory {
1834 my $borrowernumber = shift;
1835 my $dbh = C4::Context->dbh;
1838 SET borrowernumber = NULL
1839 WHERE returndate < '".$date."'
1840 AND borrowernumber IS NOT NULL
1842 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
1843 my $rows_affected = $dbh->do($query);
1844 return $rows_affected;
1847 =head2 updateWrongTransfer
1849 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
1851 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
1855 sub updateWrongTransfer {
1856 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
1857 my $dbh = C4::Context->dbh;
1858 # first step validate the actual line of transfert .
1861 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
1863 $sth->execute($FromLibrary,$itemNumber);
1866 # second step create a new line of branchtransfer to the right location .
1867 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
1869 #third step changing holdingbranch of item
1870 UpdateHoldingbranch($FromLibrary,$itemNumber);
1873 =head2 UpdateHoldingbranch
1875 $items = UpdateHoldingbranch($branch,$itmenumber);
1876 Simple methode for updating hodlingbranch in items BDD line
1879 sub UpdateHoldingbranch {
1880 my ( $branch,$itmenumber ) = @_;
1881 my $dbh = C4::Context->dbh;
1882 # first step validate the actual line of transfert .
1885 "update items set holdingbranch = ? where itemnumber= ?"
1887 $sth->execute($branch,$itmenumber);
1892 =head2 CheckValidDatedue
1894 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
1895 this function return a new date due after checked if it's a repeatable or special holiday
1896 C<$date_due> = returndate calculate with no day check
1897 C<$itemnumber> = itemnumber
1898 C<$branchcode> = localisation of issue
1900 # Why not create calendar object? -
1901 # TODO add 'duedate' option to useDaysMode .
1902 sub CheckValidDatedue {
1903 my ($date_due,$itemnumber,$branchcode)=@_;
1904 my @datedue=split('-',$date_due->output('iso'));
1905 my $years=$datedue[0];
1906 my $month=$datedue[1];
1907 my $day=$datedue[2];
1909 for (my $i=0;$i<2;$i++){
1910 $dow=Day_of_Week($years,$month,$day);
1911 ($dow=0) if ($dow>6);
1912 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
1913 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1914 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1915 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
1917 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
1920 my $newdatedue=C4::Dates->new( $years."-".$month."-".$day,'iso');
1923 =head2 CheckRepeatableHolidays
1925 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
1926 this function check if the date due is a repeatable holiday
1927 C<$date_due> = returndate calculate with no day check
1928 C<$itemnumber> = itemnumber
1929 C<$branchcode> = localisation of issue
1933 sub CheckRepeatableHolidays{
1934 my($itemnumber,$week_day,$branchcode)=@_;
1935 my $dbh = C4::Context->dbh;
1936 my $query = qq|SELECT count(*)
1937 FROM repeatable_holidays
1940 my $sth = $dbh->prepare($query);
1941 $sth->execute($branchcode,$week_day);
1942 my $result=$sth->fetchrow;
1948 =head2 CheckSpecialHolidays
1950 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1951 this function check if the date is a special holiday
1952 C<$years> = the years of datedue
1953 C<$month> = the month of datedue
1954 C<$day> = the day of datedue
1955 C<$itemnumber> = itemnumber
1956 C<$branchcode> = localisation of issue
1958 sub CheckSpecialHolidays{
1959 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
1960 my $dbh = C4::Context->dbh;
1961 my $query=qq|SELECT count(*)
1962 FROM `special_holidays`
1968 my $sth = $dbh->prepare($query);
1969 $sth->execute($years,$month,$day,$branchcode);
1970 my $countspecial=$sth->fetchrow ;
1972 return $countspecial;
1975 =head2 CheckRepeatableSpecialHolidays
1977 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1978 this function check if the date is a repeatble special holidays
1979 C<$month> = the month of datedue
1980 C<$day> = the day of datedue
1981 C<$itemnumber> = itemnumber
1982 C<$branchcode> = localisation of issue
1984 sub CheckRepeatableSpecialHolidays{
1985 my ($month,$day,$itemnumber,$branchcode) = @_;
1986 my $dbh = C4::Context->dbh;
1987 my $query=qq|SELECT count(*)
1988 FROM `repeatable_holidays`
1993 my $sth = $dbh->prepare($query);
1994 $sth->execute($month,$day,$branchcode);
1995 my $countspecial=$sth->fetchrow ;
1997 return $countspecial;
2002 sub CheckValidBarcode{
2004 my $dbh = C4::Context->dbh;
2005 my $query=qq|SELECT count(*)
2009 my $sth = $dbh->prepare($query);
2010 $sth->execute($barcode);
2011 my $exist=$sth->fetchrow ;
2022 Koha Developement team <info@koha.org>