Bug 10795: Improvements for GetOpenIssue in C4::Circulation
[koha.git] / C4 / Circulation.pm
index 93bf8e1..d74b97f 100644 (file)
@@ -88,6 +88,7 @@ BEGIN {
                &GetOpenIssue
                &AnonymiseIssueHistory
         &CheckIfIssuedToPatron
+        &IsItemIssued
        );
 
        # subs to deal with returns
@@ -564,7 +565,7 @@ sub itemissues {
             $data->{'borrower'} = $data2->{'borrowernumber'};
         }
         else {
-            $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
+            $data->{'date_due'} = ($data->{'withdrawn'} eq '1') ? 'Cancelled' : 'Available';
         }
 
 
@@ -826,9 +827,15 @@ sub CanBookBeIssued {
         $needsconfirmation{PATRON_CANT} = 1;
     } else {
         if($max_loans_allowed){
-            $needsconfirmation{TOO_MANY} = 1;
-            $needsconfirmation{current_loan_count} = $current_loan_count;
-            $needsconfirmation{max_loans_allowed} = $max_loans_allowed;
+            if ( C4::Context->preference("AllowTooManyOverride") ) {
+                $needsconfirmation{TOO_MANY} = 1;
+                $needsconfirmation{current_loan_count} = $current_loan_count;
+                $needsconfirmation{max_loans_allowed} = $max_loans_allowed;
+            } else {
+                $issuingimpossible{TOO_MANY} = 1;
+                $issuingimpossible{current_loan_count} = $current_loan_count;
+                $issuingimpossible{max_loans_allowed} = $max_loans_allowed;
+            }
         }
     }
 
@@ -852,7 +859,6 @@ sub CanBookBeIssued {
             my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
             $sth->execute($item->{'itemtype'});
             my $notforloan=$sth->fetchrow_hashref();
-            $sth->finish();
             if ($notforloan->{'notforloan'}) {
                 if (!C4::Context->preference("AllowNotForLoanOverride")) {
                     $issuingimpossible{NOT_FOR_LOAN} = 1;
@@ -873,7 +879,7 @@ sub CanBookBeIssued {
             }
         }
     }
-    if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} > 0 )
+    if ( $item->{'withdrawn'} && $item->{'withdrawn'} > 0 )
     {
         $issuingimpossible{WTHDRAWN} = 1;
     }
@@ -890,8 +896,10 @@ sub CanBookBeIssued {
     if ( C4::Context->preference("IndependentBranches") ) {
         my $userenv = C4::Context->userenv;
         if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
-            $issuingimpossible{ITEMNOTSAMEBRANCH} = 1
-              if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
+            if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} ){
+                $issuingimpossible{ITEMNOTSAMEBRANCH} = 1;
+                $issuingimpossible{'itemhomebranch'} = $item->{C4::Context->preference("HomeOrHoldingBranch")};
+            }
             $needsconfirmation{BORRNOTSAMEBRANCH} = GetBranchName( $borrower->{'branchcode'} )
               if ( $borrower->{'branchcode'} ne $userenv->{branch} );
         }
@@ -1671,7 +1679,7 @@ The book's home branch is a permanent collection. If you have borrowed
 this book, you are not allowed to return it. The value is the code for
 the book's home branch.
 
-=item C<wthdrawn>
+=item C<withdrawn>
 
 This book has been withdrawn/cancelled. The value should be ignored.
 
@@ -1764,8 +1772,8 @@ sub AddReturn {
         return ( $doreturn, $messages, $issue, $borrower );
     }
 
-    if ( $item->{'wthdrawn'} ) { # book has been cancelled
-        $messages->{'wthdrawn'} = 1;
+    if ( $item->{'withdrawn'} ) { # book has been cancelled
+        $messages->{'withdrawn'} = 1;
         $doreturn = 0 if C4::Context->preference("BlockReturnOfWithdrawnItems");
     }
 
@@ -1785,21 +1793,36 @@ sub AddReturn {
         }
 
         if ($borrowernumber) {
-        if( C4::Context->preference('CalculateFinesOnReturn') && $issue->{'overdue'}){
+            if( C4::Context->preference('CalculateFinesOnReturn') && $issue->{'overdue'}){
             # we only need to calculate and change the fines if we want to do that on return
             # Should be on for hourly loans
-                my ( $amount, $type, $unitcounttotal ) = C4::Overdues::CalcFine( $item, $borrower->{categorycode},$branch, $datedue, $today );
+                my $control = C4::Context->preference('CircControl');
+                my $control_branchcode =
+                    ( $control eq 'ItemHomeLibrary' ) ? $item->{homebranch}
+                  : ( $control eq 'PatronLibrary' )   ? $borrower->{branchcode}
+                  :                                     $issue->{branchcode};
+
+                my ( $amount, $type, $unitcounttotal ) =
+                  C4::Overdues::CalcFine( $item, $borrower->{categorycode},
+                    $control_branchcode, $datedue, $today );
+
                 $type ||= q{};
-        if ( $amount > 0 && ( C4::Context->preference('finesMode') eq 'production' )) {
-          C4::Overdues::UpdateFine(
-              $issue->{itemnumber},
-              $issue->{borrowernumber},
-                      $amount, $type, output_pref($datedue)
-              );
-        }
+
+                if ( $amount > 0
+                    && C4::Context->preference('finesMode') eq 'production' )
+                {
+                    C4::Overdues::UpdateFine( $issue->{itemnumber},
+                        $issue->{borrowernumber},
+                        $amount, $type, output_pref($datedue) );
+                }
             }
-            MarkIssueReturned($borrowernumber, $item->{'itemnumber'}, $circControlBranch, '', $borrower->{'privacy'});
-            $messages->{'WasReturned'} = 1;    # FIXME is the "= 1" right?  This could be the borrower hash.
+
+            MarkIssueReturned( $borrowernumber, $item->{'itemnumber'},
+                $circControlBranch, '', $borrower->{'privacy'} );
+
+            # FIXME is the "= 1" right?  This could be the borrower hash.
+            $messages->{'WasReturned'} = 1;
+
         }
 
         ModItem({ onloan => undef }, $issue->{'biblionumber'}, $item->{'itemnumber'});
@@ -1861,7 +1884,8 @@ sub AddReturn {
     # find reserves.....
     # if we don't have a reserve with the status W, we launch the Checkreserves routine
     my ($resfound, $resrec);
-    ($resfound, $resrec, undef) = C4::Reserves::CheckReserves( $item->{'itemnumber'} ) unless ( $item->{'wthdrawn'} );
+    my $lookahead= C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
+    ($resfound, $resrec, undef) = C4::Reserves::CheckReserves( $item->{'itemnumber'}, undef, $lookahead ) unless ( $item->{'withdrawn'} );
     if ($resfound) {
           $resrec->{'ResFound'} = $resfound;
         $messages->{'ResFound'} = $resrec;
@@ -2181,7 +2205,6 @@ sub _FixAccountForLostAndReturned {
                 (?,?,?,?)");
             $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
         }
-        $msth->finish;  # $msth might actually have data left
     }
     $amountleft *= -1 if ($amountleft > 0);
     my $desc = "Item Returned " . $item_id;
@@ -2288,12 +2311,12 @@ Returns a hashref
 
 sub GetOpenIssue {
   my ( $itemnumber ) = @_;
-
+  return unless $itemnumber;
   my $dbh = C4::Context->dbh;  
   my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
   $sth->execute( $itemnumber );
-  my $issue = $sth->fetchrow_hashref();
-  return $issue;
+  return $sth->fetchrow_hashref();
+
 }
 
 =head2 GetItemIssues
@@ -2404,8 +2427,8 @@ SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-
 FROM issues 
 LEFT JOIN items USING (itemnumber)
 LEFT OUTER JOIN branches USING (branchcode)
-WhERE returndate is NULL
-AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
+WHERE returndate is NULL
+HAVING days_until_due > 0 AND days_until_due < ?
 END_SQL
 
     my @bind_parameters = ( $params->{'days_in_advance'} );
@@ -2413,7 +2436,6 @@ END_SQL
     my $sth = $dbh->prepare( $statement );
     $sth->execute( @bind_parameters );
     my $upcoming_dues = $sth->fetchall_arrayref({});
-    $sth->finish;
 
     return $upcoming_dues;
 }
@@ -2463,8 +2485,9 @@ sub CanBookBeRenewed {
         $error = "too_many";
     }
 
-    my $resstatus = C4::Reserves::GetReserveStatus($itemnumber);
-    if ( $resstatus eq "Waiting" or $resstatus eq "Reserved" ) {
+    my ( $resfound, $resrec, undef ) = C4::Reserves::CheckReserves( $itemnumber );
+
+    if ( $resfound ) { # '' when no hold was found
         $renewokay = 0;
         $error = "on_reserve";
     }
@@ -2514,7 +2537,6 @@ sub AddRenewal {
       );
     $sth->execute( $borrowernumber, $itemnumber );
     my $issuedata = $sth->fetchrow_hashref;
-    $sth->finish;
     if(defined $datedue && ref $datedue ne 'DateTime' ) {
         carp 'Invalid date passed to AddRenewal.';
         return;
@@ -2542,7 +2564,6 @@ sub AddRenewal {
     );
 
     $sth->execute( $datedue->strftime('%Y-%m-%d %H:%M'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
-    $sth->finish;
 
     # Update the renewal count on the item, and tell zebra to reindex
     $renews = $biblio->{'renewals'} + 1;
@@ -2614,7 +2635,6 @@ sub GetRenewCount {
     $sth->execute( $bornum, $itemno );
     my $data = $sth->fetchrow_hashref;
     $renewcount = $data->{'renewals'} if $data->{'renewals'};
-    $sth->finish;
     # $item and $borrower should be calculated
     my $branchcode = _GetCircControlBranch($item, $borrower);
     
@@ -2683,7 +2703,6 @@ sub GetIssuingCharges {
         }
     }
 
-    $sth->finish; # we havent _explicitly_ fetched all rows
     return ( $charge, $item_type );
 }
 
@@ -2745,7 +2764,6 @@ sub AddIssuingCharge {
     ";
     my $sth = $dbh->prepare($query);
     $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge, $manager_id );
-    $sth->finish;
 }
 
 =head2 GetTransfers
@@ -2770,7 +2788,6 @@ sub GetTransfers {
     my $sth = $dbh->prepare($query);
     $sth->execute($itemnumber);
     my @row = $sth->fetchrow_array();
-    $sth->finish;
     return @row;
 }
 
@@ -2800,7 +2817,6 @@ sub GetTransfersFromTo {
     while ( my $data = $sth->fetchrow_hashref ) {
         push @gettransfers, $data;
     }
-    $sth->finish;
     return (@gettransfers);
 }
 
@@ -2812,14 +2828,14 @@ sub GetTransfersFromTo {
 
 sub DeleteTransfer {
     my ($itemnumber) = @_;
+    return unless $itemnumber;
     my $dbh          = C4::Context->dbh;
     my $sth          = $dbh->prepare(
         "DELETE FROM branchtransfers
          WHERE itemnumber=?
          AND datearrived IS NULL "
     );
-    $sth->execute($itemnumber);
-    $sth->finish;
+    return $sth->execute($itemnumber);
 }
 
 =head2 AnonymiseIssueHistory
@@ -2964,7 +2980,6 @@ sub updateWrongTransfer {
                        "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
                );
                $sth->execute($FromLibrary,$itemNumber);
-               $sth->finish;
 
 # second step create a new line of branchtransfer to the right location .
        ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
@@ -3108,7 +3123,6 @@ my $query = qq|SELECT count(*)
 my $sth = $dbh->prepare($query);
 $sth->execute($branchcode,$week_day);
 my $result=$sth->fetchrow;
-$sth->finish;
 return $result;
 }
 
@@ -3140,7 +3154,6 @@ my $query=qq|SELECT count(*)
 my $sth = $dbh->prepare($query);
 $sth->execute($years,$month,$day,$branchcode);
 my $countspecial=$sth->fetchrow ;
-$sth->finish;
 return $countspecial;
 }
 
@@ -3169,7 +3182,6 @@ my $query=qq|SELECT count(*)
 my $sth = $dbh->prepare($query);
 $sth->execute($month,$day,$branchcode);
 my $countspecial=$sth->fetchrow ;
-$sth->finish;
 return $countspecial;
 }
 
@@ -3185,7 +3197,6 @@ my $query=qq|SELECT count(*)
 my $sth = $dbh->prepare($query);
 $sth->execute($barcode);
 my $exist=$sth->fetchrow ;
-$sth->finish;
 return $exist;
 }
 
@@ -3227,28 +3238,31 @@ $code is either itemtype or collection code depending on what the pref BranchTra
 
 sub CreateBranchTransferLimit {
    my ( $toBranch, $fromBranch, $code ) = @_;
-
+   return unless defined($toBranch) && defined($fromBranch);
    my $limitType = C4::Context->preference("BranchTransferLimitsType");
    
    my $dbh = C4::Context->dbh;
    
    my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( $limitType, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
-   $sth->execute( $code, $toBranch, $fromBranch );
+   return $sth->execute( $code, $toBranch, $fromBranch );
 }
 
 =head2 DeleteBranchTransferLimits
 
-DeleteBranchTransferLimits($frombranch);
+    my $result = DeleteBranchTransferLimits($frombranch);
 
-Deletes all the branch transfer limits for one branch
+Deletes all the library transfer limits for one library.  Returns the
+number of limits deleted, 0e0 if no limits were deleted, or undef if
+no arguments are supplied.
 
 =cut
 
 sub DeleteBranchTransferLimits {
     my $branch = shift;
+    return unless defined $branch;
     my $dbh    = C4::Context->dbh;
     my $sth    = $dbh->prepare("DELETE FROM branch_transfer_limits WHERE fromBranch = ?");
-    $sth->execute($branch);
+    return $sth->execute($branch);
 }
 
 sub ReturnLostItem{
@@ -3266,7 +3280,7 @@ sub ReturnLostItem{
 
 
 sub LostItem{
-    my ($itemnumber, $mark_returned, $charge_fee) = @_;
+    my ($itemnumber, $mark_returned) = @_;
 
     my $dbh = C4::Context->dbh();
     my $sth=$dbh->prepare("SELECT issues.*,items.*,biblio.title 
@@ -3276,16 +3290,21 @@ sub LostItem{
                            WHERE issues.itemnumber=?");
     $sth->execute($itemnumber);
     my $issues=$sth->fetchrow_hashref();
-    $sth->finish;
 
-    # if a borrower lost the item, add a replacement cost to the their record
+    # If a borrower lost the item, add a replacement cost to the their record
     if ( my $borrowernumber = $issues->{borrowernumber} ){
         my $borrower = C4::Members::GetMemberDetails( $borrowernumber );
 
-        C4::Accounts::chargelostitem($borrowernumber, $itemnumber, $issues->{'replacementprice'}, "Lost Item $issues->{'title'} $issues->{'barcode'}")
-          if $charge_fee;
-        #FIXME : Should probably have a way to distinguish this from an item that really was returned.
-        #warn " $issues->{'borrowernumber'}  /  $itemnumber ";
+        if (C4::Context->preference('WhenLostForgiveFine')){
+            my $fix = _FixOverduesOnReturn($borrowernumber, $itemnumber, 1, 0); # 1, 0 = exemptfine, no-dropbox
+            defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $itemnumber...) failed!";  # zero is OK, check defined
+        }
+        if (C4::Context->preference('WhenLostChargeReplacementFee')){
+            C4::Accounts::chargelostitem($borrowernumber, $itemnumber, $issues->{'replacementprice'}, "Lost Item $issues->{'title'} $issues->{'barcode'}");
+            #FIXME : Should probably have a way to distinguish this from an item that really was returned.
+            #warn " $issues->{'borrowernumber'}  /  $itemnumber ";
+        }
+
         MarkIssueReturned($borrowernumber,$itemnumber,undef,undef,$borrower->{'privacy'}) if $mark_returned;
     }
 }
@@ -3295,17 +3314,16 @@ sub GetOfflineOperations {
     my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE branchcode=? ORDER BY timestamp");
     $sth->execute(C4::Context->userenv->{'branch'});
     my $results = $sth->fetchall_arrayref({});
-    $sth->finish;
     return $results;
 }
 
 sub GetOfflineOperation {
+    my $operationid = shift;
+    return unless $operationid;
     my $dbh = C4::Context->dbh;
     my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE operationid=?");
-    $sth->execute( shift );
-    my $result = $sth->fetchrow_hashref;
-    $sth->finish;
-    return $result;
+    $sth->execute( $operationid );
+    return $sth->fetchrow_hashref;
 }
 
 sub AddOfflineOperation {
@@ -3462,6 +3480,25 @@ sub CheckIfIssuedToPatron {
     return;
 }
 
+=head2 IsItemIssued
+
+  IsItemIssued( $itemnumber )
+
+  Return 1 if the item is on loan, otherwise return 0
+
+=cut
+
+sub IsItemIssued {
+    my $itemnumber = shift;
+    my $dbh = C4::Context->dbh;
+    my $sth = $dbh->prepare(q{
+        SELECT COUNT(*)
+        FROM issues
+        WHERE itemnumber = ?
+    });
+    $sth->execute($itemnumber);
+    return $sth->fetchrow;
+}
 
 1;