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
22 #use warnings; # soon!
42 use POSIX qw(strftime);
43 use C4::Branch; # GetBranches
44 use C4::Log; # logaction
48 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
52 $VERSION = 3.02; # for version checking
55 # FIXME subs that should probably be elsewhere
61 # subs to deal with issuing a book
74 &GetBranchBorrowerCircRule
76 &AnonymiseIssueHistory
79 # subs to deal with returns
85 # subs to deal with transfers
92 &IsBranchTransferAllowed
93 &CreateBranchTransferLimit
94 &DeleteBranchTransferLimits
100 C4::Circulation - Koha circulation module
108 The functions in this module deal with circulation, issues, and
109 returns, as well as general information about the library.
110 Also deals with stocktaking.
116 =head3 $str = &barcodedecode($barcode);
120 =item Generic filter function for barcode string.
121 Called on every circ if the System Pref itemBarcodeInputFilter is set.
122 Will do some manipulation of the barcode for systems that deliver a barcode
123 to circulation.pl that differs from the barcode stored for the item.
124 For proper functioning of this filter, calling the function on the
125 correct barcode string (items.barcode) should return an unaltered barcode.
131 # FIXME -- the &decode fcn below should be wrapped into this one.
132 # FIXME -- these plugins should be moved out of Circulation.pm
136 my $filter = C4::Context->preference('itemBarcodeInputFilter');
137 if($filter eq 'whitespace') {
140 } elsif($filter eq 'cuecat') {
142 my @fields = split( /\./, $barcode );
143 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
144 if ( $#results == 2 ) {
150 } elsif($filter eq 'T-prefix') {
151 if ( $barcode =~ /^[Tt]/) {
152 if (substr($barcode,1,1) eq '0') {
155 $barcode = substr($barcode,2) + 0 ;
158 return sprintf( "T%07d",$barcode);
164 =head3 $str = &decode($chunk);
168 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
178 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
179 my @s = map { index( $seq, $_ ); } split( //, $encoded );
180 my $l = ( $#s + 1 ) % 4;
191 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
193 chr( ( $n >> 16 ) ^ 67 )
194 .chr( ( $n >> 8 & 255 ) ^ 67 )
195 .chr( ( $n & 255 ) ^ 67 );
198 $r = substr( $r, 0, length($r) - $l );
204 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
206 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
208 C<$newbranch> is the code for the branch to which the item should be transferred.
210 C<$barcode> is the barcode of the item to be transferred.
212 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
213 Otherwise, if an item is reserved, the transfer fails.
215 Returns three values:
219 is true if the transfer was successful.
223 is a reference-to-hash which may have any of the following keys:
229 There is no item in the catalog with the given barcode. The value is C<$barcode>.
233 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.
235 =item C<DestinationEqualsHolding>
237 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.
241 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.
245 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>.
247 =item C<WasTransferred>
249 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
256 my ( $tbr, $barcode, $ignoreRs ) = @_;
259 my $branches = GetBranches();
260 my $itemnumber = GetItemnumberFromBarcode( $barcode );
261 my $issue = GetItemIssue($itemnumber);
262 my $biblio = GetBiblioFromItemNumber($itemnumber);
265 if ( not $itemnumber ) {
266 $messages->{'BadBarcode'} = $barcode;
270 # get branches of book...
271 my $hbr = $biblio->{'homebranch'};
272 my $fbr = $biblio->{'holdingbranch'};
274 # if using Branch Transfer Limits
275 if ( C4::Context->preference("UseBranchTransferLimits") == 1 ) {
276 if ( C4::Context->preference("item-level_itypes") ) {
277 if ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itype'} ) ) {
278 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itype'};
281 } elsif ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itemtype'} ) ) {
282 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itemtype'};
288 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
289 $messages->{'IsPermanent'} = $hbr;
293 # can't transfer book if is already there....
294 if ( $fbr eq $tbr ) {
295 $messages->{'DestinationEqualsHolding'} = 1;
299 # check if it is still issued to someone, return it...
300 if ($issue->{borrowernumber}) {
301 AddReturn( $barcode, $fbr );
302 $messages->{'WasReturned'} = $issue->{borrowernumber};
306 # That'll save a database query.
307 my ( $resfound, $resrec ) =
308 CheckReserves( $itemnumber );
309 if ( $resfound and not $ignoreRs ) {
310 $resrec->{'ResFound'} = $resfound;
312 # $messages->{'ResFound'} = $resrec;
316 #actually do the transfer....
318 ModItemTransfer( $itemnumber, $fbr, $tbr );
320 # don't need to update MARC anymore, we do it in batch now
321 $messages->{'WasTransfered'} = 1;
322 ModDateLastSeen( $itemnumber );
324 return ( $dotransfer, $messages, $biblio );
329 my $borrower = shift;
330 my $biblionumber = shift;
332 my $cat_borrower = $borrower->{'categorycode'};
333 my $dbh = C4::Context->dbh;
335 # Get which branchcode we need
336 if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
337 $branch = C4::Context->userenv->{'branch'};
339 elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
340 $branch = $borrower->{'branchcode'};
344 $branch = $item->{'homebranch'};
346 my $type = (C4::Context->preference('item-level_itypes'))
347 ? $item->{'itype'} # item-level
348 : $item->{'itemtype'}; # biblio-level
350 # given branch, patron category, and item type, determine
351 # applicable issuing rule
352 my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
354 # if a rule is found and has a loan limit set, count
355 # how many loans the patron already has that meet that
357 if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
359 my $count_query = "SELECT COUNT(*) FROM issues
360 JOIN items USING (itemnumber) ";
362 my $rule_itemtype = $issuing_rule->{itemtype};
363 if ($rule_itemtype eq "*") {
364 # matching rule has the default item type, so count only
365 # those existing loans that don't fall under a more
367 if (C4::Context->preference('item-level_itypes')) {
368 $count_query .= " WHERE items.itype NOT IN (
369 SELECT itemtype FROM issuingrules
371 AND (categorycode = ? OR categorycode = ?)
375 $count_query .= " JOIN biblioitems USING (biblionumber)
376 WHERE biblioitems.itemtype NOT IN (
377 SELECT itemtype FROM issuingrules
379 AND (categorycode = ? OR categorycode = ?)
383 push @bind_params, $issuing_rule->{branchcode};
384 push @bind_params, $issuing_rule->{categorycode};
385 push @bind_params, $cat_borrower;
387 # rule has specific item type, so count loans of that
389 if (C4::Context->preference('item-level_itypes')) {
390 $count_query .= " WHERE items.itype = ? ";
392 $count_query .= " JOIN biblioitems USING (biblionumber)
393 WHERE biblioitems.itemtype= ? ";
395 push @bind_params, $type;
398 $count_query .= " AND borrowernumber = ? ";
399 push @bind_params, $borrower->{'borrowernumber'};
400 my $rule_branch = $issuing_rule->{branchcode};
401 if ($rule_branch ne "*") {
402 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
403 $count_query .= " AND issues.branchcode = ? ";
404 push @bind_params, $branch;
405 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
406 ; # if branch is the patron's home branch, then count all loans by patron
408 $count_query .= " AND items.homebranch = ? ";
409 push @bind_params, $branch;
413 my $count_sth = $dbh->prepare($count_query);
414 $count_sth->execute(@bind_params);
415 my ($current_loan_count) = $count_sth->fetchrow_array;
417 my $max_loans_allowed = $issuing_rule->{'maxissueqty'};
418 if ($current_loan_count >= $max_loans_allowed) {
419 return "$current_loan_count / $max_loans_allowed";
423 # Now count total loans against the limit for the branch
424 my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
425 if (defined($branch_borrower_circ_rule->{maxissueqty})) {
426 my @bind_params = ();
427 my $branch_count_query = "SELECT COUNT(*) FROM issues
428 JOIN items USING (itemnumber)
429 WHERE borrowernumber = ? ";
430 push @bind_params, $borrower->{borrowernumber};
432 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
433 $branch_count_query .= " AND issues.branchcode = ? ";
434 push @bind_params, $branch;
435 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
436 ; # if branch is the patron's home branch, then count all loans by patron
438 $branch_count_query .= " AND items.homebranch = ? ";
439 push @bind_params, $branch;
441 my $branch_count_sth = $dbh->prepare($branch_count_query);
442 $branch_count_sth->execute(@bind_params);
443 my ($current_loan_count) = $branch_count_sth->fetchrow_array;
445 my $max_loans_allowed = $branch_borrower_circ_rule->{maxissueqty};
446 if ($current_loan_count >= $max_loans_allowed) {
447 return "$current_loan_count / $max_loans_allowed";
451 # OK, the patron can issue !!!
457 @issues = &itemissues($biblioitemnumber, $biblio);
459 Looks up information about who has borrowed the bookZ<>(s) with the
460 given biblioitemnumber.
462 C<$biblio> is ignored.
464 C<&itemissues> returns an array of references-to-hash. The keys
465 include the fields from the C<items> table in the Koha database.
466 Additional keys include:
472 If the item is currently on loan, this gives the due date.
474 If the item is not on loan, then this is either "Available" or
475 "Cancelled", if the item has been withdrawn.
479 If the item is currently on loan, this gives the card number of the
480 patron who currently has the item.
482 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
484 These give the timestamp for the last three times the item was
487 =item C<card0>, C<card1>, C<card2>
489 The card number of the last three patrons who borrowed this item.
491 =item C<borrower0>, C<borrower1>, C<borrower2>
493 The borrower number of the last three patrons who borrowed this item.
501 my ( $bibitem, $biblio ) = @_;
502 my $dbh = C4::Context->dbh;
504 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
509 $sth->execute($bibitem) || die $sth->errstr;
511 while ( my $data = $sth->fetchrow_hashref ) {
513 # Find out who currently has this item.
514 # FIXME - Wouldn't it be better to do this as a left join of
515 # some sort? Currently, this code assumes that if
516 # fetchrow_hashref() fails, then the book is on the shelf.
517 # fetchrow_hashref() can fail for any number of reasons (e.g.,
518 # database server crash), not just because no items match the
520 my $sth2 = $dbh->prepare(
521 "SELECT * FROM issues
522 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
527 $sth2->execute( $data->{'itemnumber'} );
528 if ( my $data2 = $sth2->fetchrow_hashref ) {
529 $data->{'date_due'} = $data2->{'date_due'};
530 $data->{'card'} = $data2->{'cardnumber'};
531 $data->{'borrower'} = $data2->{'borrowernumber'};
534 $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
539 # Find the last 3 people who borrowed this item.
540 $sth2 = $dbh->prepare(
541 "SELECT * FROM old_issues
542 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
544 ORDER BY returndate DESC,timestamp DESC"
547 $sth2->execute( $data->{'itemnumber'} );
548 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
549 { # FIXME : error if there is less than 3 pple borrowing this item
550 if ( my $data2 = $sth2->fetchrow_hashref ) {
551 $data->{"timestamp$i2"} = $data2->{'timestamp'};
552 $data->{"card$i2"} = $data2->{'cardnumber'};
553 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
558 $results[$i] = $data;
566 =head2 CanBookBeIssued
568 Check if a book can be issued.
570 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
572 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
576 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
578 =item C<$barcode> is the bar code of the book being issued.
580 =item C<$duedatespec> is a C4::Dates object.
590 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
591 Possible values are :
597 sticky due date is invalid
601 borrower gone with no address
605 borrower declared it's card lost
611 =head3 UNKNOWN_BARCODE
625 item is restricted (set by ??)
627 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
628 Possible values are :
636 renewing, not issuing
638 =head3 ISSUED_TO_ANOTHER
640 issued to someone else.
644 reserved for someone else.
648 sticky due date is invalid
652 if the borrower borrows to much things
656 sub CanBookBeIssued {
657 my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
658 my %needsconfirmation; # filled with problems that needs confirmations
659 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
660 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
661 my $issue = GetItemIssue($item->{itemnumber});
662 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
663 $item->{'itemtype'}=$item->{'itype'};
664 my $dbh = C4::Context->dbh;
667 # DUE DATE is OK ? -- should already have checked.
669 #$issuingimpossible{INVALID_DATE} = 1 unless ($duedate);
674 if ( $borrower->{'category_type'} eq 'X' && ( $item->{barcode} )) {
675 # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
676 &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
677 return( { STATS => 1 }, {});
679 if ( $borrower->{flags}->{GNA} ) {
680 $issuingimpossible{GNA} = 1;
682 if ( $borrower->{flags}->{'LOST'} ) {
683 $issuingimpossible{CARD_LOST} = 1;
685 if ( $borrower->{flags}->{'DBARRED'} ) {
686 $issuingimpossible{DEBARRED} = 1;
688 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
689 $issuingimpossible{EXPIRED} = 1;
691 my @expirydate= split /-/,$borrower->{'dateexpiry'};
692 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
693 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
694 $issuingimpossible{EXPIRED} = 1;
703 C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
704 if ( C4::Context->preference("IssuingInProcess") ) {
705 my $amountlimit = C4::Context->preference("noissuescharge");
706 if ( $amount > $amountlimit && !$inprocess ) {
707 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
709 elsif ( $amount > 0 && $amount <= $amountlimit && !$inprocess ) {
710 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
715 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
720 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
722 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
723 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
728 unless ( $item->{barcode} ) {
729 $issuingimpossible{UNKNOWN_BARCODE} = 1;
731 if ( $item->{'notforloan'}
732 && $item->{'notforloan'} > 0 )
734 $issuingimpossible{NOT_FOR_LOAN} = 1;
736 elsif ( !$item->{'notforloan'} ){
737 # we have to check itemtypes.notforloan also
738 if (C4::Context->preference('item-level_itypes')){
739 # this should probably be a subroutine
740 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
741 $sth->execute($item->{'itemtype'});
742 my $notforloan=$sth->fetchrow_hashref();
744 if ($notforloan->{'notforloan'} == 1){
745 $issuingimpossible{NOT_FOR_LOAN} = 1;
748 elsif ($biblioitem->{'notforloan'} == 1){
749 $issuingimpossible{NOT_FOR_LOAN} = 1;
752 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
754 $issuingimpossible{WTHDRAWN} = 1;
756 if ( $item->{'restricted'}
757 && $item->{'restricted'} == 1 )
759 $issuingimpossible{RESTRICTED} = 1;
761 if ( C4::Context->preference("IndependantBranches") ) {
762 my $userenv = C4::Context->userenv;
763 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
764 $issuingimpossible{NOTSAMEBRANCH} = 1
765 if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
770 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
772 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
775 # Already issued to current borrower. Ask whether the loan should
777 my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
778 $borrower->{'borrowernumber'},
779 $item->{'itemnumber'}
781 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
782 $issuingimpossible{NO_MORE_RENEWALS} = 1;
785 $needsconfirmation{RENEW_ISSUE} = 1;
788 elsif ($issue->{borrowernumber}) {
790 # issued to someone else
791 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
793 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
794 $needsconfirmation{ISSUED_TO_ANOTHER} =
795 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
798 # See if the item is on reserve.
799 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
801 my $resbor = $res->{'borrowernumber'};
802 my ( $resborrower ) = C4::Members::GetMemberDetails( $resbor, 0 );
803 my $branches = GetBranches();
804 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
805 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
807 # The item is on reserve and waiting, but has been
808 # reserved by some other patron.
809 $needsconfirmation{RESERVE_WAITING} =
810 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
812 elsif ( $restype eq "Reserved" ) {
813 # The item is on reserve for someone else.
814 $needsconfirmation{RESERVED} =
815 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
818 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
819 if ( $borrower->{'categorycode'} eq 'W' ) {
821 return ( \%emptyhash, \%needsconfirmation );
824 return ( \%issuingimpossible, \%needsconfirmation );
829 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
831 &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
835 =item C<$borrower> is a hash with borrower informations (from GetMemberDetails).
837 =item C<$barcode> is the barcode of the item being issued.
839 =item C<$datedue> is a C4::Dates object for the max date of return, i.e. the date due (optional).
842 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
844 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
845 Defaults to today. Unlike C<$datedue>, NOT a C4::Dates object, unfortunately.
847 AddIssue does the following things :
848 - step 01: check that there is a borrowernumber & a barcode provided
849 - check for RENEWAL (book issued & being issued to the same patron)
850 - renewal YES = Calculate Charge & renew
852 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
854 - fill reserve if reserve to this patron
855 - cancel reserve or not, otherwise
856 * TRANSFERT PENDING ?
857 - complete the transfert
865 my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate ) = @_;
866 my $dbh = C4::Context->dbh;
867 my $barcodecheck=CheckValidBarcode($barcode);
869 # $issuedate defaults to today.
870 if ( ! defined $issuedate ) {
871 $issuedate = strftime( "%Y-%m-%d", localtime );
873 if ($borrower and $barcode and $barcodecheck ne '0'){
874 # find which item we issue
875 my $item = GetItem('', $barcode) or return undef; # if we don't get an Item, abort.
877 # Get which branchcode we need
878 if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
879 $branch = C4::Context->userenv->{'branch'};
881 elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
882 $branch = $borrower->{'branchcode'};
886 $branch = $item->{'homebranch'};
889 # get actual issuing if there is one
890 my $actualissue = GetItemIssue( $item->{itemnumber});
892 # get biblioinformation for this item
893 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
896 # check if we just renew the issue.
898 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
899 $datedue = AddRenewal(
900 $borrower->{'borrowernumber'},
901 $item->{'itemnumber'},
904 $issuedate, # here interpreted as the renewal date
909 if ( $actualissue->{borrowernumber}) {
910 # This book is currently on loan, but not to the person
911 # who wants to borrow it now. mark it returned before issuing to the new borrower
914 C4::Context->userenv->{'branch'}
918 # See if the item is on reserve.
919 my ( $restype, $res ) =
920 C4::Reserves::CheckReserves( $item->{'itemnumber'} );
922 my $resbor = $res->{'borrowernumber'};
923 if ( $resbor eq $borrower->{'borrowernumber'} ) {
925 # The item is reserved by the current patron
926 ModReserveFill($res);
928 elsif ( $restype eq "Waiting" ) {
931 # The item is on reserve and waiting, but has been
932 # reserved by some other patron.
934 elsif ( $restype eq "Reserved" ) {
937 # The item is reserved by someone else.
938 if ($cancelreserve) { # cancel reserves on this item
939 CancelReserve( 0, $res->{'itemnumber'},
940 $res->{'borrowernumber'} );
943 if ($cancelreserve) {
944 CancelReserve( $res->{'biblionumber'}, 0,
945 $res->{'borrowernumber'} );
948 # set waiting reserve to first in reserve queue as book isn't waiting now
950 $res->{'biblionumber'},
951 $res->{'borrowernumber'},
957 # Starting process for transfer job (checking transfert and validate it if we have one)
958 my ($datesent) = GetTransfers($item->{'itemnumber'});
960 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
963 "UPDATE branchtransfers
964 SET datearrived = now(),
966 comments = 'Forced branchtransfer'
967 WHERE itemnumber= ? AND datearrived IS NULL"
969 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
973 # Record in the database the fact that the book was issued.
977 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
981 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
982 my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
983 $datedue = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch );
985 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
986 if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
987 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
991 $borrower->{'borrowernumber'}, # borrowernumber
992 $item->{'itemnumber'}, # itemnumber
993 $issuedate, # issuedate
994 $datedue->output('iso'), # date_due
995 C4::Context->userenv->{'branch'} # branchcode
999 ModItem({ issues => $item->{'issues'},
1000 holdingbranch => C4::Context->userenv->{'branch'},
1002 datelastborrowed => C4::Dates->new()->output('iso'),
1003 onloan => $datedue->output('iso'),
1004 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1005 ModDateLastSeen( $item->{'itemnumber'} );
1007 # If it costs to borrow this book, charge it to the patron's account.
1008 my ( $charge, $itemtype ) = GetIssuingCharges(
1009 $item->{'itemnumber'},
1010 $borrower->{'borrowernumber'}
1012 if ( $charge > 0 ) {
1014 $item->{'itemnumber'},
1015 $borrower->{'borrowernumber'}, $charge
1017 $item->{'charge'} = $charge;
1020 # Record the fact that this book was issued.
1022 C4::Context->userenv->{'branch'},
1024 '', $item->{'itemnumber'},
1025 $item->{'itype'}, $borrower->{'borrowernumber'}
1029 logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'})
1030 if C4::Context->preference("IssueLog");
1032 return ($datedue); # not necessarily the same as when it came in!
1035 =head2 GetLoanLength
1037 Get loan length for an itemtype, a borrower type and a branch
1039 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1044 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1045 my $dbh = C4::Context->dbh;
1048 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1050 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1051 # try to find issuelength & return the 1st available.
1052 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1053 $sth->execute( $borrowertype, $itemtype, $branchcode );
1054 my $loanlength = $sth->fetchrow_hashref;
1055 return $loanlength->{issuelength}
1056 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1058 $sth->execute( $borrowertype, "*", $branchcode );
1059 $loanlength = $sth->fetchrow_hashref;
1060 return $loanlength->{issuelength}
1061 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1063 $sth->execute( "*", $itemtype, $branchcode );
1064 $loanlength = $sth->fetchrow_hashref;
1065 return $loanlength->{issuelength}
1066 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1068 $sth->execute( "*", "*", $branchcode );
1069 $loanlength = $sth->fetchrow_hashref;
1070 return $loanlength->{issuelength}
1071 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1073 $sth->execute( $borrowertype, $itemtype, "*" );
1074 $loanlength = $sth->fetchrow_hashref;
1075 return $loanlength->{issuelength}
1076 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1078 $sth->execute( $borrowertype, "*", "*" );
1079 $loanlength = $sth->fetchrow_hashref;
1080 return $loanlength->{issuelength}
1081 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1083 $sth->execute( "*", $itemtype, "*" );
1084 $loanlength = $sth->fetchrow_hashref;
1085 return $loanlength->{issuelength}
1086 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1088 $sth->execute( "*", "*", "*" );
1089 $loanlength = $sth->fetchrow_hashref;
1090 return $loanlength->{issuelength}
1091 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1093 # if no rule is set => 21 days (hardcoded)
1097 =head2 GetIssuingRule
1099 FIXME - This is a copy-paste of GetLoanLength
1100 as a stop-gap. Do not wish to change API for GetLoanLength
1101 this close to release, however, Overdues::GetIssuingRules is broken.
1103 Get the issuing rule for an itemtype, a borrower type and a branch
1104 Returns a hashref from the issuingrules table.
1106 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1110 sub GetIssuingRule {
1111 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1112 my $dbh = C4::Context->dbh;
1113 my $sth = $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null" );
1116 $sth->execute( $borrowertype, $itemtype, $branchcode );
1117 $irule = $sth->fetchrow_hashref;
1118 return $irule if defined($irule) ;
1120 $sth->execute( $borrowertype, "*", $branchcode );
1121 $irule = $sth->fetchrow_hashref;
1122 return $irule if defined($irule) ;
1124 $sth->execute( "*", $itemtype, $branchcode );
1125 $irule = $sth->fetchrow_hashref;
1126 return $irule if defined($irule) ;
1128 $sth->execute( "*", "*", $branchcode );
1129 $irule = $sth->fetchrow_hashref;
1130 return $irule if defined($irule) ;
1132 $sth->execute( $borrowertype, $itemtype, "*" );
1133 $irule = $sth->fetchrow_hashref;
1134 return $irule if defined($irule) ;
1136 $sth->execute( $borrowertype, "*", "*" );
1137 $irule = $sth->fetchrow_hashref;
1138 return $irule if defined($irule) ;
1140 $sth->execute( "*", $itemtype, "*" );
1141 $irule = $sth->fetchrow_hashref;
1142 return $irule if defined($irule) ;
1144 $sth->execute( "*", "*", "*" );
1145 $irule = $sth->fetchrow_hashref;
1146 return $irule if defined($irule) ;
1148 # if no rule matches,
1152 =head2 GetBranchBorrowerCircRule
1156 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1160 Retrieves circulation rule attributes that apply to the given
1161 branch and patron category, regardless of item type.
1162 The return value is a hashref containing the following key:
1164 maxissueqty - maximum number of loans that a
1165 patron of the given category can have at the given
1166 branch. If the value is undef, no limit.
1168 This will first check for a specific branch and
1169 category match from branch_borrower_circ_rules.
1171 If no rule is found, it will then check default_branch_circ_rules
1172 (same branch, default category). If no rule is found,
1173 it will then check default_borrower_circ_rules (default
1174 branch, same category), then failing that, default_circ_rules
1175 (default branch, default category).
1177 If no rule has been found in the database, it will default to
1182 C<$branchcode> and C<$categorycode> should contain the
1183 literal branch code and patron category code, respectively - no
1188 sub GetBranchBorrowerCircRule {
1189 my $branchcode = shift;
1190 my $categorycode = shift;
1192 my $branch_cat_query = "SELECT maxissueqty
1193 FROM branch_borrower_circ_rules
1194 WHERE branchcode = ?
1195 AND categorycode = ?";
1196 my $dbh = C4::Context->dbh();
1197 my $sth = $dbh->prepare($branch_cat_query);
1198 $sth->execute($branchcode, $categorycode);
1200 if ($result = $sth->fetchrow_hashref()) {
1204 # try same branch, default borrower category
1205 my $branch_query = "SELECT maxissueqty
1206 FROM default_branch_circ_rules
1207 WHERE branchcode = ?";
1208 $sth = $dbh->prepare($branch_query);
1209 $sth->execute($branchcode);
1210 if ($result = $sth->fetchrow_hashref()) {
1214 # try default branch, same borrower category
1215 my $category_query = "SELECT maxissueqty
1216 FROM default_borrower_circ_rules
1217 WHERE categorycode = ?";
1218 $sth = $dbh->prepare($category_query);
1219 $sth->execute($categorycode);
1220 if ($result = $sth->fetchrow_hashref()) {
1224 # try default branch, default borrower category
1225 my $default_query = "SELECT maxissueqty
1226 FROM default_circ_rules";
1227 $sth = $dbh->prepare($default_query);
1229 if ($result = $sth->fetchrow_hashref()) {
1233 # built-in default circulation rule
1235 maxissueqty => undef,
1241 ($doreturn, $messages, $iteminformation, $borrower) =
1242 &AddReturn($barcode, $branch, $exemptfine, $dropbox);
1248 =item C<$barcode> is the bar code of the book being returned.
1250 =item C<$branch> is the code of the branch where the book is being returned.
1252 =item C<$exemptfine> indicates that overdue charges for the item will be
1255 =item C<$dropbox> indicates that the check-in date is assumed to be
1256 yesterday, or the last non-holiday as defined in C4::Calendar . If
1257 overdue charges are applied and C<$dropbox> is true, the last charge
1258 will be removed. This assumes that the fines accrual script has run
1263 C<&AddReturn> returns a list of four items:
1265 C<$doreturn> is true iff the return succeeded.
1267 C<$messages> is a reference-to-hash giving the reason for failure:
1273 No item with this barcode exists. The value is C<$barcode>.
1277 The book is not currently on loan. The value is C<$barcode>.
1279 =item C<IsPermanent>
1281 The book's home branch is a permanent collection. If you have borrowed
1282 this book, you are not allowed to return it. The value is the code for
1283 the book's home branch.
1287 This book has been withdrawn/cancelled. The value should be ignored.
1291 The item was reserved. The value is a reference-to-hash whose keys are
1292 fields from the reserves table of the Koha database, and
1293 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1294 either C<Waiting>, C<Reserved>, or 0.
1298 C<$borrower> is a reference-to-hash, giving information about the
1299 patron who last borrowed the book.
1304 my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1305 my $dbh = C4::Context->dbh;
1309 my $validTransfert = 0;
1310 my $reserveDone = 0;
1312 # get information on item
1313 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1314 my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1315 # use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);
1316 unless ($iteminformation->{'itemnumber'} ) {
1317 $messages->{'BadBarcode'} = $barcode;
1321 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1322 $messages->{'NotIssued'} = $barcode;
1323 # even though item is not on loan, it may still
1324 # be transferred; therefore, get current branch information
1325 my $curr_iteminfo = GetItem($iteminformation->{'itemnumber'});
1326 $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
1327 $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
1331 # check if the book is in a permanent collection....
1332 my $hbr = $iteminformation->{C4::Context->preference("HomeOrHoldingBranch")};
1333 my $branches = GetBranches();
1334 # FIXME -- This 'PE' attribute is largely undocumented. afaict, there's no user interface that reflects this functionality.
1335 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1336 $messages->{'IsPermanent'} = $hbr;
1339 # if independent branches are on and returning to different branch, refuse the return
1340 if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1341 $messages->{'Wrongbranch'} = 1;
1345 # check that the book has been cancelled
1346 if ( $iteminformation->{'wthdrawn'} ) {
1347 $messages->{'wthdrawn'} = 1;
1351 # new op dev : if the book returned in an other branch update the holding branch
1353 # update issues, thereby returning book (should push this out into another subroutine
1354 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1356 # case of a return of document (deal with issues and holdingbranch)
1359 my $circControlBranch;
1361 # don't allow dropbox mode to create an invalid entry in issues (issuedate > returndate) FIXME: actually checks eq, not gt
1362 undef($dropbox) if ( $iteminformation->{'issuedate'} eq C4::Dates->today('iso') );
1363 if (C4::Context->preference('CircControl') eq 'ItemHomeBranch' ) {
1364 $circControlBranch = $iteminformation->{homebranch};
1365 } elsif ( C4::Context->preference('CircControl') eq 'PatronLibrary') {
1366 $circControlBranch = $borrower->{branchcode};
1367 } else { # CircControl must be PickupLibrary.
1368 $circControlBranch = $iteminformation->{holdingbranch};
1369 # FIXME - is this right ? are we sure that the holdingbranch is still the pickup branch?
1372 MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'},$circControlBranch);
1373 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1376 # continue to deal with returns cases, but not only if we have an issue
1378 # the holdingbranch is updated if the document is returned in an other location .
1379 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1380 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1381 # reload iteminformation holdingbranch with the userenv value
1382 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1384 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1385 ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1387 if ($iteminformation->{borrowernumber}){
1388 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1390 # fix up the accounts.....
1391 if ( $iteminformation->{'itemlost'} ) {
1392 $messages->{'WasLost'} = 1;
1395 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1396 # check if we have a transfer for this document
1397 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1399 # if we have a transfer to do, we update the line of transfers with the datearrived
1401 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1404 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1406 $sth->execute( $iteminformation->{'itemnumber'} );
1408 # 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'
1409 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1412 $messages->{'WrongTransfer'} = $tobranch;
1413 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1415 $validTransfert = 1;
1418 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1419 # fix up the accounts.....
1420 if ($iteminformation->{'itemlost'}) {
1421 FixAccountForLostAndReturned($iteminformation, $borrower);
1422 $messages->{'WasLost'} = 1;
1424 # fix up the overdues in accounts...
1425 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1426 $iteminformation->{'itemnumber'}, $exemptfine, $dropbox );
1428 # find reserves.....
1429 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1430 my ( $resfound, $resrec ) =
1431 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1433 $resrec->{'ResFound'} = $resfound;
1434 $messages->{'ResFound'} = $resrec;
1439 # Record the fact that this book was returned.
1441 $branch, 'return', '0', '',
1442 $iteminformation->{'itemnumber'},
1443 $biblio->{'itemtype'},
1444 $borrower->{'borrowernumber'}
1447 logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'})
1448 if C4::Context->preference("ReturnLog");
1450 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1451 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1453 if ( ( $branch ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1454 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1455 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1456 $messages->{'WasTransfered'} = 1;
1457 } elsif ( C4::Context->preference("UseBranchTransferLimits") == 1
1458 && ! IsTransferAllowed( $branch, $iteminformation->{'homebranch'}, $iteminformation->{'itemtype'} )
1460 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1461 $messages->{'WasTransfered'} = 1;
1464 $messages->{'NeedsTransfer'} = 1;
1468 return ( $doreturn, $messages, $iteminformation, $borrower );
1471 =head2 MarkIssueReturned
1475 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate);
1479 Unconditionally marks an issue as being returned by
1480 moving the C<issues> row to C<old_issues> and
1481 setting C<returndate> to the current date, or
1482 the last non-holiday date of the branccode specified in
1483 C<dropbox_branch> . Assumes you've already checked that
1484 it's safe to do this, i.e. last non-holiday > issuedate.
1486 if C<$returndate> is specified (in iso format), it is used as the date
1487 of the return. It is ignored when a dropbox_branch is passed in.
1489 Ideally, this function would be internal to C<C4::Circulation>,
1490 not exported, but it is currently needed by one
1491 routine in C<C4::Accounts>.
1495 sub MarkIssueReturned {
1496 my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate ) = @_;
1497 my $dbh = C4::Context->dbh;
1498 my $query = "UPDATE issues SET returndate=";
1500 if ($dropbox_branch) {
1501 my $calendar = C4::Calendar->new( branchcode => $dropbox_branch );
1502 my $dropboxdate = $calendar->addDate( C4::Dates->new(), -1 );
1504 push @bind, $dropboxdate->output('iso');
1505 } elsif ($returndate) {
1507 push @bind, $returndate;
1509 $query .= " now() ";
1511 $query .= " WHERE borrowernumber = ? AND itemnumber = ?";
1512 push @bind, $borrowernumber, $itemnumber;
1514 my $sth_upd = $dbh->prepare($query);
1515 $sth_upd->execute(@bind);
1516 my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues
1517 WHERE borrowernumber = ?
1518 AND itemnumber = ?");
1519 $sth_copy->execute($borrowernumber, $itemnumber);
1520 my $sth_del = $dbh->prepare("DELETE FROM issues
1521 WHERE borrowernumber = ?
1522 AND itemnumber = ?");
1523 $sth_del->execute($borrowernumber, $itemnumber);
1526 =head2 FixOverduesOnReturn
1528 &FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
1530 C<$brn> borrowernumber
1534 C<$exemptfine> BOOL -- remove overdue charge associated with this issue.
1535 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
1537 internal function, called only by AddReturn
1541 sub FixOverduesOnReturn {
1542 my ( $borrowernumber, $item, $exemptfine, $dropbox ) = @_;
1543 my $dbh = C4::Context->dbh;
1545 # check for overdue fine
1548 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1550 $sth->execute( $borrowernumber, $item );
1552 # alter fine to show that the book has been returned
1554 if ($data = $sth->fetchrow_hashref) {
1556 my @bind = ($borrowernumber,$item ,$data->{'accountno'});
1558 $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
1559 if (C4::Context->preference("FinesLog")) {
1560 &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
1562 } elsif ($dropbox && $data->{lastincrement}) {
1563 my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
1564 my $amt = $data->{amount} - $data->{lastincrement} ;
1565 if (C4::Context->preference("FinesLog")) {
1566 &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
1568 $uquery = "update accountlines set accounttype='F' ";
1569 if($outstanding >= 0 && $amt >=0) {
1570 $uquery .= ", amount = ? , amountoutstanding=? ";
1571 unshift @bind, ($amt, $outstanding) ;
1574 $uquery = "update accountlines set accounttype='F' ";
1576 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1577 my $usth = $dbh->prepare($uquery);
1578 $usth->execute(@bind);
1586 =head2 FixAccountForLostAndReturned
1588 &FixAccountForLostAndReturned($iteminfo,$borrower);
1590 Calculates the charge for a book lost and returned (Not exported & used only once)
1592 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1594 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1596 Internal function, called by AddReturn
1600 sub FixAccountForLostAndReturned {
1601 my ($iteminfo, $borrower) = @_;
1602 my $dbh = C4::Context->dbh;
1603 my $itm = $iteminfo->{'itemnumber'};
1604 # check for charge made for lost book
1605 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1606 $sth->execute($itm);
1607 if (my $data = $sth->fetchrow_hashref) {
1608 # writeoff this amount
1610 my $amount = $data->{'amount'};
1611 my $acctno = $data->{'accountno'};
1613 if ($data->{'amountoutstanding'} == $amount) {
1614 $offset = $data->{'amount'};
1617 $offset = $amount - $data->{'amountoutstanding'};
1618 $amountleft = $data->{'amountoutstanding'} - $amount;
1620 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1621 WHERE (borrowernumber = ?)
1622 AND (itemnumber = ?) AND (accountno = ?) ");
1623 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1625 #check if any credit is left if so writeoff other accounts
1626 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
1627 if ($amountleft < 0){
1630 if ($amountleft > 0){
1631 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1632 AND (amountoutstanding >0) ORDER BY date");
1633 $msth->execute($data->{'borrowernumber'});
1634 # offset transactions
1637 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1638 if ($accdata->{'amountoutstanding'} < $amountleft) {
1640 $amountleft -= $accdata->{'amountoutstanding'};
1642 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1645 my $thisacct = $accdata->{'accountno'};
1646 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1647 WHERE (borrowernumber = ?)
1648 AND (accountno=?)");
1649 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1651 $usth = $dbh->prepare("INSERT INTO accountoffsets
1652 (borrowernumber, accountno, offsetaccount, offsetamount)
1655 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1660 if ($amountleft > 0){
1663 my $desc="Item Returned ".$iteminfo->{'barcode'};
1664 $usth = $dbh->prepare("INSERT INTO accountlines
1665 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1666 VALUES (?,?,now(),?,?,'CR',?)");
1667 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1669 $usth = $dbh->prepare("INSERT INTO accountoffsets
1670 (borrowernumber, accountno, offsetaccount, offsetamount)
1672 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1674 ModItem({ paidfor => '' }, undef, $itm);
1682 $issues = &GetItemIssue($itemnumber);
1684 Returns patrons currently having a book. nothing if item is not issued atm
1686 C<$itemnumber> is the itemnumber
1688 Returns an array of hashes
1690 FIXME: Though the above says that this function returns nothing if the
1691 item is not issued, this actually returns a hasref that looks like
1702 my ( $itemnumber) = @_;
1703 return unless $itemnumber;
1704 my $dbh = C4::Context->dbh;
1708 my $today = POSIX::strftime("%Y%m%d", localtime);
1710 my $sth = $dbh->prepare(
1711 "SELECT * FROM issues
1712 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1714 issues.itemnumber=?");
1715 $sth->execute($itemnumber);
1716 my $data = $sth->fetchrow_hashref;
1717 my $datedue = $data->{'date_due'};
1719 if ( $datedue < $today ) {
1720 $data->{'overdue'} = 1;
1722 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1729 $issue = GetOpenIssue( $itemnumber );
1731 Returns the row from the issues table if the item is currently issued, undef if the item is not currently issued
1733 C<$itemnumber> is the item's itemnumber
1740 my ( $itemnumber ) = @_;
1742 my $dbh = C4::Context->dbh;
1743 my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
1744 $sth->execute( $itemnumber );
1745 my $issue = $sth->fetchrow_hashref();
1749 =head2 GetItemIssues
1751 $issues = &GetItemIssues($itemnumber, $history);
1753 Returns patrons that have issued a book
1755 C<$itemnumber> is the itemnumber
1756 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1758 Returns an array of hashes
1763 my ( $itemnumber,$history ) = @_;
1764 my $dbh = C4::Context->dbh;
1768 my $today = POSIX::strftime("%Y%m%d", localtime);
1770 my $sql = "SELECT * FROM issues
1771 JOIN borrowers USING (borrowernumber)
1772 JOIN items USING (itemnumber)
1773 WHERE issues.itemnumber = ? ";
1776 SELECT * FROM old_issues
1777 LEFT JOIN borrowers USING (borrowernumber)
1778 JOIN items USING (itemnumber)
1779 WHERE old_issues.itemnumber = ? ";
1781 $sql .= "ORDER BY date_due DESC";
1782 my $sth = $dbh->prepare($sql);
1784 $sth->execute($itemnumber, $itemnumber);
1786 $sth->execute($itemnumber);
1788 while ( my $data = $sth->fetchrow_hashref ) {
1789 my $datedue = $data->{'date_due'};
1791 if ( $datedue < $today ) {
1792 $data->{'overdue'} = 1;
1794 my $itemnumber = $data->{'itemnumber'};
1795 push @GetItemIssues, $data;
1798 return ( \@GetItemIssues );
1801 =head2 GetBiblioIssues
1803 $issues = GetBiblioIssues($biblionumber);
1805 this function get all issues from a biblionumber.
1808 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1809 tables issues and the firstname,surname & cardnumber from borrowers.
1813 sub GetBiblioIssues {
1814 my $biblionumber = shift;
1815 return undef unless $biblionumber;
1816 my $dbh = C4::Context->dbh;
1818 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1820 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1821 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1822 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1823 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1824 WHERE biblio.biblionumber = ?
1826 SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1828 LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1829 LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1830 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1831 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1832 WHERE biblio.biblionumber = ?
1835 my $sth = $dbh->prepare($query);
1836 $sth->execute($biblionumber, $biblionumber);
1839 while ( my $data = $sth->fetchrow_hashref ) {
1840 push @issues, $data;
1845 =head2 GetUpcomingDueIssues
1849 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
1855 sub GetUpcomingDueIssues {
1858 $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
1859 my $dbh = C4::Context->dbh;
1861 my $statement = <<END_SQL;
1862 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due
1864 LEFT JOIN items USING (itemnumber)
1865 WhERE returndate is NULL
1866 AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
1869 my @bind_parameters = ( $params->{'days_in_advance'} );
1871 my $sth = $dbh->prepare( $statement );
1872 $sth->execute( @bind_parameters );
1873 my $upcoming_dues = $sth->fetchall_arrayref({});
1876 return $upcoming_dues;
1879 =head2 CanBookBeRenewed
1881 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
1883 Find out whether a borrowed item may be renewed.
1885 C<$dbh> is a DBI handle to the Koha database.
1887 C<$borrowernumber> is the borrower number of the patron who currently
1888 has the item on loan.
1890 C<$itemnumber> is the number of the item to renew.
1892 C<$override_limit>, if supplied with a true value, causes
1893 the limit on the number of times that the loan can be renewed
1894 (as controlled by the item type) to be ignored.
1896 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1897 item must currently be on loan to the specified borrower; renewals
1898 must be allowed for the item's type; and the borrower must not have
1899 already renewed the loan. $error will contain the reason the renewal can not proceed
1903 sub CanBookBeRenewed {
1905 # check renewal status
1906 my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
1907 my $dbh = C4::Context->dbh;
1912 # Look in the issues table for this item, lent to this borrower,
1913 # and not yet returned.
1915 # FIXME - I think this function could be redone to use only one SQL call.
1916 my $sth1 = $dbh->prepare(
1917 "SELECT * FROM issues
1918 WHERE borrowernumber = ?
1921 $sth1->execute( $borrowernumber, $itemnumber );
1922 if ( my $data1 = $sth1->fetchrow_hashref ) {
1924 # Found a matching item
1926 # See if this item may be renewed. This query is convoluted
1927 # because it's a bit messy: given the item number, we need to find
1928 # the biblioitem, which gives us the itemtype, which tells us
1929 # whether it may be renewed.
1930 my $query = "SELECT renewalsallowed FROM items ";
1931 $query .= (C4::Context->preference('item-level_itypes'))
1932 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1933 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1934 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1935 $query .= "WHERE items.itemnumber = ?";
1936 my $sth2 = $dbh->prepare($query);
1937 $sth2->execute($itemnumber);
1938 if ( my $data2 = $sth2->fetchrow_hashref ) {
1939 $renews = $data2->{'renewalsallowed'};
1941 if ( ( $renews && $renews > $data1->{'renewals'} ) || $override_limit ) {
1948 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1956 return ($renewokay,$error);
1961 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
1965 C<$borrowernumber> is the borrower number of the patron who currently
1968 C<$itemnumber> is the number of the item to renew.
1970 C<$branch> is the library branch. Defaults to the homebranch of the ITEM.
1972 C<$datedue> can be a C4::Dates object used to set the due date.
1974 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate. If
1975 this parameter is not supplied, lastreneweddate is set to the current date.
1977 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
1978 from the book's item type.
1983 my $borrowernumber = shift or return undef;
1984 my $itemnumber = shift or return undef;
1985 my $item = GetItem($itemnumber) or return undef;
1986 my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
1987 my $branch = (@_) ? shift : $item->{homebranch}; # opac-renew doesn't send branch
1988 my $datedue = shift;
1989 my $lastreneweddate = shift;
1991 # If the due date wasn't specified, calculate it by adding the
1992 # book's loan length to today's date.
1993 unless ($datedue && $datedue->output('iso')) {
1995 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1996 my $loanlength = GetLoanLength(
1997 $borrower->{'categorycode'},
1998 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1999 $item->{homebranch} # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
2001 #FIXME -- use circControl?
2002 $datedue = CalcDateDue(C4::Dates->new(),$loanlength,$branch); # this branch is the transactional branch.
2003 # The question of whether to use item's homebranch calendar is open.
2006 # $lastreneweddate defaults to today.
2007 unless (defined $lastreneweddate) {
2008 $lastreneweddate = strftime( "%Y-%m-%d", localtime );
2011 my $dbh = C4::Context->dbh;
2012 # Find the issues record for this book
2014 $dbh->prepare("SELECT * FROM issues
2015 WHERE borrowernumber=?
2018 $sth->execute( $borrowernumber, $itemnumber );
2019 my $issuedata = $sth->fetchrow_hashref;
2022 # Update the issues record to have the new due date, and a new count
2023 # of how many times it has been renewed.
2024 my $renews = $issuedata->{'renewals'} + 1;
2025 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2026 WHERE borrowernumber=?
2029 $sth->execute( $datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2032 # Update the renewal count on the item, and tell zebra to reindex
2033 $renews = $biblio->{'renewals'} + 1;
2034 ModItem({ renewals => $renews }, $biblio->{'biblionumber'}, $itemnumber);
2036 # Charge a new rental fee, if applicable?
2037 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2038 if ( $charge > 0 ) {
2039 my $accountno = getnextacctno( $borrowernumber );
2040 my $item = GetBiblioFromItemNumber($itemnumber);
2041 $sth = $dbh->prepare(
2042 "INSERT INTO accountlines
2044 borrowernumber, accountno, amount,
2046 accounttype, amountoutstanding, itemnumber
2048 VALUES (now(),?,?,?,?,?,?,?)"
2050 $sth->execute( $borrowernumber, $accountno, $charge,
2051 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2052 'Rent', $charge, $itemnumber );
2056 UpdateStats( $branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2061 # check renewal status
2062 my ($bornum,$itemno)=@_;
2063 my $dbh = C4::Context->dbh;
2065 my $renewsallowed = 0;
2067 # Look in the issues table for this item, lent to this borrower,
2068 # and not yet returned.
2070 # FIXME - I think this function could be redone to use only one SQL call.
2071 my $sth = $dbh->prepare("select * from issues
2072 where (borrowernumber = ?)
2073 and (itemnumber = ?)");
2074 $sth->execute($bornum,$itemno);
2075 my $data = $sth->fetchrow_hashref;
2076 $renewcount = $data->{'renewals'} if $data->{'renewals'};
2078 my $query = "SELECT renewalsallowed FROM items ";
2079 $query .= (C4::Context->preference('item-level_itypes'))
2080 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2081 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
2082 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2083 $query .= "WHERE items.itemnumber = ?";
2084 my $sth2 = $dbh->prepare($query);
2085 $sth2->execute($itemno);
2086 my $data2 = $sth2->fetchrow_hashref();
2087 $renewsallowed = $data2->{'renewalsallowed'};
2088 $renewsleft = $renewsallowed - $renewcount;
2089 return ($renewcount,$renewsallowed,$renewsleft);
2092 =head2 GetIssuingCharges
2094 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
2096 Calculate how much it would cost for a given patron to borrow a given
2097 item, including any applicable discounts.
2099 C<$itemnumber> is the item number of item the patron wishes to borrow.
2101 C<$borrowernumber> is the patron's borrower number.
2103 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
2104 and C<$item_type> is the code for the item's item type (e.g., C<VID>
2109 sub GetIssuingCharges {
2111 # calculate charges due
2112 my ( $itemnumber, $borrowernumber ) = @_;
2114 my $dbh = C4::Context->dbh;
2117 # Get the book's item type and rental charge (via its biblioitem).
2118 my $qcharge = "SELECT itemtypes.itemtype,rentalcharge FROM items
2119 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
2120 $qcharge .= (C4::Context->preference('item-level_itypes'))
2121 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2122 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2124 $qcharge .= "WHERE items.itemnumber =?";
2126 my $sth1 = $dbh->prepare($qcharge);
2127 $sth1->execute($itemnumber);
2128 if ( my $data1 = $sth1->fetchrow_hashref ) {
2129 $item_type = $data1->{'itemtype'};
2130 $charge = $data1->{'rentalcharge'};
2131 my $q2 = "SELECT rentaldiscount FROM borrowers
2132 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
2133 WHERE borrowers.borrowernumber = ?
2134 AND issuingrules.itemtype = ?";
2135 my $sth2 = $dbh->prepare($q2);
2136 $sth2->execute( $borrowernumber, $item_type );
2137 if ( my $data2 = $sth2->fetchrow_hashref ) {
2138 my $discount = $data2->{'rentaldiscount'};
2139 if ( $discount eq 'NULL' ) {
2142 $charge = ( $charge * ( 100 - $discount ) ) / 100;
2148 return ( $charge, $item_type );
2151 =head2 AddIssuingCharge
2153 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2157 sub AddIssuingCharge {
2158 my ( $itemnumber, $borrowernumber, $charge ) = @_;
2159 my $dbh = C4::Context->dbh;
2160 my $nextaccntno = getnextacctno( $borrowernumber );
2162 INSERT INTO accountlines
2163 (borrowernumber, itemnumber, accountno,
2164 date, amount, description, accounttype,
2166 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
2168 my $sth = $dbh->prepare($query);
2169 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
2175 GetTransfers($itemnumber);
2180 my ($itemnumber) = @_;
2182 my $dbh = C4::Context->dbh;
2188 FROM branchtransfers
2189 WHERE itemnumber = ?
2190 AND datearrived IS NULL
2192 my $sth = $dbh->prepare($query);
2193 $sth->execute($itemnumber);
2194 my @row = $sth->fetchrow_array();
2200 =head2 GetTransfersFromTo
2202 @results = GetTransfersFromTo($frombranch,$tobranch);
2204 Returns the list of pending transfers between $from and $to branch
2208 sub GetTransfersFromTo {
2209 my ( $frombranch, $tobranch ) = @_;
2210 return unless ( $frombranch && $tobranch );
2211 my $dbh = C4::Context->dbh;
2213 SELECT itemnumber,datesent,frombranch
2214 FROM branchtransfers
2217 AND datearrived IS NULL
2219 my $sth = $dbh->prepare($query);
2220 $sth->execute( $frombranch, $tobranch );
2223 while ( my $data = $sth->fetchrow_hashref ) {
2224 push @gettransfers, $data;
2227 return (@gettransfers);
2230 =head2 DeleteTransfer
2232 &DeleteTransfer($itemnumber);
2236 sub DeleteTransfer {
2237 my ($itemnumber) = @_;
2238 my $dbh = C4::Context->dbh;
2239 my $sth = $dbh->prepare(
2240 "DELETE FROM branchtransfers
2242 AND datearrived IS NULL "
2244 $sth->execute($itemnumber);
2248 =head2 AnonymiseIssueHistory
2250 $rows = AnonymiseIssueHistory($borrowernumber,$date)
2252 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
2253 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
2255 return the number of affected rows.
2259 sub AnonymiseIssueHistory {
2261 my $borrowernumber = shift;
2262 my $dbh = C4::Context->dbh;
2265 SET borrowernumber = NULL
2266 WHERE returndate < '".$date."'
2267 AND borrowernumber IS NOT NULL
2269 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
2270 my $rows_affected = $dbh->do($query);
2271 return $rows_affected;
2274 =head2 updateWrongTransfer
2276 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
2278 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
2282 sub updateWrongTransfer {
2283 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2284 my $dbh = C4::Context->dbh;
2285 # first step validate the actual line of transfert .
2288 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2290 $sth->execute($FromLibrary,$itemNumber);
2293 # second step create a new line of branchtransfer to the right location .
2294 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2296 #third step changing holdingbranch of item
2297 UpdateHoldingbranch($FromLibrary,$itemNumber);
2300 =head2 UpdateHoldingbranch
2302 $items = UpdateHoldingbranch($branch,$itmenumber);
2303 Simple methode for updating hodlingbranch in items BDD line
2307 sub UpdateHoldingbranch {
2308 my ( $branch,$itemnumber ) = @_;
2309 ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2314 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2315 this function calculates the due date given the loan length ,
2316 checking against the holidays calendar as per the 'useDaysMode' syspref.
2317 C<$startdate> = C4::Dates object representing start date of loan period (assumed to be today)
2318 C<$branch> = location whose calendar to use
2319 C<$loanlength> = loan length prior to adjustment
2323 my ($startdate,$loanlength,$branch) = @_;
2324 if(C4::Context->preference('useDaysMode') eq 'Days') { # ignoring calendar
2325 my $datedue = time + ($loanlength) * 86400;
2326 #FIXME - assumes now even though we take a startdate
2327 my @datearr = localtime($datedue);
2328 return C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2330 my $calendar = C4::Calendar->new( branchcode => $branch );
2331 my $datedue = $calendar->addDate($startdate, $loanlength);
2336 =head2 CheckValidDatedue
2337 This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2338 To be replaced by CalcDateDue() once C4::Calendar use is tested.
2340 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2341 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2342 C<$date_due> = returndate calculate with no day check
2343 C<$itemnumber> = itemnumber
2344 C<$branchcode> = location of issue (affected by 'CircControl' syspref)
2345 C<$loanlength> = loan length prior to adjustment
2348 sub CheckValidDatedue {
2349 my ($date_due,$itemnumber,$branchcode)=@_;
2350 my @datedue=split('-',$date_due->output('iso'));
2351 my $years=$datedue[0];
2352 my $month=$datedue[1];
2353 my $day=$datedue[2];
2354 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2356 for (my $i=0;$i<2;$i++){
2357 $dow=Day_of_Week($years,$month,$day);
2358 ($dow=0) if ($dow>6);
2359 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2360 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2361 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2362 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2364 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2367 my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2372 =head2 CheckRepeatableHolidays
2374 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2375 this function checks if the date due is a repeatable holiday
2376 C<$date_due> = returndate calculate with no day check
2377 C<$itemnumber> = itemnumber
2378 C<$branchcode> = localisation of issue
2382 sub CheckRepeatableHolidays{
2383 my($itemnumber,$week_day,$branchcode)=@_;
2384 my $dbh = C4::Context->dbh;
2385 my $query = qq|SELECT count(*)
2386 FROM repeatable_holidays
2389 my $sth = $dbh->prepare($query);
2390 $sth->execute($branchcode,$week_day);
2391 my $result=$sth->fetchrow;
2397 =head2 CheckSpecialHolidays
2399 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2400 this function check if the date is a special holiday
2401 C<$years> = the years of datedue
2402 C<$month> = the month of datedue
2403 C<$day> = the day of datedue
2404 C<$itemnumber> = itemnumber
2405 C<$branchcode> = localisation of issue
2409 sub CheckSpecialHolidays{
2410 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2411 my $dbh = C4::Context->dbh;
2412 my $query=qq|SELECT count(*)
2413 FROM `special_holidays`
2419 my $sth = $dbh->prepare($query);
2420 $sth->execute($years,$month,$day,$branchcode);
2421 my $countspecial=$sth->fetchrow ;
2423 return $countspecial;
2426 =head2 CheckRepeatableSpecialHolidays
2428 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2429 this function check if the date is a repeatble special holidays
2430 C<$month> = the month of datedue
2431 C<$day> = the day of datedue
2432 C<$itemnumber> = itemnumber
2433 C<$branchcode> = localisation of issue
2437 sub CheckRepeatableSpecialHolidays{
2438 my ($month,$day,$itemnumber,$branchcode) = @_;
2439 my $dbh = C4::Context->dbh;
2440 my $query=qq|SELECT count(*)
2441 FROM `repeatable_holidays`
2446 my $sth = $dbh->prepare($query);
2447 $sth->execute($month,$day,$branchcode);
2448 my $countspecial=$sth->fetchrow ;
2450 return $countspecial;
2455 sub CheckValidBarcode{
2457 my $dbh = C4::Context->dbh;
2458 my $query=qq|SELECT count(*)
2462 my $sth = $dbh->prepare($query);
2463 $sth->execute($barcode);
2464 my $exist=$sth->fetchrow ;
2469 =head2 IsBranchTransferAllowed
2471 $allowed = IsBranchTransferAllowed( $toBranch, $fromBranch, $itemtype );
2475 sub IsBranchTransferAllowed {
2476 my ( $toBranch, $fromBranch, $itemtype ) = @_;
2478 if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed.
2480 my $dbh = C4::Context->dbh;
2482 my $sth = $dbh->prepare('SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND itemtype = ?');
2483 $sth->execute( $toBranch, $fromBranch, $itemtype );
2484 my $limit = $sth->fetchrow_hashref();
2486 ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed*
2487 if ( $limit->{'limitId'} ) {
2494 =head2 CreateBranchTransferLimit
2496 CreateBranchTransferLimit( $toBranch, $fromBranch, $itemtype );
2500 sub CreateBranchTransferLimit {
2501 my ( $toBranch, $fromBranch, $itemtype ) = @_;
2503 my $dbh = C4::Context->dbh;
2505 my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( itemtype, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
2506 $sth->execute( $itemtype, $toBranch, $fromBranch );
2509 =head2 DeleteBranchTransferLimits
2511 DeleteBranchTransferLimits();
2515 sub DeleteBranchTransferLimits {
2516 my $dbh = C4::Context->dbh;
2517 my $sth = $dbh->prepare("TRUNCATE TABLE branch_transfer_limits");
2528 Koha Developement team <info@koha.org>