Bug 19056: Replace C4::Reserves::GetReserveCount with Koha::Patron->holds->count
[koha.git] / C4 / Reserves.pm
index 5874260..924ce5f 100644 (file)
@@ -34,16 +34,26 @@ use C4::Accounts;
 use C4::Members::Messaging;
 use C4::Members qw();
 use C4::Letters;
-use C4::Branch qw( GetBranchDetail );
-use C4::Dates qw( format_date_in_iso );
+use C4::Log;
 
+use Koha::Biblios;
 use Koha::DateUtils;
 use Koha::Calendar;
 use Koha::Database;
+use Koha::Hold;
+use Koha::Old::Hold;
+use Koha::Holds;
+use Koha::Libraries;
+use Koha::IssuingRules;
+use Koha::Items;
+use Koha::ItemTypes;
+use Koha::Patrons;
 
 use List::MoreUtils qw( firstidx any );
+use Carp;
+use Data::Dumper;
 
-use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
+use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
 
 =head1 NAME
 
@@ -61,7 +71,7 @@ This modules provides somes functions to deal with reservations.
   The following columns contains important values :
   - priority >0      : then the reserve is at 1st stage, and not yet affected to any item.
              =0      : then the reserve is being dealed
-  - found : NULL       : means the patron requested the 1st available, and we haven't choosen the item
+  - found : NULL       : means the patron requested the 1st available, and we haven't chosen the item
             T(ransit)  : the reserve is linked to an item but is in transit to the pickup branch
             W(aiting)  : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
             F(inished) : the reserve has been completed, and is done
@@ -74,7 +84,7 @@ This modules provides somes functions to deal with reservations.
          if there is no transfer to do, the reserve waiting
          patron can pick it up                                    P =0, F=W,    I=filled
          if there is a transfer to do, write in branchtransfer    P =0, F=T,    I=filled
-           The pickup library recieve the book, it check in       P =0, F=W,    I=filled
+           The pickup library receive the book, it check in       P =0, F=W,    I=filled
   The patron borrow the book                                      P =0, F=F,    I=filled
 
   ==== 2nd use case ====
@@ -89,22 +99,13 @@ This modules provides somes functions to deal with reservations.
 =cut
 
 BEGIN {
-    # set the version for version checking
-    $VERSION = 3.07.00.049;
     require Exporter;
     @ISA = qw(Exporter);
     @EXPORT = qw(
         &AddReserve
 
         &GetReserve
-        &GetReservesFromItemnumber
-        &GetReservesFromBiblionumber
-        &GetReservesFromBorrowernumber
         &GetReservesForBranch
-        &GetReservesToBranch
-        &GetReserveCount
-        &GetReserveFee
-        &GetReserveInfo
         &GetReserveStatus
 
         &GetOtherReserves
@@ -119,7 +120,7 @@ BEGIN {
 
         &CheckReserves
         &CanBookBeReserved
-       &CanItemBeReserved
+        &CanItemBeReserved
         &CanReserveBeCanceledFromOpac
         &CancelReserve
         &CancelExpiredReserves
@@ -140,38 +141,47 @@ BEGIN {
         &GetReservesControlBranch
 
         IsItemOnHoldAndFound
+
+        GetMaxPatronHoldsForRecord
     );
     @EXPORT_OK = qw( MergeHolds );
 }
 
 =head2 AddReserve
 
-    AddReserve($branch,$borrowernumber,$biblionumber,$constraint,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
+    AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
+
+Adds reserve and generates HOLDPLACED message.
+
+The following tables are available witin the HOLDPLACED message:
+
+    branches
+    borrowers
+    biblio
+    biblioitems
+    items
+    reserves
 
 =cut
 
 sub AddReserve {
     my (
-        $branch,    $borrowernumber, $biblionumber,
-        $constraint, $bibitems,  $priority, $resdate, $expdate, $notes,
-        $title,      $checkitem, $found
+        $branch,   $borrowernumber, $biblionumber, $bibitems,
+        $priority, $resdate,        $expdate,      $notes,
+        $title,    $checkitem,      $found,        $itemtype
     ) = @_;
-    my $fee =
-          GetReserveFee($borrowernumber, $biblionumber, $constraint,
-            $bibitems );
-    my $dbh     = C4::Context->dbh;
-    my $const   = lc substr( $constraint, 0, 1 );
-    $resdate = format_date_in_iso( $resdate ) if ( $resdate );
-    $resdate = C4::Dates->today( 'iso' ) unless ( $resdate );
-    if ($expdate) {
-        $expdate = format_date_in_iso( $expdate );
-    } else {
-        undef $expdate; # make reserves.expirationdate default to null rather than '0000-00-00'
-    }
-    if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
-       # Make room in reserves for this before those of a later reserve date
-       $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
+
+    $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
+        or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
+
+    $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
+
+    if ( C4::Context->preference('AllowHoldDateInFuture') ) {
+
+        # Make room in reserves for this before those of a later reserve date
+        $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
     }
+
     my $waitingdate;
 
     # If the reserv had the waiting status, we had the value of the resdate
@@ -179,55 +189,59 @@ sub AddReserve {
         $waitingdate = $resdate;
     }
 
-    #eval {
+    # Don't add itemtype limit if specific item is selected
+    $itemtype = undef if $checkitem;
+
     # updates take place here
-    if ( $fee > 0 ) {
-        my $nextacctno = &getnextacctno( $borrowernumber );
-        my $query      = qq{
-        INSERT INTO accountlines
-            (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
-        VALUES
-            (?,?,now(),?,?,'Res',?)
-    };
-        my $usth = $dbh->prepare($query);
-        $usth->execute( $borrowernumber, $nextacctno, $fee,
-            "Reserve Charge - $title", $fee );
+    my $hold = Koha::Hold->new(
+        {
+            borrowernumber => $borrowernumber,
+            biblionumber   => $biblionumber,
+            reservedate    => $resdate,
+            branchcode     => $branch,
+            priority       => $priority,
+            reservenotes   => $notes,
+            itemnumber     => $checkitem,
+            found          => $found,
+            waitingdate    => $waitingdate,
+            expirationdate => $expdate,
+            itemtype       => $itemtype,
+        }
+    )->store();
+
+    logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
+        if C4::Context->preference('HoldsLog');
+
+    my $reserve_id = $hold->id();
+
+    # add a reserve fee if needed
+    if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
+        my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
+        ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
     }
 
-    #if ($const eq 'a'){
-    my $query = qq{
-        INSERT INTO reserves
-            (borrowernumber,biblionumber,reservedate,branchcode,constrainttype,
-            priority,reservenotes,itemnumber,found,waitingdate,expirationdate)
-        VALUES
-             (?,?,?,?,?,
-             ?,?,?,?,?,?)
-             };
-    my $sth = $dbh->prepare($query);
-    $sth->execute(
-        $borrowernumber, $biblionumber, $resdate, $branch,
-        $const,          $priority,     $notes,   $checkitem,
-        $found,          $waitingdate, $expdate
-    );
-    my $reserve_id = $sth->{mysql_insertid};
+    _FixPriority({ biblionumber => $biblionumber});
 
     # Send e-mail to librarian if syspref is active
     if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
-        my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
-        my $branch_details = C4::Branch::GetBranchDetail($borrower->{branchcode});
+        my $patron = Koha::Patrons->find( $borrowernumber );
+        my $library = $patron->library;
         if ( my $letter =  C4::Letters::GetPreparedLetter (
             module => 'reserves',
             letter_code => 'HOLDPLACED',
             branchcode => $branch,
+            lang => $patron->lang,
             tables => {
-                'branches'  => $branch_details,
-                'borrowers' => $borrower,
-                'biblio'    => $biblionumber,
-                'items'     => $checkitem,
+                'branches'    => $library->unblessed,
+                'borrowers'   => $patron->unblessed,
+                'biblio'      => $biblionumber,
+                'biblioitems' => $biblionumber,
+                'items'       => $checkitem,
+                'reserves'    => $hold->unblessed,
             },
         ) ) {
 
-            my $admin_email_address =$branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
+            my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
 
             C4::Letters::EnqueueLetter(
                 {   letter                 => $letter,
@@ -240,19 +254,6 @@ sub AddReserve {
         }
     }
 
-    #}
-    ($const eq "o" || $const eq "e") or return;   # FIXME: why not have a useful return value?
-    $query = qq{
-        INSERT INTO reserveconstraints
-            (borrowernumber,biblionumber,reservedate,biblioitemnumber)
-        VALUES
-            (?,?,?,?)
-    };
-    $sth = $dbh->prepare($query);    # keep prepare outside the loop!
-    foreach (@$bibitems) {
-        $sth->execute($borrowernumber, $biblionumber, $resdate, $_);
-    }
-        
     return $reserve_id;
 }
 
@@ -268,189 +269,13 @@ sub GetReserve {
     my ($reserve_id) = @_;
 
     my $dbh = C4::Context->dbh;
+
     my $query = "SELECT * FROM reserves WHERE reserve_id = ?";
     my $sth = $dbh->prepare( $query );
     $sth->execute( $reserve_id );
     return $sth->fetchrow_hashref();
 }
 
-=head2 GetReservesFromBiblionumber
-
-  my $reserves = GetReservesFromBiblionumber({
-    biblionumber => $biblionumber,
-    [ itemnumber => $itemnumber, ]
-    [ all_dates => 1|0 ]
-  });
-
-This function gets the list of reservations for one C<$biblionumber>,
-returning an arrayref pointing to the reserves for C<$biblionumber>.
-
-By default, only reserves whose start date falls before the current
-time are returned.  To return all reserves, including future ones,
-the C<all_dates> parameter can be included and set to a true value.
-
-If the C<itemnumber> parameter is supplied, reserves must be targeted
-to that item or not targeted to any item at all; otherwise, they
-are excluded from the list.
-
-=cut
-
-sub GetReservesFromBiblionumber {
-    my ( $params ) = @_;
-    my $biblionumber = $params->{biblionumber} or return [];
-    my $itemnumber = $params->{itemnumber};
-    my $all_dates = $params->{all_dates} // 0;
-    my $dbh   = C4::Context->dbh;
-
-    # Find the desired items in the reserves
-    my @params;
-    my $query = "
-        SELECT  reserve_id,
-                branchcode,
-                timestamp AS rtimestamp,
-                priority,
-                biblionumber,
-                borrowernumber,
-                reservedate,
-                constrainttype,
-                found,
-                itemnumber,
-                reservenotes,
-                expirationdate,
-                lowestPriority,
-                suspend,
-                suspend_until
-        FROM     reserves
-        WHERE biblionumber = ? ";
-    push( @params, $biblionumber );
-    unless ( $all_dates ) {
-        $query .= " AND reservedate <= CAST(NOW() AS DATE) ";
-    }
-    if ( $itemnumber ) {
-        $query .= " AND ( itemnumber IS NULL OR itemnumber = ? )";
-        push( @params, $itemnumber );
-    }
-    $query .= "ORDER BY priority";
-    my $sth = $dbh->prepare($query);
-    $sth->execute( @params );
-    my @results;
-    my $i = 0;
-    while ( my $data = $sth->fetchrow_hashref ) {
-
-        # FIXME - What is this doing? How do constraints work?
-        if ($data->{constrainttype} eq 'o') {
-            $query = '
-                SELECT biblioitemnumber
-                FROM  reserveconstraints
-                WHERE  biblionumber   = ?
-                AND   borrowernumber = ?
-                AND   reservedate    = ?
-            ';
-            my $csth = $dbh->prepare($query);
-            $csth->execute($data->{biblionumber}, $data->{borrowernumber}, $data->{reservedate});
-            my @bibitemno;
-            while ( my $bibitemnos = $csth->fetchrow_array ) {
-                push( @bibitemno, $bibitemnos );    # FIXME: inefficient: use fetchall_arrayref
-            }
-            my $count = scalar @bibitemno;
-
-            # if we have two or more different specific itemtypes
-            # reserved by same person on same day
-            my $bdata;
-            if ( $count > 1 ) {
-                $bdata = GetBiblioItemData( $bibitemno[$i] );   # FIXME: This doesn't make sense.
-                $i++; #  $i can increase each pass, but the next @bibitemno might be smaller?
-            }
-            else {
-                # Look up the book we just found.
-                $bdata = GetBiblioItemData( $bibitemno[0] );
-            }
-            # Add the results of this latest search to the current
-            # results.
-            # FIXME - An 'each' would probably be more efficient.
-            foreach my $key ( keys %$bdata ) {
-                $data->{$key} = $bdata->{$key};
-            }
-        }
-        push @results, $data;
-    }
-    return \@results;
-}
-
-=head2 GetReservesFromItemnumber
-
- ( $reservedate, $borrowernumber, $branchcode, $reserve_id, $waitingdate ) = GetReservesFromItemnumber($itemnumber);
-
-Get the first reserve for a specific item number (based on priority). Returns the abovementioned values for that reserve.
-
-The routine does not look at future reserves (read: item level holds), but DOES include future waits (a confirmed future hold).
-
-=cut
-
-sub GetReservesFromItemnumber {
-    my ($itemnumber) = @_;
-
-    my $schema = Koha::Database->new()->schema();
-
-    my $r = $schema->resultset('Reserve')->search(
-        {
-            itemnumber => $itemnumber,
-            suspend    => 0,
-            -or        => [
-                reservedate => \'<= CAST( NOW() AS DATE )',
-                waitingdate => { '!=', undef }
-            ]
-        },
-        {
-            order_by => 'priority',
-        }
-    )->first();
-
-    return unless $r;
-
-    return (
-        $r->reservedate(),
-        $r->get_column('borrowernumber'),
-        $r->get_column('branchcode'),
-        $r->reserve_id(),
-        $r->waitingdate(),
-    );
-}
-
-=head2 GetReservesFromBorrowernumber
-
-    $borrowerreserv = GetReservesFromBorrowernumber($borrowernumber,$tatus);
-
-TODO :: Descritpion
-
-=cut
-
-sub GetReservesFromBorrowernumber {
-    my ( $borrowernumber, $status ) = @_;
-    my $dbh   = C4::Context->dbh;
-    my $sth;
-    if ($status) {
-        $sth = $dbh->prepare("
-            SELECT *
-            FROM   reserves
-            WHERE  borrowernumber=?
-                AND found =?
-            ORDER BY reservedate
-        ");
-        $sth->execute($borrowernumber,$status);
-    } else {
-        $sth = $dbh->prepare("
-            SELECT *
-            FROM   reserves
-            WHERE  borrowernumber=?
-            ORDER BY reservedate
-        ");
-        $sth->execute($borrowernumber);
-    }
-    my $data = $sth->fetchall_arrayref({});
-    return @$data;
-}
-#-------------------------------------------------------------------------------------
 =head2 CanBookBeReserved
 
   $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
@@ -488,103 +313,137 @@ sub CanBookBeReserved{
          damaged,         if the Item is damaged.
          cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
          tooManyReserves, if the borrower has exceeded his maximum reserve amount.
+         notReservable,   if holds on this item are not allowed
 
 =cut
 
-sub CanItemBeReserved{
-    my ($borrowernumber, $itemnumber) = @_;
+sub CanItemBeReserved {
+    my ( $borrowernumber, $itemnumber ) = @_;
+
+    my $dbh = C4::Context->dbh;
+    my $ruleitemtype;    # itemtype of the matching issuing rule
+    my $allowedreserves  = 0; # Total number of holds allowed across all records
+    my $holds_per_record = 1; # Total number of holds allowed for this one given record
 
-    my $dbh             = C4::Context->dbh;
-    my $ruleitemtype; # itemtype of the matching issuing rule
-    my $allowedreserves = 0;
-            
     # we retrieve borrowers and items informations #
     # item->{itype} will come for biblioitems if necessery
-    my $item = GetItem($itemnumber);
-    my $biblioData = C4::Biblio::GetBiblioData( $item->{biblionumber} );
-    my $borrower = C4::Members::GetMember('borrowernumber'=>$borrowernumber);
+    my $item       = GetItem($itemnumber);
+    my $biblio     = Koha::Biblios->find( $item->{biblionumber} );
+    my $patron = Koha::Patrons->find( $borrowernumber );
+    my $borrower = $patron->unblessed;
 
     # If an item is damaged and we don't allow holds on damaged items, we can stop right here
-    return 'damaged' if ( $item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems') );
+    return 'damaged'
+      if ( $item->{damaged}
+        && !C4::Context->preference('AllowHoldsOnDamagedItems') );
 
-    #Check for the age restriction
-    my ($ageRestriction, $daysToAgeRestriction) = C4::Circulation::GetAgeRestriction( $biblioData->{agerestriction}, $borrower );
+    # Check for the age restriction
+    my ( $ageRestriction, $daysToAgeRestriction ) =
+      C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
     return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
 
+    # Check that the patron doesn't have an item level hold on this item already
+    return 'itemAlreadyOnHold'
+      if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
+
     my $controlbranch = C4::Context->preference('ReservesControlBranch');
-    my $itemtypefield = C4::Context->preference('item-level_itypes') ? "itype" : "itemtype";
-
-    # we retrieve user rights on this itemtype and branchcode
-    my $sth = $dbh->prepare("SELECT categorycode, itemtype, branchcode, reservesallowed
-                             FROM issuingrules
-                             WHERE (categorycode in (?,'*') )
-                             AND (itemtype IN (?,'*'))
-                             AND (branchcode IN (?,'*'))
-                             ORDER BY
-                               categorycode DESC,
-                               itemtype     DESC,
-                               branchcode   DESC;"
-                           );
-
-    my $querycount ="SELECT
-                            count(*) as count
-                            FROM reserves
-                                LEFT JOIN items USING (itemnumber)
-                                LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
-                                LEFT JOIN borrowers USING (borrowernumber)
-                            WHERE borrowernumber = ?
-                                ";
-    
-    
-    my $branchcode   = "";
-    my $branchfield  = "reserves.branchcode";
-
-    if( $controlbranch eq "ItemHomeLibrary" ){
+
+    my $querycount = q{
+        SELECT count(*) AS count
+          FROM reserves
+     LEFT JOIN items USING (itemnumber)
+     LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
+     LEFT JOIN borrowers USING (borrowernumber)
+         WHERE borrowernumber = ?
+    };
+
+    my $branchcode  = "";
+    my $branchfield = "reserves.branchcode";
+
+    if ( $controlbranch eq "ItemHomeLibrary" ) {
         $branchfield = "items.homebranch";
-        $branchcode = $item->{homebranch};
-    }elsif( $controlbranch eq "PatronLibrary" ){
+        $branchcode  = $item->{homebranch};
+    }
+    elsif ( $controlbranch eq "PatronLibrary" ) {
         $branchfield = "borrowers.branchcode";
-        $branchcode = $borrower->{branchcode};
-    }
-    
-    # we retrieve rights 
-    $sth->execute($borrower->{'categorycode'}, $item->{'itype'}, $branchcode);
-    if(my $rights = $sth->fetchrow_hashref()){
-        $ruleitemtype    = $rights->{itemtype};
-        $allowedreserves = $rights->{reservesallowed}; 
-    }else{
+        $branchcode  = $borrower->{branchcode};
+    }
+
+    # we retrieve rights
+    if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
+        $ruleitemtype     = $rights->{itemtype};
+        $allowedreserves  = $rights->{reservesallowed};
+        $holds_per_record = $rights->{holds_per_record};
+    }
+    else {
         $ruleitemtype = '*';
     }
 
+    $item = Koha::Items->find( $itemnumber );
+    my $holds = Koha::Holds->search(
+        {
+            borrowernumber => $borrowernumber,
+            biblionumber   => $item->biblionumber,
+            found          => undef, # Found holds don't count against a patron's holds limit
+        }
+    );
+    if ( $holds->count() >= $holds_per_record ) {
+        return "tooManyHoldsForThisRecord";
+    }
+
     # we retrieve count
 
     $querycount .= "AND $branchfield = ?";
-    
-    $querycount .= " AND $itemtypefield = ?" if ($ruleitemtype ne "*");
+
+    # If using item-level itypes, fall back to the record
+    # level itemtype if the hold has no associated item
+    $querycount .=
+      C4::Context->preference('item-level_itypes')
+      ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
+      : " AND biblioitems.itemtype = ?"
+      if ( $ruleitemtype ne "*" );
+
     my $sthcount = $dbh->prepare($querycount);
-    
-    if($ruleitemtype eq "*"){
-        $sthcount->execute($borrowernumber, $branchcode);
-    }else{
-        $sthcount->execute($borrowernumber, $branchcode, $ruleitemtype);
+
+    if ( $ruleitemtype eq "*" ) {
+        $sthcount->execute( $borrowernumber, $branchcode );
+    }
+    else {
+        $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
     }
 
     my $reservecount = "0";
-    if(my $rowcount = $sthcount->fetchrow_hashref()){
+    if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
         $reservecount = $rowcount->{count};
     }
+
     # we check if it's ok or not
-    if( $reservecount >= $allowedreserves ){
+    if ( $reservecount >= $allowedreserves ) {
         return 'tooManyReserves';
     }
 
+    my $circ_control_branch =
+      C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
+    my $branchitemrule =
+      C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype );
+
+    if ( $branchitemrule->{holdallowed} == 0 ) {
+        return 'notReservable';
+    }
+
+    if (   $branchitemrule->{holdallowed} == 1
+        && $borrower->{branchcode} ne $item->homebranch )
+    {
+        return 'cannotReserveFromOtherBranches';
+    }
+
     # If reservecount is ok, we check item branch if IndependentBranches is ON
     # and canreservefromotherbranches is OFF
     if ( C4::Context->preference('IndependentBranches')
         and !C4::Context->preference('canreservefromotherbranches') )
     {
-        my $itembranch = $item->{homebranch};
-        if ($itembranch ne $borrower->{branchcode}) {
+        my $itembranch = $item->homebranch;
+        if ( $itembranch ne $borrower->{branchcode} ) {
             return 'cannotReserveFromOtherBranches';
         }
     }
@@ -615,36 +474,11 @@ sub CanReserveBeCanceledFromOpac {
 
 }
 
-#--------------------------------------------------------------------------------
-=head2 GetReserveCount
-
-  $number = &GetReserveCount($borrowernumber);
-
-this function returns the number of reservation for a borrower given on input arg.
-
-=cut
-
-sub GetReserveCount {
-    my ($borrowernumber) = @_;
-
-    my $dbh = C4::Context->dbh;
-
-    my $query = "
-        SELECT COUNT(*) AS counter
-        FROM reserves
-        WHERE borrowernumber = ?
-    ";
-    my $sth = $dbh->prepare($query);
-    $sth->execute($borrowernumber);
-    my $row = $sth->fetchrow_hashref;
-    return $row->{counter};
-}
-
 =head2 GetOtherReserves
 
   ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
 
-Check queued list of this document and check if this document must be  transfered
+Check queued list of this document and check if this document must be transferred
 
 =cut
 
@@ -688,132 +522,65 @@ sub GetOtherReserves {
     return ( $messages, $nextreservinfo );
 }
 
-=head2 GetReserveFee
+=head2 ChargeReserveFee
 
-  $fee = GetReserveFee($borrowernumber,$biblionumber,$constraint,$biblionumber);
+    $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
 
-Calculate the fee for a reserve
+    Charge the fee for a reserve (if $fee > 0)
 
 =cut
 
-sub GetReserveFee {
-    my ($borrowernumber, $biblionumber, $constraint, $bibitems ) = @_;
-
-    #check for issues;
-    my $dbh   = C4::Context->dbh;
-    my $const = lc substr( $constraint, 0, 1 );
-    my $query = qq{
-      SELECT * FROM borrowers
-    LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
-    WHERE borrowernumber = ?
+sub ChargeReserveFee {
+    my ( $borrowernumber, $fee, $title ) = @_;
+    return if !$fee || $fee==0; # the last test is needed to include 0.00
+    my $accquery = qq{
+INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
     };
-    my $sth = $dbh->prepare($query);
-    $sth->execute($borrowernumber);
-    my $data = $sth->fetchrow_hashref;
-    my $fee      = $data->{'reservefee'};
-    my $cntitems = @- > $bibitems;
-
-    if ( $fee > 0 ) {
-
-        # check for items on issue
-        # first find biblioitem records
-        my @biblioitems;
-        my $sth1 = $dbh->prepare(
-            "SELECT * FROM biblio LEFT JOIN biblioitems on biblio.biblionumber = biblioitems.biblionumber
-                   WHERE (biblio.biblionumber = ?)"
-        );
-        $sth1->execute($biblionumber);
-        while ( my $data1 = $sth1->fetchrow_hashref ) {
-            if ( $const eq "a" ) {
-                push @biblioitems, $data1;
-            }
-            else {
-                my $found = 0;
-                my $x     = 0;
-                while ( $x < $cntitems ) {
-                    if ( @$bibitems->{'biblioitemnumber'} ==
-                        $data->{'biblioitemnumber'} )
-                    {
-                        $found = 1;
-                    }
-                    $x++;
-                }
-                if ( $const eq 'o' ) {
-                    if ( $found == 1 ) {
-                        push @biblioitems, $data1;
-                    }
-                }
-                else {
-                    if ( $found == 0 ) {
-                        push @biblioitems, $data1;
-                    }
-                }
-            }
-        }
-        my $cntitemsfound = @biblioitems;
-        my $issues        = 0;
-        my $x             = 0;
-        my $allissued     = 1;
-        while ( $x < $cntitemsfound ) {
-            my $bitdata = $biblioitems[$x];
-            my $sth2    = $dbh->prepare(
-                "SELECT * FROM items
-                     WHERE biblioitemnumber = ?"
-            );
-            $sth2->execute( $bitdata->{'biblioitemnumber'} );
-            while ( my $itdata = $sth2->fetchrow_hashref ) {
-                my $sth3 = $dbh->prepare(
-                    "SELECT * FROM issues
-                       WHERE itemnumber = ?"
-                );
-                $sth3->execute( $itdata->{'itemnumber'} );
-                if ( my $isdata = $sth3->fetchrow_hashref ) {
-                }
-                else {
-                    $allissued = 0;
-                }
-            }
-            $x++;
-        }
-        if ( $allissued == 0 ) {
-            my $rsth =
-              $dbh->prepare("SELECT * FROM reserves WHERE biblionumber = ?");
-            $rsth->execute($biblionumber);
-            if ( my $rdata = $rsth->fetchrow_hashref ) {
-            }
-            else {
-                $fee = 0;
-            }
-        }
-    }
-    return $fee;
+    my $dbh = C4::Context->dbh;
+    my $nextacctno = &getnextacctno( $borrowernumber );
+    $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
 }
 
-=head2 GetReservesToBranch
+=head2 GetReserveFee
 
-  @transreserv = GetReservesToBranch( $frombranch );
+    $fee = GetReserveFee( $borrowernumber, $biblionumber );
 
-Get reserve list for a given branch
+    Calculate the fee for a reserve (if applicable).
 
 =cut
 
-sub GetReservesToBranch {
-    my ( $frombranch ) = @_;
+sub GetReserveFee {
+    my ( $borrowernumber, $biblionumber ) = @_;
+    my $borquery = qq{
+SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
+    };
+    my $issue_qry = qq{
+SELECT COUNT(*) FROM items
+LEFT JOIN issues USING (itemnumber)
+WHERE items.biblionumber=? AND issues.issue_id IS NULL
+    };
+    my $holds_qry = qq{
+SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
+    };
+
     my $dbh = C4::Context->dbh;
-    my $sth = $dbh->prepare(
-        "SELECT reserve_id,borrowernumber,reservedate,itemnumber,timestamp
-         FROM reserves 
-         WHERE priority='0' 
-           AND branchcode=?"
-    );
-    $sth->execute( $frombranch );
-    my @transreserv;
-    my $i = 0;
-    while ( my $data = $sth->fetchrow_hashref ) {
-        $transreserv[$i] = $data;
-        $i++;
+    my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
+    my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
+    if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
+        # This is a reconstruction of the old code:
+        # Compare number of items with items issued, and optionally check holds
+        # If not all items are issued and there are no holds: charge no fee
+        # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
+        my ( $notissued, $reserved );
+        ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
+            ( $biblionumber ) );
+        if( $notissued ) {
+            ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
+                ( $biblionumber, $borrowernumber ) );
+            $fee = 0 if $reserved == 0;
+        }
     }
-    return (@transreserv);
+    return $fee;
 }
 
 =head2 GetReservesForBranch
@@ -827,8 +594,8 @@ sub GetReservesForBranch {
     my $dbh = C4::Context->dbh;
 
     my $query = "
-        SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate
-        FROM   reserves 
+        SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate, expirationdate
+        FROM   reserves
         WHERE   priority='0'
         AND found='W'
     ";
@@ -988,12 +755,12 @@ sub CheckReserves {
             if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
                 return ( "Waiting", $res, \@reserves ); # Found it
             } else {
-                my $borrowerinfo;
+                my $patron;
                 my $iteminfo;
                 my $local_hold_match;
 
                 if ($LocalHoldsPriority) {
-                    $borrowerinfo = C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
+                    $patron = Koha::Patrons->find( $res->{borrowernumber} );
                     $iteminfo = C4::Items::GetItem($itemnumber);
 
                     my $local_holds_priority_item_branchcode =
@@ -1002,7 +769,7 @@ sub CheckReserves {
                       ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
                       ? $res->{branchcode}
                       : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
-                      ? $borrowerinfo->{branchcode}
+                      ? $patron->branchcode
                       : undef;
                     $local_hold_match =
                       $local_holds_priority_item_branchcode eq
@@ -1011,12 +778,14 @@ sub CheckReserves {
 
                 # See if this item is more important than what we've got so far
                 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
-                    $borrowerinfo ||= C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
                     $iteminfo ||= C4::Items::GetItem($itemnumber);
-                    my $branch = GetReservesControlBranch( $iteminfo, $borrowerinfo );
+                    next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
+                    $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
+                    my $branch = GetReservesControlBranch( $iteminfo, $patron->unblessed );
                     my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
                     next if ($branchitemrule->{'holdallowed'} == 0);
-                    next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $borrowerinfo->{'branchcode'}));
+                    next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
+                    next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy} }) );
                     $priority = $res->{'priority'};
                     $highest  = $res;
                     last if $local_hold_match;
@@ -1045,52 +814,28 @@ Cancels all reserves with an expiration date from before today.
 
 sub CancelExpiredReserves {
 
-    # Cancel reserves that have passed their expiration date.
+    my $today = dt_from_string();
+    my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
+
     my $dbh = C4::Context->dbh;
     my $sth = $dbh->prepare( "
         SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
         AND expirationdate IS NOT NULL
-        AND found IS NULL
     " );
     $sth->execute();
 
     while ( my $res = $sth->fetchrow_hashref() ) {
-        CancelReserve({ reserve_id => $res->{'reserve_id'} });
-    }
-
-    # Cancel reserves that have been waiting too long
-    if ( C4::Context->preference("ExpireReservesMaxPickUpDelay") ) {
-        my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
-        my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
-        my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
-
-        my $today = dt_from_string();
-
-        my $query = "SELECT * FROM reserves WHERE TO_DAYS( NOW() ) - TO_DAYS( waitingdate ) > ? AND found = 'W' AND priority = 0";
-        $sth = $dbh->prepare( $query );
-        $sth->execute( $max_pickup_delay );
+        my $calendar = Koha::Calendar->new( branchcode => $res->{'branchcode'} );
+        my $cancel_params = { reserve_id => $res->{'reserve_id'} };
 
-        while ( my $res = $sth->fetchrow_hashref ) {
-            my $do_cancel = 1;
-            unless ( $cancel_on_holidays ) {
-                my $calendar = Koha::Calendar->new( branchcode => $res->{'branchcode'} );
-                my $is_holiday = $calendar->is_holiday( $today );
+        next if !$cancel_on_holidays && $calendar->is_holiday( $today );
 
-                if ( $is_holiday ) {
-                    $do_cancel = 0;
-                }
-            }
-
-            if ( $do_cancel ) {
-                if ( $charge ) {
-                    manualinvoice($res->{'borrowernumber'}, $res->{'itemnumber'}, 'Hold waiting too long', 'F', $charge);
-                }
-
-                CancelReserve({ reserve_id => $res->{'reserve_id'} });
-            }
+        if ( $res->{found} eq 'W' ) {
+            $cancel_params->{charge_cancel_fee} = 1;
         }
-    }
 
+        CancelReserve($cancel_params);
+    }
 }
 
 =head2 AutoUnsuspendReserves
@@ -1102,20 +847,18 @@ Unsuspends all suspended reserves with a suspend_until date from before today.
 =cut
 
 sub AutoUnsuspendReserves {
+    my $today = dt_from_string();
 
-    my $dbh = C4::Context->dbh;
-
-    my $query = "UPDATE reserves SET suspend = 0, suspend_until = NULL WHERE DATE( suspend_until ) < DATE( CURDATE() )";
-    my $sth = $dbh->prepare( $query );
-    $sth->execute();
+    my @holds = Koha::Holds->search( { suspend_until => { '<' => $today->ymd() } } );
 
+    map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
 }
 
 =head2 CancelReserve
 
-  CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber ] });
+  CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber, ] [ charge_cancel_fee => 1 ] });
 
-Cancels a reserve.
+Cancels a reserve. If C<charge_cancel_fee> is passed and the C<ExpireReservesMaxPickUpDelayCharge> syspref is set, charge that fee to the patron's account.
 
 =cut
 
@@ -1123,7 +866,9 @@ sub CancelReserve {
     my ( $params ) = @_;
 
     my $reserve_id = $params->{'reserve_id'};
-    $reserve_id = GetReserveId( $params ) unless ( $reserve_id );
+    # Filter out only the desired keys; this will insert undefined values for elements missing in
+    # \%params, but GetReserveId filters them out anyway.
+    $reserve_id = GetReserveId( { biblionumber => $params->{'biblionumber'}, borrowernumber => $params->{'borrowernumber'}, itemnumber => $params->{'itemnumber'} } ) unless ( $reserve_id );
 
     return unless ( $reserve_id );
 
@@ -1131,10 +876,14 @@ sub CancelReserve {
 
     my $reserve = GetReserve( $reserve_id );
     if ($reserve) {
+
+        my $hold = Koha::Holds->find( $reserve_id );
+        logaction( 'HOLDS', 'CANCEL', $hold->reserve_id, Dumper($hold->unblessed) )
+            if C4::Context->preference('HoldsLog');
+
         my $query = "
             UPDATE reserves
             SET    cancellationdate = now(),
-                   found            = Null,
                    priority         = 0
             WHERE  reserve_id = ?
         ";
@@ -1158,6 +907,12 @@ sub CancelReserve {
 
         # now fix the priority on the others....
         _FixPriority({ biblionumber => $reserve->{biblionumber} });
+
+        # and, if desired, charge a cancel fee
+        my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
+        if ( $charge && $params->{'charge_cancel_fee'} ) {
+            manualinvoice($reserve->{'borrowernumber'}, $reserve->{'itemnumber'}, '', 'HE', $charge);
+        }
     }
 
     return $reserve;
@@ -1216,24 +971,32 @@ sub ModReserve {
     return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
     $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber }) unless ( $reserve_id );
 
-    my $dbh = C4::Context->dbh;
     if ( $rank eq "del" ) {
         CancelReserve({ reserve_id => $reserve_id });
     }
     elsif ($rank =~ /^\d+/ and $rank > 0) {
-        my $query = "
-            UPDATE reserves SET priority = ? ,branchcode = ?, itemnumber = ?, found = NULL, waitingdate = NULL
-            WHERE reserve_id = ?
-        ";
-        my $sth = $dbh->prepare($query);
-        $sth->execute( $rank, $branchcode, $itemnumber, $reserve_id );
+        my $hold = Koha::Holds->find($reserve_id);
+        logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
+            if C4::Context->preference('HoldsLog');
+
+        $hold->set(
+            {
+                priority    => $rank,
+                branchcode  => $branchcode,
+                itemnumber  => $itemnumber,
+                found       => undef,
+                waitingdate => undef
+            }
+        )->store();
 
         if ( defined( $suspend_until ) ) {
             if ( $suspend_until ) {
-                $suspend_until = C4::Dates->new( $suspend_until )->output("iso");
-                $dbh->do("UPDATE reserves SET suspend = 1, suspend_until = ? WHERE reserve_id = ?", undef, ( $suspend_until, $reserve_id ) );
+                $suspend_until = eval { dt_from_string( $suspend_until ) };
+                $hold->suspend_hold( $suspend_until );
             } else {
-                $dbh->do("UPDATE reserves SET suspend_until = NULL WHERE reserve_id = ?", undef, ( $reserve_id ) );
+                # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
+                # If the hold is not suspended, this does nothing.
+                $hold->set( { suspend_until => undef } )->store();
             }
         }
 
@@ -1255,56 +1018,34 @@ whose keys are fields from the reserves table in the Koha database.
 
 sub ModReserveFill {
     my ($res) = @_;
-    my $dbh = C4::Context->dbh;
-    # fill in a reserve record....
     my $reserve_id = $res->{'reserve_id'};
-    my $biblionumber = $res->{'biblionumber'};
-    my $borrowernumber    = $res->{'borrowernumber'};
-    my $resdate = $res->{'reservedate'};
+
+    my $hold = Koha::Holds->find($reserve_id);
 
     # get the priority on this record....
-    my $priority;
-    my $query = "SELECT priority
-                 FROM   reserves
-                 WHERE  biblionumber   = ?
-                  AND   borrowernumber = ?
-                  AND   reservedate    = ?";
-    my $sth = $dbh->prepare($query);
-    $sth->execute( $biblionumber, $borrowernumber, $resdate );
-    ($priority) = $sth->fetchrow_array;
+    my $priority = $hold->priority;
 
-    # update the database...
-    $query = "UPDATE reserves
-                  SET    found            = 'F',
-                         priority         = 0
-                 WHERE  biblionumber     = ?
-                    AND reservedate      = ?
-                    AND borrowernumber   = ?
-                ";
-    $sth = $dbh->prepare($query);
-    $sth->execute( $biblionumber, $resdate, $borrowernumber );
-
-    # move to old_reserves
-    $query = "INSERT INTO old_reserves
-                 SELECT * FROM reserves
-                 WHERE  biblionumber     = ?
-                    AND reservedate      = ?
-                    AND borrowernumber   = ?
-                ";
-    $sth = $dbh->prepare($query);
-    $sth->execute( $biblionumber, $resdate, $borrowernumber );
-    $query = "DELETE FROM reserves
-                 WHERE  biblionumber     = ?
-                    AND reservedate      = ?
-                    AND borrowernumber   = ?
-                ";
-    $sth = $dbh->prepare($query);
-    $sth->execute( $biblionumber, $resdate, $borrowernumber );
+    # update the hold statuses, no need to store it though, we will be deleting it anyway
+    $hold->set(
+        {
+            found    => 'F',
+            priority => 0,
+        }
+    );
+
+    Koha::Old::Hold->new( $hold->unblessed() )->store();
+
+    $hold->delete();
+
+    if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
+        my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
+        ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
+    }
 
     # now fix the priority on the others (if the priority wasn't
     # already sorted!)....
     unless ( $priority == 0 ) {
-        _FixPriority({ reserve_id => $reserve_id, biblionumber => $biblionumber });
+        _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
     }
 }
 
@@ -1337,12 +1078,12 @@ sub ModReserveStatus {
 
 =head2 ModReserveAffect
 
-  &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend);
+  &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
 
-This function affect an item and a status for a given reserve
-The itemnumber parameter is used to find the biblionumber.
-with the biblionumber & the borrowernumber, we can affect the itemnumber
-to the correct reserve.
+This function affect an item and a status for a given reserve, either fetched directly
+by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
+is given, only first reserve returned is affected, which is ok for anything but
+multi-item holds.
 
 if $transferToDo is not set, then the status is set to "Waiting" as well.
 otherwise, a transfer is on the way, and the end of the transfer will
@@ -1351,7 +1092,7 @@ take care of the waiting status
 =cut
 
 sub ModReserveAffect {
-    my ( $itemnumber, $borrowernumber,$transferToDo ) = @_;
+    my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
     my $dbh = C4::Context->dbh;
 
     # we want to attach $itemnumber to $borrowernumber, find the biblionumber
@@ -1362,44 +1103,29 @@ sub ModReserveAffect {
 
     # get request - need to find out if item is already
     # waiting in order to not send duplicate hold filled notifications
-    my $reserve_id = GetReserveId({
-        borrowernumber => $borrowernumber,
-        biblionumber   => $biblionumber,
-    });
-    return unless defined $reserve_id;
-    my $request = GetReserveInfo($reserve_id);
-    my $already_on_shelf = ($request && $request->{found} eq 'W') ? 1 : 0;
-
-    # If we affect a reserve that has to be transfered, don't set to Waiting
-    my $query;
-    if ($transferToDo) {
-    $query = "
-        UPDATE reserves
-        SET    priority = 0,
-               itemnumber = ?,
-               found = 'T'
-        WHERE borrowernumber = ?
-          AND biblionumber = ?
-    ";
-    }
-    else {
-    # affect the reserve to Waiting as well.
-        $query = "
-            UPDATE reserves
-            SET     priority = 0,
-                    found = 'W',
-                    waitingdate = NOW(),
-                    itemnumber = ?
-            WHERE borrowernumber = ?
-              AND biblionumber = ?
-        ";
-    }
-    $sth = $dbh->prepare($query);
-    $sth->execute( $itemnumber, $borrowernumber,$biblionumber);
-    _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber ) if ( !$transferToDo && !$already_on_shelf );
+
+    my $hold;
+    # Find hold by id if we have it
+    $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
+    # Find item level hold for this item if there is one
+    $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
+    # Find record level hold if there is no item level hold
+    $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
+
+    return unless $hold;
+
+    my $already_on_shelf = $hold->found && $hold->found eq 'W';
+
+    $hold->itemnumber($itemnumber);
+    $hold->set_waiting($transferToDo);
+
+    _koha_notify_reserve( $hold->reserve_id )
+      if ( !$transferToDo && !$already_on_shelf );
+
     _FixPriority( { biblionumber => $biblionumber } );
+
     if ( C4::Context->preference("ReturnToShelvingCart") ) {
-      CartToShelf( $itemnumber );
+        CartToShelf($itemnumber);
     }
 
     return;
@@ -1442,7 +1168,7 @@ sub ModReserveMinusPriority {
     my $dbh   = C4::Context->dbh;
     my $query = "
         UPDATE reserves
-        SET    priority = 0 , itemnumber = ? 
+        SET    priority = 0 , itemnumber = ?
         WHERE  reserve_id = ?
     ";
     my $sth_upd = $dbh->prepare($query);
@@ -1451,59 +1177,6 @@ sub ModReserveMinusPriority {
     _FixPriority({ reserve_id => $reserve_id, rank => '0' });
 }
 
-=head2 GetReserveInfo
-
-  &GetReserveInfo($reserve_id);
-
-Get item and borrower details for a current hold.
-Current implementation this query should have a single result.
-
-=cut
-
-sub GetReserveInfo {
-    my ( $reserve_id ) = @_;
-    my $dbh = C4::Context->dbh;
-    my $strsth="SELECT
-                   reserve_id,
-                   reservedate,
-                   reservenotes,
-                   reserves.borrowernumber,
-                   reserves.biblionumber,
-                   reserves.branchcode,
-                   reserves.waitingdate,
-                   notificationdate,
-                   reminderdate,
-                   priority,
-                   found,
-                   firstname,
-                   surname,
-                   phone,
-                   email,
-                   address,
-                   address2,
-                   cardnumber,
-                   city,
-                   zipcode,
-                   biblio.title,
-                   biblio.author,
-                   items.holdingbranch,
-                   items.itemcallnumber,
-                   items.itemnumber,
-                   items.location,
-                   barcode,
-                   notes
-                FROM reserves
-                LEFT JOIN items USING(itemnumber)
-                LEFT JOIN borrowers USING(borrowernumber)
-                LEFT JOIN biblio ON  (reserves.biblionumber=biblio.biblionumber)
-                WHERE reserves.reserve_id = ?";
-    my $sth = $dbh->prepare($strsth);
-    $sth->execute($reserve_id);
-
-    my $data = $sth->fetchrow_hashref;
-    return $data;
-}
-
 =head2 IsAvailableForItemLevelRequest
 
   my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
@@ -1548,8 +1221,30 @@ sub IsAvailableForItemLevelRequest {
         $item->{withdrawn}        ||
         ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
 
+    my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
+
+    if ( $on_shelf_holds == 1 ) {
+        return 1;
+    } elsif ( $on_shelf_holds == 2 ) {
+        my @items =
+          Koha::Items->search( { biblionumber => $item->{biblionumber} } );
+
+        my $any_available = 0;
+
+        foreach my $i (@items) {
+            $any_available = 1
+              unless $i->itemlost
+              || $i->notforloan > 0
+              || $i->withdrawn
+              || $i->onloan
+              || IsItemOnHoldAndFound( $i->id )
+              || ( $i->damaged
+                && !C4::Context->preference('AllowHoldsOnDamagedItems') )
+              || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan;
+        }
 
-    return 1 if _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
+        return $any_available ? 0 : 1;
+    }
 
     return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
 }
@@ -1575,7 +1270,7 @@ sub _get_itype {
 
     my $itype;
     if (C4::Context->preference('item-level_itypes')) {
-        # We cant trust GetItem to honour the syspref, so safest to do it ourselves
+        # We can't trust GetItem to honour the syspref, so safest to do it ourselves
         # When GetItem is fixed, we can remove this
         $itype = $item->{itype};
     }
@@ -1600,8 +1295,8 @@ sub _get_itype {
 sub _OnShelfHoldsAllowed {
     my ($itype,$borrowercategory,$branchcode) = @_;
 
-    my $rule = C4::Circulation::GetIssuingRule($borrowercategory, $itype, $branchcode);
-    return $rule->{onshelfholds};
+    my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
+    return $issuing_rule ? $issuing_rule->onshelfholds : undef;
 }
 
 =head2 AlterPriority
@@ -1616,8 +1311,6 @@ Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was
 sub AlterPriority {
     my ( $where, $reserve_id ) = @_;
 
-    my $dbh = C4::Context->dbh;
-
     my $reserve = GetReserve( $reserve_id );
 
     if ( $reserve->{cancellationdate} ) {
@@ -1657,7 +1350,7 @@ sub ToggleLowestPriority {
 
     my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
     $sth->execute( $reserve_id );
-    
+
     _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
 }
 
@@ -1674,29 +1367,15 @@ be cleared when it is unsuspended.
 sub ToggleSuspend {
     my ( $reserve_id, $suspend_until ) = @_;
 
-    $suspend_until = output_pref(
-        {
-            dt         => dt_from_string($suspend_until),
-            dateformat => 'iso',
-            dateonly   => 1
-        }
-    ) if ($suspend_until);
+    $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
 
-    my $do_until = ( $suspend_until ) ? '?' : 'NULL';
+    my $hold = Koha::Holds->find( $reserve_id );
 
-    my $dbh = C4::Context->dbh;
-
-    my $sth = $dbh->prepare(
-        "UPDATE reserves SET suspend = NOT suspend,
-        suspend_until = CASE WHEN suspend = 0 THEN NULL ELSE $do_until END
-        WHERE reserve_id = ?
-    ");
-
-    my @params;
-    push( @params, $suspend_until ) if ( $suspend_until );
-    push( @params, $reserve_id );
-
-    $sth->execute( @params );
+    if ( $hold->is_suspended ) {
+        $hold->resume()
+    } else {
+        $hold->suspend_hold( $suspend_until );
+    }
 }
 
 =head2 SuspendAll
@@ -1721,37 +1400,26 @@ sub SuspendAll {
     my $borrowernumber = $params{'borrowernumber'} || undef;
     my $biblionumber   = $params{'biblionumber'}   || undef;
     my $suspend_until  = $params{'suspend_until'}  || undef;
-    my $suspend        = defined( $params{'suspend'} ) ? $params{'suspend'} :  1;
+    my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
 
-    $suspend_until = C4::Dates->new( $suspend_until )->output("iso") if ( defined( $suspend_until ) );
+    $suspend_until = eval { dt_from_string($suspend_until) }
+      if ( defined($suspend_until) );
 
     return unless ( $borrowernumber || $biblionumber );
 
-    my ( $query, $sth, $dbh, @query_params );
+    my $params;
+    $params->{found}          = undef;
+    $params->{borrowernumber} = $borrowernumber if $borrowernumber;
+    $params->{biblionumber}   = $biblionumber if $biblionumber;
 
-    $query = "UPDATE reserves SET suspend = ? ";
-    push( @query_params, $suspend );
-    if ( !$suspend ) {
-        $query .= ", suspend_until = NULL ";
-    } elsif ( $suspend_until ) {
-        $query .= ", suspend_until = ? ";
-        push( @query_params, $suspend_until );
-    }
-    $query .= " WHERE ";
-    if ( $borrowernumber ) {
-        $query .= " borrowernumber = ? ";
-        push( @query_params, $borrowernumber );
+    my @holds = Koha::Holds->search($params);
+
+    if ($suspend) {
+        map { $_->suspend_hold($suspend_until) } @holds;
     }
-    $query .= " AND " if ( $borrowernumber && $biblionumber );
-    if ( $biblionumber ) {
-        $query .= " biblionumber = ? ";
-        push( @query_params, $biblionumber );
+    else {
+        map { $_->resume() } @holds;
     }
-    $query .= " AND found IS NULL ";
-
-    $dbh = C4::Context->dbh;
-    $sth = $dbh->prepare( $query );
-    $sth->execute( @query_params );
 }
 
 
@@ -1823,7 +1491,7 @@ sub _FixPriority {
 
     # get whats left
     my $query = "
-        SELECT reserve_id, borrowernumber, reservedate, constrainttype
+        SELECT reserve_id, borrowernumber, reservedate
         FROM   reserves
         WHERE  biblionumber   = ?
           AND  ((found <> 'W' AND found <> 'T') OR found IS NULL)
@@ -1866,7 +1534,7 @@ sub _FixPriority {
             $priority[$j]->{'reserve_id'}
         );
     }
-    
+
     $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
     $sth->execute();
 
@@ -1885,13 +1553,10 @@ sub _FixPriority {
 
   @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
 
-Looks for an item-specific match first, then for a title-level match, returning the
-first match found.  If neither, then we look for a 3rd kind of match based on
-reserve constraints.
+Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
+first match found.  If neither, then we look for non-holds-queue based holds.
 Lookahead is the number of days to look in advance.
 
-TODO: add more explanation about reserve constraints
-
 C<&_Findgroupreserve> returns :
 C<@results> is an array of references-to-hash whose keys are mostly
 fields from the reserves table of the Koha database, plus
@@ -1904,7 +1569,7 @@ sub _Findgroupreserve {
     my $dbh   = C4::Context->dbh;
 
     # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
-    # check for exact targetted match
+    # check for exact targeted match
     my $item_level_target_query = qq{
         SELECT reserves.biblionumber        AS biblionumber,
                reserves.borrowernumber      AS borrowernumber,
@@ -1917,7 +1582,8 @@ sub _Findgroupreserve {
                reserves.timestamp           AS timestamp,
                biblioitems.biblioitemnumber AS biblioitemnumber,
                reserves.itemnumber          AS itemnumber,
-               reserves.reserve_id          AS reserve_id
+               reserves.reserve_id          AS reserve_id,
+               reserves.itemtype            AS itemtype
         FROM reserves
         JOIN biblioitems USING (biblionumber)
         JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
@@ -1938,7 +1604,7 @@ sub _Findgroupreserve {
     }
     return @results if @results;
 
-    # check for title-level targetted match
+    # check for title-level targeted match
     my $title_level_target_query = qq{
         SELECT reserves.biblionumber        AS biblionumber,
                reserves.borrowernumber      AS borrowernumber,
@@ -1951,7 +1617,8 @@ sub _Findgroupreserve {
                reserves.timestamp           AS timestamp,
                biblioitems.biblioitemnumber AS biblioitemnumber,
                reserves.itemnumber          AS itemnumber,
-               reserves.reserve_id          AS reserve_id
+               reserves.reserve_id          AS reserve_id,
+               reserves.itemtype            AS itemtype
         FROM reserves
         JOIN biblioitems USING (biblionumber)
         JOIN hold_fill_targets USING (biblionumber, borrowernumber)
@@ -1983,23 +1650,18 @@ sub _Findgroupreserve {
                reserves.reservenotes               AS reservenotes,
                reserves.priority                   AS priority,
                reserves.timestamp                  AS timestamp,
-               reserveconstraints.biblioitemnumber AS biblioitemnumber,
                reserves.itemnumber                 AS itemnumber,
-               reserves.reserve_id                 AS reserve_id
+               reserves.reserve_id                 AS reserve_id,
+               reserves.itemtype                   AS itemtype
         FROM reserves
-          LEFT JOIN reserveconstraints ON reserves.biblionumber = reserveconstraints.biblionumber
         WHERE reserves.biblionumber = ?
-          AND ( ( reserveconstraints.biblioitemnumber = ?
-          AND reserves.borrowernumber = reserveconstraints.borrowernumber
-          AND reserves.reservedate    = reserveconstraints.reservedate )
-          OR  reserves.constrainttype='a' )
           AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
           AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
           AND suspend = 0
           ORDER BY priority
     };
     $sth = $dbh->prepare($query);
-    $sth->execute( $biblio, $bibitem, $itemnumber, $lookahead||0);
+    $sth->execute( $biblio, $itemnumber, $lookahead||0);
     @results = ();
     while ( my $data = $sth->fetchrow_hashref ) {
         push( @results, $data )
@@ -2010,18 +1672,38 @@ sub _Findgroupreserve {
 
 =head2 _koha_notify_reserve
 
-  _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber );
+  _koha_notify_reserve( $hold->reserve_id );
 
 Sends a notification to the patron that their hold has been filled (through
 ModReserveAffect, _not_ ModReserveFill)
 
+The letter code for this notice may be found using the following query:
+
+    select distinct letter_code
+    from message_transports
+    inner join message_attributes using (message_attribute_id)
+    where message_name = 'Hold_Filled'
+
+This will probably sipmly be 'HOLD', but because it is defined in the database,
+it is subject to addition or change.
+
+The following tables are availalbe witin the notice:
+
+    branches
+    borrowers
+    biblio
+    biblioitems
+    reserves
+    items
+
 =cut
 
 sub _koha_notify_reserve {
-    my ($itemnumber, $borrowernumber, $biblionumber) = @_;
+    my $reserve_id = shift;
+    my $hold = Koha::Holds->find($reserve_id);
+    my $borrowernumber = $hold->borrowernumber;
 
-    my $dbh = C4::Context->dbh;
-    my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
+    my $patron = Koha::Patrons->find( $borrowernumber );
 
     # Try to get the borrower's email address
     my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
@@ -2031,29 +1713,22 @@ sub _koha_notify_reserve {
             message_name => 'Hold_Filled'
     } );
 
-    my $sth = $dbh->prepare("
-        SELECT *
-        FROM   reserves
-        WHERE  borrowernumber = ?
-            AND biblionumber = ?
-    ");
-    $sth->execute( $borrowernumber, $biblionumber );
-    my $reserve = $sth->fetchrow_hashref;
-    my $branch_details = GetBranchDetail( $reserve->{'branchcode'} );
+    my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
 
-    my $admin_email_address = $branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
+    my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
 
     my %letter_params = (
         module => 'reserves',
-        branchcode => $reserve->{branchcode},
+        branchcode => $hold->branchcode,
+        lang => $patron->lang,
         tables => {
-            'branches'  => $branch_details,
-            'borrowers' => $borrower,
-            'biblio'    => $biblionumber,
-            'reserves'  => $reserve,
-            'items', $reserve->{'itemnumber'},
+            'branches'       => $library,
+            'borrowers'      => $patron->unblessed,
+            'biblio'         => $hold->biblionumber,
+            'biblioitems'    => $hold->biblionumber,
+            'reserves'       => $hold->unblessed,
+            'items'          => $hold->itemnumber,
         },
-        substitute => { today => C4::Dates->new()->output() },
     );
 
     my $notification_sent = 0; #Keeping track if a Hold_filled message is sent. If no message can be sent, then default to a print message.
@@ -2079,7 +1754,7 @@ sub _koha_notify_reserve {
     while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
         next if (
                ( $mtt eq 'email' and not $to_address ) # No email address
-            or ( $mtt eq 'sms'   and not $borrower->{smsalertnumber} ) # No SMS number
+            or ( $mtt eq 'sms'   and not $patron->smsalertnumber ) # No SMS number
             or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
         );
 
@@ -2090,7 +1765,7 @@ sub _koha_notify_reserve {
     if (! $notification_sent) {
         &$send_notification('print', 'HOLD');
     }
-    
+
 }
 
 =head2 _ShiftPriorityByDateAndPriority
@@ -2158,7 +1833,7 @@ sub OPACItemHoldsAllowed {
     my $itype;
     my $dbh = C4::Context->dbh;
     if (C4::Context->preference('item-level_itypes')) {
-       # We cant trust GetItem to honour the syspref, so safest to do it ourselves
+       # We can't trust GetItem to honour the syspref, so safest to do it ourselves
        # When GetItem is fixed, we can remove this
        $itype = $item->{itype};
     }
@@ -2202,11 +1877,11 @@ If $cancelreserve boolean is set to true, it will remove existing reserve
 sub MoveReserve {
     my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
 
-    my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber );
+    my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
+    my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
     return unless $res;
 
     my $biblionumber     =  $res->{biblionumber};
-    my $biblioitemnumber = $res->{biblioitemnumber};
 
     if ($res->{borrowernumber} == $borrowernumber) {
         ModReserveFill($res);
@@ -2234,11 +1909,7 @@ sub MoveReserve {
             RevertWaitingStatus({ itemnumber => $itemnumber });
         }
         elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
-            CancelReserve({
-                biblionumber   => $res->{'biblionumber'},
-                itemnumber     => $res->{'itemnumber'},
-                borrowernumber => $res->{'borrowernumber'}
-            });
+            CancelReserve( { reserve_id => $res->{'reserve_id'} } );
         }
     }
 }
@@ -2272,7 +1943,7 @@ sub MergeHolds {
         );
         my $upd_sth = $dbh->prepare(
 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
-        AND reservedate = ? AND constrainttype = ? AND (itemnumber = ? or itemnumber is NULL) "
+        AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
         );
         $sth->execute( $to_biblio, 'W', 'T' );
         my $priority = 1;
@@ -2280,7 +1951,7 @@ sub MergeHolds {
             $upd_sth->execute(
                 $priority,                    $to_biblio,
                 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
-                $reserve->{'constrainttype'}, $reserve->{'itemnumber'}
+                $reserve->{'itemnumber'}
             );
             $priority++;
         }
@@ -2361,33 +2032,32 @@ sub GetReserveId {
 
     return unless ( ( $params->{'biblionumber'} || $params->{'itemnumber'} ) && $params->{'borrowernumber'} );
 
-    my $dbh = C4::Context->dbh();
-
-    my $sql = "SELECT reserve_id FROM reserves WHERE ";
-
-    my @params;
-    my @limits;
     foreach my $key ( keys %$params ) {
-        if ( defined( $params->{$key} ) ) {
-            push( @limits, "$key = ?" );
-            push( @params, $params->{$key} );
-        }
+        delete $params->{$key} unless defined( $params->{$key} );
     }
 
-    $sql .= join( " AND ", @limits );
+    my $hold = Koha::Holds->search( $params )->next();
 
-    my $sth = $dbh->prepare( $sql );
-    $sth->execute( @params );
-    my $row = $sth->fetchrow_hashref();
+    return unless $hold;
 
-    return $row->{'reserve_id'};
+    return $hold->id();
 }
 
 =head2 ReserveSlip
 
   ReserveSlip($branchcode, $borrowernumber, $biblionumber)
 
-  Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
+Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
+
+The letter code will be HOLD_SLIP, and the following tables are
+available within the slip:
+
+    reserves
+    branches
+    borrowers
+    biblio
+    biblioitems
+    items
 
 =cut
 
@@ -2395,22 +2065,26 @@ sub ReserveSlip {
     my ($branch, $borrowernumber, $biblionumber) = @_;
 
 #   return unless ( C4::Context->boolean_preference('printreserveslips') );
+    my $patron = Koha::Patrons->find( $borrowernumber );
 
     my $reserve_id = GetReserveId({
         biblionumber => $biblionumber,
         borrowernumber => $borrowernumber
     }) or return;
-    my $reserve = GetReserveInfo($reserve_id) or return;
+    my $reserve = Koha::Holds->find($reserve_id) or return;
+    $reserve = $reserve->unblessed;
 
     return  C4::Letters::GetPreparedLetter (
         module => 'circulation',
-        letter_code => 'RESERVESLIP',
+        letter_code => 'HOLD_SLIP',
         branchcode => $branch,
+        lang => $patron->lang,
         tables => {
             'reserves'    => $reserve,
             'branches'    => $reserve->{branchcode},
             'borrowers'   => $reserve->{borrowernumber},
             'biblio'      => $reserve->{biblionumber},
+            'biblioitems' => $reserve->{biblionumber},
             'items'       => $reserve->{itemnumber},
         },
     );
@@ -2511,6 +2185,76 @@ sub IsItemOnHoldAndFound {
     return $found;
 }
 
+=head2 GetMaxPatronHoldsForRecord
+
+my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
+
+For multiple holds on a given record for a given patron, the max
+number of record level holds that a patron can be placed is the highest
+value of the holds_per_record rule for each item if the record for that
+patron. This subroutine finds and returns the highest holds_per_record
+rule value for a given patron id and record id.
+
+=cut
+
+sub GetMaxPatronHoldsForRecord {
+    my ( $borrowernumber, $biblionumber ) = @_;
+
+    my $patron = Koha::Patrons->find($borrowernumber);
+    my @items = Koha::Items->search( { biblionumber => $biblionumber } );
+
+    my $controlbranch = C4::Context->preference('ReservesControlBranch');
+
+    my $categorycode = $patron->categorycode;
+    my $branchcode;
+    $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
+
+    my $max = 0;
+    foreach my $item (@items) {
+        my $itemtype = $item->effective_itemtype();
+
+        $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
+
+        my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
+        my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
+        $max = $holds_per_record if $holds_per_record > $max;
+    }
+
+    return $max;
+}
+
+=head2 GetHoldRule
+
+my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
+
+Returns the matching hold related issuingrule fields for a given
+patron category, itemtype, and library.
+
+=cut
+
+sub GetHoldRule {
+    my ( $categorycode, $itemtype, $branchcode ) = @_;
+
+    my $dbh = C4::Context->dbh;
+
+    my $sth = $dbh->prepare(
+        q{
+         SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record
+           FROM issuingrules
+          WHERE (categorycode in (?,'*') )
+            AND (itemtype IN (?,'*'))
+            AND (branchcode IN (?,'*'))
+       ORDER BY categorycode DESC,
+                itemtype     DESC,
+                branchcode   DESC
+        }
+    );
+
+    $sth->execute( $categorycode, $itemtype, $branchcode );
+
+    return $sth->fetchrow_hashref();
+}
+
 =head1 AUTHOR
 
 Koha Development Team <http://koha-community.org/>