Bug 25444: Simplify the code using a loop
[koha-ffzg.git] / C4 / Reserves.pm
index 216ecec..d328773 100644 (file)
@@ -21,37 +21,34 @@ package C4::Reserves;
 # along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 
-use strict;
-#use warnings; FIXME - Bug 2505
-use C4::Context;
+use Modern::Perl;
+
+use C4::Accounts;
 use C4::Biblio;
-use C4::Members;
-use C4::Items;
 use C4::Circulation;
-use C4::Accounts;
-
-# for _koha_notify_reserve
-use C4::Members::Messaging;
-use C4::Members qw();
+use C4::Context;
+use C4::Items;
 use C4::Letters;
 use C4::Log;
-
+use C4::Members::Messaging;
+use C4::Members;
+use Koha::Account::Lines;
 use Koha::Biblios;
-use Koha::DateUtils;
 use Koha::Calendar;
+use Koha::CirculationRules;
 use Koha::Database;
+use Koha::DateUtils;
 use Koha::Hold;
-use Koha::Old::Hold;
 use Koha::Holds;
-use Koha::Libraries;
-use Koha::IssuingRules;
-use Koha::Items;
 use Koha::ItemTypes;
+use Koha::Items;
+use Koha::Libraries;
+use Koha::Old::Hold;
 use Koha::Patrons;
 
-use List::MoreUtils qw( firstidx any );
 use Carp;
 use Data::Dumper;
+use List::MoreUtils qw( firstidx any );
 
 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
 
@@ -125,6 +122,7 @@ BEGIN {
         &AutoUnsuspendReserves
 
         &IsAvailableForItemLevelRequest
+        ItemsAnyAvailableForHold
 
         &AlterPriority
         &ToggleLowestPriority
@@ -144,7 +142,21 @@ BEGIN {
 
 =head2 AddReserve
 
-    AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
+    AddReserve(
+        {
+            branchcode       => $branchcode,
+            borrowernumber   => $borrowernumber,
+            biblionumber     => $biblionumber,
+            priority         => $priority,
+            reservation_date => $reservation_date,
+            expiration_date  => $expiration_date,
+            notes            => $notes,
+            title            => $title,
+            itemnumber       => $itemnumber,
+            found            => $found,
+            itemtype         => $itemtype,
+        }
+    );
 
 Adds reserve and generates HOLDPLACED message.
 
@@ -160,17 +172,50 @@ The following tables are available witin the HOLDPLACED message:
 =cut
 
 sub AddReserve {
-    my (
-        $branch,   $borrowernumber, $biblionumber, $bibitems,
-        $priority, $resdate,        $expdate,      $notes,
-        $title,    $checkitem,      $found,        $itemtype
-    ) = @_;
+    my ($params)       = @_;
+    my $branch         = $params->{branchcode};
+    my $borrowernumber = $params->{borrowernumber};
+    my $biblionumber   = $params->{biblionumber};
+    my $priority       = $params->{priority};
+    my $resdate        = $params->{reservation_date};
+    my $expdate        = $params->{expiration_date};
+    my $notes          = $params->{notes};
+    my $title          = $params->{title};
+    my $checkitem      = $params->{itemnumber};
+    my $found          = $params->{found};
+    my $itemtype       = $params->{itemtype};
 
     $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 we have an item selectionned, and the pickup branch is the same as the holdingbranch
+    # of the document, we force the value $priority and $found .
+    if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
+        my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
+
+        if (
+            # If item is already checked out, it cannot be set waiting
+            !$item->onloan
+
+            # The item can't be waiting if it needs a transfer
+            && $item->holdingbranch eq $branch
+
+            # Similarly, if in transit it can't be waiting
+            && !$item->get_transfer
+
+            # If we can't hold damaged items, and it is damaged, it can't be waiting
+            && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
+
+            # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
+            && !$item->current_holds->count )
+        {
+            $priority = 0;
+            $found = 'W';
+        }
+    }
+
     if ( C4::Context->preference('AllowHoldDateInFuture') ) {
 
         # Make room in reserves for this before those of a later reserve date
@@ -180,7 +225,7 @@ sub AddReserve {
     my $waitingdate;
 
     # If the reserv had the waiting status, we had the value of the resdate
-    if ( $found eq 'W' ) {
+    if ( $found && $found eq 'W' ) {
         $waitingdate = $resdate;
     }
 
@@ -201,8 +246,10 @@ sub AddReserve {
             waitingdate    => $waitingdate,
             expirationdate => $expdate,
             itemtype       => $itemtype,
+            item_level_hold => $checkitem ? 1 : 0,
         }
     )->store();
+    $hold->set_waiting() if $found && $found eq 'W';
 
     logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
         if C4::Context->preference('HoldsLog');
@@ -236,14 +283,14 @@ sub AddReserve {
             },
         ) ) {
 
-            my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
+            my $branch_email_address = $library->inbound_email_address;
 
             C4::Letters::EnqueueLetter(
-                {   letter                 => $letter,
+                {
+                    letter                 => $letter,
                     borrowernumber         => $borrowernumber,
                     message_transport_type => 'email',
-                    from_address           => $admin_email_address,
-                    to_address           => $admin_email_address,
+                    to_address             => $branch_email_address,
                 }
             );
         }
@@ -254,7 +301,7 @@ sub AddReserve {
 
 =head2 CanBookBeReserved
 
-  $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
+  $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode)
   if ($canReserve eq 'OK') { #We can reserve this Item! }
 
 See CanItemBeReserved() for possible return values.
@@ -262,64 +309,70 @@ See CanItemBeReserved() for possible return values.
 =cut
 
 sub CanBookBeReserved{
-    my ($borrowernumber, $biblionumber) = @_;
+    my ($borrowernumber, $biblionumber, $pickup_branchcode) = @_;
 
-    my $items = GetItemnumbersForBiblio($biblionumber);
+    my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
     #get items linked via host records
     my @hostitems = get_hostitemnumbers_of($biblionumber);
     if (@hostitems){
-    push (@$items,@hostitems);
+        push (@itemnumbers, @hostitems);
     }
 
-    my $canReserve;
-    foreach my $item (@$items) {
-        $canReserve = CanItemBeReserved( $borrowernumber, $item );
-        return 'OK' if $canReserve eq 'OK';
+    my $canReserve = { status => '' };
+    foreach my $itemnumber (@itemnumbers) {
+        $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode );
+        return { status => 'OK' } if $canReserve->{status} eq 'OK';
     }
     return $canReserve;
 }
 
 =head2 CanItemBeReserved
 
-  $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
-  if ($canReserve eq 'OK') { #We can reserve this Item! }
-
-@RETURNS OK,              if the Item can be reserved.
-         ageRestricted,   if the Item is age restricted for this borrower.
-         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
+  $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode)
+  if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
+
+@RETURNS { status => OK },              if the Item can be reserved.
+         { status => ageRestricted },   if the Item is age restricted for this borrower.
+         { status => damaged },         if the Item is damaged.
+         { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
+         { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
+         { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
+         { status => notReservable },   if holds on this item are not allowed
+         { status => libraryNotFound },   if given branchcode is not an existing library
+         { status => libraryNotPickupLocation },   if given branchcode is not configured to be a pickup location
+         { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
+         { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
 
 =cut
 
 sub CanItemBeReserved {
-    my ( $borrowernumber, $itemnumber ) = @_;
+    my ( $borrowernumber, $itemnumber, $pickup_branchcode ) = @_;
 
     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 $holds_per_day;        # Default to unlimited
 
     # we retrieve borrowers and items informations #
     # item->{itype} will come for biblioitems if necessery
-    my $item       = GetItem($itemnumber);
-    my $biblio     = Koha::Biblios->find( $item->{biblionumber} );
+    my $item       = Koha::Items->find($itemnumber);
+    my $biblio     = $item->biblio;
     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}
+    return { status =>'damaged' }
+      if ( $item->damaged
         && !C4::Context->preference('AllowHoldsOnDamagedItems') );
 
     # Check for the age restriction
     my ( $ageRestriction, $daysToAgeRestriction ) =
       C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
-    return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
+    return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
 
     # Check that the patron doesn't have an item level hold on this item already
-    return 'itemAlreadyOnHold'
+    return { status =>'itemAlreadyOnHold' }
       if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
 
     my $controlbranch = C4::Context->preference('ReservesControlBranch');
@@ -338,7 +391,7 @@ sub CanItemBeReserved {
 
     if ( $controlbranch eq "ItemHomeLibrary" ) {
         $branchfield = "items.homebranch";
-        $branchcode  = $item->{homebranch};
+        $branchcode  = $item->homebranch;
     }
     elsif ( $controlbranch eq "PatronLibrary" ) {
         $branchfield = "borrowers.branchcode";
@@ -346,30 +399,41 @@ sub CanItemBeReserved {
     }
 
     # we retrieve rights
-    if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
+    if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
         $ruleitemtype     = $rights->{itemtype};
-        $allowedreserves  = $rights->{reservesallowed};
-        $holds_per_record = $rights->{holds_per_record};
+        $allowedreserves  = $rights->{reservesallowed} // $allowedreserves;
+        $holds_per_record = $rights->{holds_per_record} // $holds_per_record;
+        $holds_per_day    = $rights->{holds_per_day};
     }
     else {
-        $ruleitemtype = '*';
+        $ruleitemtype = undef;
     }
 
-    $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";
+    if (   defined $holds_per_record && $holds_per_record ne ''
+        && $holds->count() >= $holds_per_record ) {
+        return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
+    }
+
+    my $today_holds = Koha::Holds->search({
+        borrowernumber => $borrowernumber,
+        reservedate    => dt_from_string->date
+    });
+
+    if (   defined $holds_per_day && $holds_per_day ne ''
+        && $today_holds->count() >= $holds_per_day )
+    {
+        return { status => 'tooManyReservesToday', limit => $holds_per_day };
     }
 
     # we retrieve count
 
-    $querycount .= "AND $branchfield = ?";
+    $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
 
     # If using item-level itypes, fall back to the record
     # level itemtype if the hold has no associated item
@@ -377,15 +441,15 @@ sub CanItemBeReserved {
       C4::Context->preference('item-level_itypes')
       ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
       : " AND biblioitems.itemtype = ?"
-      if ( $ruleitemtype ne "*" );
+      if defined $ruleitemtype;
 
     my $sthcount = $dbh->prepare($querycount);
 
-    if ( $ruleitemtype eq "*" ) {
-        $sthcount->execute( $borrowernumber, $branchcode );
+    if ( defined $ruleitemtype ) {
+        $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
     }
     else {
-        $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
+        $sthcount->execute( $borrowernumber, $branchcode );
     }
 
     my $reservecount = "0";
@@ -394,23 +458,49 @@ sub CanItemBeReserved {
     }
 
     # we check if it's ok or not
-    if ( $reservecount >= $allowedreserves ) {
-        return 'tooManyReserves';
+    if (   defined  $allowedreserves && $allowedreserves ne ''
+        && $reservecount >= $allowedreserves ) {
+        return { status => 'tooManyReserves', limit => $allowedreserves };
+    }
+
+    # Now we need to check hold limits by patron category
+    my $rule = Koha::CirculationRules->get_effective_rule(
+        {
+            categorycode => $borrower->{categorycode},
+            branchcode   => $branchcode,
+            rule_name    => 'max_holds',
+        }
+    );
+    if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
+        my $total_holds_count = Koha::Holds->search(
+            {
+                borrowernumber => $borrower->{borrowernumber}
+            }
+        )->count();
+
+        return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
     }
 
-    my $circ_control_branch =
-      C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
+    my $reserves_control_branch =
+      GetReservesControlBranch( $item->unblessed(), $borrower );
     my $branchitemrule =
-      C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype );
+      C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
 
     if ( $branchitemrule->{holdallowed} == 0 ) {
-        return 'notReservable';
+        return { status => 'notReservable' };
     }
 
     if (   $branchitemrule->{holdallowed} == 1
         && $borrower->{branchcode} ne $item->homebranch )
     {
-        return 'cannotReserveFromOtherBranches';
+        return { status => 'cannotReserveFromOtherBranches' };
+    }
+
+    my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
+    if ( $branchitemrule->{holdallowed} == 3) {
+        if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
+            return { status => 'branchNotInHoldGroup' };
+        }
     }
 
     # If reservecount is ok, we check item branch if IndependentBranches is ON
@@ -418,13 +508,34 @@ sub CanItemBeReserved {
     if ( C4::Context->preference('IndependentBranches')
         and !C4::Context->preference('canreservefromotherbranches') )
     {
-        my $itembranch = $item->homebranch;
-        if ( $itembranch ne $borrower->{branchcode} ) {
-            return 'cannotReserveFromOtherBranches';
+        if ( $item->homebranch ne $borrower->{branchcode} ) {
+            return { status => 'cannotReserveFromOtherBranches' };
+        }
+    }
+
+    if ($pickup_branchcode) {
+        my $destination = Koha::Libraries->find({
+            branchcode => $pickup_branchcode,
+        });
+
+        unless ($destination) {
+            return { status => 'libraryNotFound' };
+        }
+        unless ($destination->pickup_location) {
+            return { status => 'libraryNotPickupLocation' };
+        }
+        unless ($item->can_be_transferred({ to => $destination })) {
+            return { status => 'cannotBeTransferred' };
+        }
+        unless ($branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
+            return { status => 'pickupNotInHoldGroup' };
+        }
+        unless ($branchitemrule->{hold_fulfillment_policy} ne 'patrongroup' || Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
+            return { status => 'pickupNotInHoldGroup' };
         }
     }
 
-    return 'OK';
+    return { status => 'OK' };
 }
 
 =head2 CanReserveBeCanceledFromOpac
@@ -464,8 +575,8 @@ sub GetOtherReserves {
     my $nextreservinfo;
     my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
     if ($checkreserves) {
-        my $iteminfo = GetItem($itemnumber);
-        if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
+        my $item = Koha::Items->find($itemnumber);
+        if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
             $messages->{'transfert'} = $checkreserves->{'branchcode'};
             #minus priorities of others reservs
             ModReserveMinusPriority(
@@ -476,8 +587,9 @@ sub GetOtherReserves {
             #launch the subroutine dotransfer
             C4::Items::ModItemTransfer(
                 $itemnumber,
-                $iteminfo->{'holdingbranch'},
-                $checkreserves->{'branchcode'}
+                $item->holdingbranch,
+                $checkreserves->{'branchcode'},
+                'Reserve'
               ),
               ;
         }
@@ -492,7 +604,7 @@ sub GetOtherReserves {
             ModReserveStatus($itemnumber,'W');
         }
 
-        $nextreservinfo = $checkreserves->{'borrowernumber'};
+        $nextreservinfo = $checkreserves;
     }
 
     return ( $messages, $nextreservinfo );
@@ -508,13 +620,20 @@ sub GetOtherReserves {
 
 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 $dbh = C4::Context->dbh;
-    my $nextacctno = &getnextacctno( $borrowernumber );
-    $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
+    return if !$fee || $fee == 0;    # the last test is needed to include 0.00
+    Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
+        {
+            amount       => $fee,
+            description  => $title,
+            note         => undef,
+            user_id      => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
+            library_id   => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
+            interface    => C4::Context->interface,
+            invoice_type => undef,
+            type         => 'RESERVE',
+            item_id      => undef
+        }
+    );
 }
 
 =head2 GetReserveFee
@@ -589,16 +708,16 @@ sub GetReserveStatus {
         return 'Finished' if $found eq 'F';
     }
 
-    return 'Reserved' if $priority > 0;
+    return 'Reserved' if defined $priority && $priority > 0;
 
     return ''; # empty string here will remove need for checking undef, or less log lines
 }
 
 =head2 CheckReserves
 
-  ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
-  ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
-  ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
+  ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
+  ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
+  ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
 
 Find a book in the reserves.
 
@@ -669,14 +788,14 @@ sub CheckReserves {
     }
     # note: we get the itemnumber because we might have started w/ just the barcode.  Now we know for sure we have it.
     my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
-
     return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
 
     return unless $itemnumber; # bail if we got nothing.
-
     # if item is not for loan it cannot be reserved either.....
     # except where items.notforloan < 0 :  This indicates the item is holdable.
-    return if  ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
+
+    my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
+    return if $dont_trap or $notforloan_per_itemtype;
 
     # Find this item in the reserves
     my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
@@ -686,6 +805,7 @@ sub CheckReserves {
     # the more important the item.)
     # $highest is the most important item we've seen so far.
     my $highest;
+
     if (scalar @reserves) {
         my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
         my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
@@ -693,7 +813,7 @@ sub CheckReserves {
 
         my $priority = 10000000;
         foreach my $res (@reserves) {
-            if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
+            if ( $res->{'itemnumber'} && $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
                 if ($res->{'found'} eq 'W') {
                     return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
                 } else {
@@ -701,15 +821,15 @@ sub CheckReserves {
                 }
             } else {
                 my $patron;
-                my $iteminfo;
+                my $item;
                 my $local_hold_match;
 
                 if ($LocalHoldsPriority) {
                     $patron = Koha::Patrons->find( $res->{borrowernumber} );
-                    $iteminfo = C4::Items::GetItem($itemnumber);
+                    $item = Koha::Items->find($itemnumber);
 
                     my $local_holds_priority_item_branchcode =
-                      $iteminfo->{$LocalHoldsPriorityItemControl};
+                      $item->$LocalHoldsPriorityItemControl;
                     my $local_holds_priority_patron_branchcode =
                       ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
                       ? $res->{branchcode}
@@ -723,14 +843,20 @@ 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 ) {
-                    $iteminfo ||= C4::Items::GetItem($itemnumber);
-                    next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
+                    $item ||= Koha::Items->find($itemnumber);
+                    next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
                     $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
-                    my $branch = GetReservesControlBranch( $iteminfo, $patron->unblessed );
-                    my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
+                    my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
+                    my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
                     next if ($branchitemrule->{'holdallowed'} == 0);
                     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} }) );
+                    my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
+                    next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
+                    my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
+                    next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
+                    next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
+                    next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
+                    next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
                     $priority = $res->{'priority'};
                     $highest  = $res;
                     last if $local_hold_match;
@@ -764,7 +890,7 @@ sub CancelExpiredReserves {
 
     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
     my $params = { expirationdate => { '<', $dtf->format_date($today) } };
-    $params->{found} = undef unless $expireWaiting;
+    $params->{found} = [ { '!=', 'W' }, undef ]  unless $expireWaiting;
 
     # FIXME To move to Koha::Holds->search_expired (?)
     my $holds = Koha::Holds->search( $params );
@@ -793,9 +919,9 @@ Unsuspends all suspended reserves with a suspend_until date from before today.
 sub AutoUnsuspendReserves {
     my $today = dt_from_string();
 
-    my @holds = Koha::Holds->search( { suspend_until => { '<' => $today->ymd() } } );
+    my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
 
-    map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
+    map { $_->resume() } @holds;
 }
 
 =head2 ModReserve
@@ -867,15 +993,21 @@ sub ModReserve {
         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();
+        my $properties = {
+            priority    => $rank,
+            branchcode  => $branchcode,
+            itemnumber  => $itemnumber,
+            found       => undef,
+            waitingdate => undef
+        };
+        if (exists $params->{reservedate}) {
+            $properties->{reservedate} = $params->{reservedate} || undef;
+        }
+        if (exists $params->{expirationdate}) {
+            $properties->{expirationdate} = $params->{expirationdate} || undef;
+        }
+
+        $hold->set($properties)->store();
 
         if ( defined( $suspend_until ) ) {
             if ( $suspend_until ) {
@@ -909,7 +1041,6 @@ sub ModReserveFill {
     my $reserve_id = $res->{'reserve_id'};
 
     my $hold = Koha::Holds->find($reserve_id);
-
     # get the priority on this record....
     my $priority = $hold->priority;
 
@@ -921,6 +1052,9 @@ sub ModReserveFill {
         }
     );
 
+    logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
+        if C4::Context->preference('HoldsLog');
+
     # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
     Koha::Old::Hold->new( $hold->unblessed() )->store();
 
@@ -960,7 +1094,10 @@ sub ModReserveStatus {
     my $sth_set = $dbh->prepare($query);
     $sth_set->execute( $newstatus, $itemnumber );
 
-    if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
+    my $item = Koha::Items->find($itemnumber);
+    if ( $item->location && $item->location eq 'CART'
+        && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
+        && $newstatus ) {
       CartToShelf( $itemnumber );
     }
 }
@@ -1008,15 +1145,28 @@ sub ModReserveAffect {
     $hold->itemnumber($itemnumber);
     $hold->set_waiting($transferToDo);
 
-    _koha_notify_reserve( $hold->reserve_id )
-      if ( !$transferToDo && !$already_on_shelf );
+    if( !$transferToDo ){
+        _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
+        my $transfers = Koha::Item::Transfers->search({
+            itemnumber => $itemnumber,
+            datearrived => undef
+        });
+        while( my $transfer = $transfers->next ){
+            $transfer->datearrived( dt_from_string() )->store;
+        };
+    }
 
-    _FixPriority( { biblionumber => $biblionumber } );
 
-    if ( C4::Context->preference("ReturnToShelvingCart") ) {
-        CartToShelf($itemnumber);
+    _FixPriority( { biblionumber => $biblionumber } );
+    my $item = Koha::Items->find($itemnumber);
+    if ( $item->location && $item->location eq 'CART'
+        && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
+      CartToShelf( $itemnumber );
     }
 
+    logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
+        if C4::Context->preference('HoldsLog');
+
     return;
 }
 
@@ -1041,7 +1191,7 @@ sub ModReserveCancelAll {
     #step 2 launch the subroutine of the others reserves
     ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
 
-    return ( $messages, $nextreservinfo );
+    return ( $messages, $nextreservinfo->{borrowernumber} );
 }
 
 =head2 ModReserveMinusPriority
@@ -1070,7 +1220,7 @@ sub ModReserveMinusPriority {
 
 =head2 IsAvailableForItemLevelRequest
 
-  my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
+  my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
 
 Checks whether a given item record is available for an
 item-level hold request.  An item is available if
@@ -1078,6 +1228,7 @@ item-level hold request.  An item is available if
 * it is not lost AND
 * it is not damaged AND
 * it is not withdrawn AND
+* a waiting or in transit reserve is placed on
 * does not have a not for loan value > 0
 
 Need to check the issuingrules onshelfholds column,
@@ -1092,112 +1243,102 @@ and canreservefromotherbranches.
 =cut
 
 sub IsAvailableForItemLevelRequest {
-    my $item = shift;
-    my $borrower = shift;
+    my $item                = shift;
+    my $patron              = shift;
+    my $pickup_branchcode   = shift;
+    # items_any_available is precalculated status passed from request.pl when set of items
+    # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
+    my $items_any_available = shift;
 
     my $dbh = C4::Context->dbh;
     # must check the notforloan setting of the itemtype
     # FIXME - a lot of places in the code do this
     #         or something similar - need to be
     #         consolidated
-    my $itype = _get_itype($item);
-    my $notforloan_per_itemtype
-      = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
-                              undef, $itype);
+    my $itemtype = $item->effective_itemtype;
+    my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
 
     return 0 if
         $notforloan_per_itemtype ||
-        $item->{itemlost}        ||
-        $item->{notforloan} > 0  ||
-        $item->{withdrawn}        ||
-        ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
-
-    my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
+        $item->itemlost        ||
+        $item->notforloan > 0  ||
+        $item->withdrawn        ||
+        ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
+
+    if ($pickup_branchcode) {
+        my $destination = Koha::Libraries->find($pickup_branchcode);
+        return 0 unless $destination;
+        return 0 unless $destination->pickup_location;
+        return 0 unless $item->can_be_transferred( { to => $destination } );
+        my $reserves_control_branch =
+            GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
+        my $branchitemrule =
+            C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
+        my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
+        return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
+    }
+
+    my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
 
     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) {
-
-            my $circ_control_branch = C4::Circulation::_GetCircControlBranch( $i->unblessed(), $borrower );
-            my $branchitemrule = C4::Circulation::GetBranchItemRule( $circ_control_branch, $i->itype );
-
-            $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
-              || $branchitemrule->{holdallowed} == 1 && $borrower->{branchcode} ne $i->homebranch;
-        }
 
+        # if we have this param predefined from outer caller sub, we just need
+        # to return it, so we saving from having loop inside other loop:
+        return  $items_any_available ? 0 : 1
+            if defined $items_any_available;
+
+        my $any_available = ItemsAnyAvailableForHold( { biblionumber => $item->biblionumber, patron => $patron });
         return $any_available ? 0 : 1;
+    } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
+        return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
     }
-
-    return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
 }
 
-=head2 OnShelfHoldsAllowed
+=head2 ItemsAnyAvailableForHold
 
-  OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
+  ItemsAnyAvailableForHold( { biblionumber => $biblionumber, patron => $patron });
 
-Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
-holds are allowed, returns true if so.
+This function checks all items for specified biblionumber (num) / patron (object)
+and returns true (1) or false (0) depending if any of rules allows at least of
+one item to be available for hold including lots of parameters/logic
 
 =cut
 
-sub OnShelfHoldsAllowed {
-    my ($item, $borrower) = @_;
+sub ItemsAnyAvailableForHold {
+    my $param = shift;
 
-    my $itype = _get_itype($item);
-    return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
-}
+    my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
 
-sub _get_itype {
-    my $item = shift;
+    my $any_available = 0;
 
-    my $itype;
-    if (C4::Context->preference('item-level_itypes')) {
-        # 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};
-    }
-    else {
-        # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
-        # So if we already have a biblioitems join when calling this function,
-        # we don't need to access the database again
-        $itype = $item->{itemtype};
-    }
-    unless ($itype) {
-        my $dbh = C4::Context->dbh;
-        my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
-        my $sth = $dbh->prepare($query);
-        $sth->execute($item->{biblioitemnumber});
-        if (my $data = $sth->fetchrow_hashref()){
-            $itype = $data->{itemtype};
-        }
-    }
-    return $itype;
-}
+    foreach my $i (@items) {
+        my $reserves_control_branch =
+            GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
+        my $branchitemrule =
+            C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
+        my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
 
-sub _OnShelfHoldsAllowed {
-    my ($itype,$borrowercategory,$branchcode) = @_;
+        $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
+            || $branchitemrule->{holdallowed} == 1 && $param->{patron}->branchcode ne $i->homebranch
+            || $branchitemrule->{holdallowed} == 3 && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } );
+    }
 
-    my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
-    return $issuing_rule ? $issuing_rule->onshelfholds : undef;
+    return $any_available;
 }
 
 =head2 AlterPriority
 
-  AlterPriority( $where, $reserve_id );
+  AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
 
 This function changes a reserve's priority up, down, to the top, or to the bottom.
 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
@@ -1205,7 +1346,7 @@ Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was
 =cut
 
 sub AlterPriority {
-    my ( $where, $reserve_id ) = @_;
+    my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
 
     my $hold = Koha::Holds->find( $reserve_id );
     return unless $hold;
@@ -1215,21 +1356,18 @@ sub AlterPriority {
         return;
     }
 
-    if ( $where eq 'up' || $where eq 'down' ) {
-
-      my $priority = $hold->priority;
-      $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
-      _FixPriority({ reserve_id => $reserve_id, rank => $priority })
-
+    if ( $where eq 'up' ) {
+      return unless $prev_priority;
+      _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
+    } elsif ( $where eq 'down' ) {
+      return unless $next_priority;
+      _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
     } elsif ( $where eq 'top' ) {
-
-      _FixPriority({ reserve_id => $reserve_id, rank => '1' })
-
+      _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
     } elsif ( $where eq 'bottom' ) {
-
-      _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
-
+      _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
     }
+
     # FIXME Should return the new priority
 }
 
@@ -1368,6 +1506,10 @@ sub _FixPriority {
     my $hold;
     if ( $reserve_id ) {
         $hold = Koha::Holds->find( $reserve_id );
+        if (!defined $hold){
+            # may have already been checked out and hold fulfilled
+            $hold = Koha::Old::Holds->find( $reserve_id );
+        }
         return unless $hold;
     }
 
@@ -1378,7 +1520,7 @@ sub _FixPriority {
     if ( $rank eq "del" ) { # FIXME will crash if called without $hold
         $hold->cancel;
     }
-    elsif ( $rank eq "W" || $rank eq "0" ) {
+    elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
 
         # make sure priority for waiting or in-transit items is 0
         my $query = "
@@ -1406,11 +1548,12 @@ sub _FixPriority {
         push( @priority,     $line );
     }
 
+    # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
     # To find the matching index
     my $i;
     my $key = -1;    # to allow for 0 to be a valid result
     for ( $i = 0 ; $i < @priority ; $i++ ) {
-        if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
+        if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
             $key = $i;    # save the index
             last;
         }
@@ -1465,6 +1608,13 @@ C<@results> is an array of references-to-hash whose keys are mostly
 fields from the reserves table of the Koha database, plus
 C<biblioitemnumber>.
 
+This routine with either return:
+1 - Item specific holds from the holds queue
+2 - Title level holds from the holds queue
+3 - All holds for this biblionumber
+
+All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
+
 =cut
 
 sub _Findgroupreserve {
@@ -1732,8 +1882,10 @@ If $cancelreserve boolean is set to true, it will remove existing reserve
 sub MoveReserve {
     my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
 
+    $cancelreserve //= 0;
+
     my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
-    my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
+    my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
     return unless $res;
 
     my $biblionumber     =  $res->{biblionumber};
@@ -1746,18 +1898,16 @@ sub MoveReserve {
         # The item is reserved by someone else.
         # Find this item in the reserves
 
-        my $borr_res;
-        foreach (@$all_reserves) {
-            $_->{'borrowernumber'} == $borrowernumber or next;
-            $_->{'biblionumber'}   == $biblionumber   or next;
-
-            $borr_res = $_;
-            last;
-        }
+        my $borr_res  = Koha::Holds->search({
+            borrowernumber => $borrowernumber,
+            biblionumber   => $biblionumber,
+        },{
+            order_by       => 'priority'
+        })->next();
 
         if ( $borr_res ) {
             # The item is reserved by the current patron
-            ModReserveFill($borr_res);
+            ModReserveFill($borr_res->unblessed);
         }
 
         if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
@@ -1846,6 +1996,8 @@ sub RevertWaitingStatus {
     $sth->execute( $itemnumber );
     my $reserve = $sth->fetchrow_hashref();
 
+    my $hold = Koha::Holds->find( $reserve->{reserve_id} ); # TODO Remove the next raw SQL statements and use this instead
+
     ## Increment the priority of all other non-waiting
     ## reserves for this bib record
     $query = "
@@ -1860,24 +2012,31 @@ sub RevertWaitingStatus {
     $sth = $dbh->prepare( $query );
     $sth->execute( $reserve->{'biblionumber'} );
 
-    ## Fix up the currently waiting reserve
-    $query = "
-    UPDATE reserves
-    SET
-      priority = 1,
-      found = NULL,
-      waitingdate = NULL
-    WHERE
-      reserve_id = ?
-    ";
-    $sth = $dbh->prepare( $query );
-    $sth->execute( $reserve->{'reserve_id'} );
+    $hold->set(
+        {
+            priority    => 1,
+            found       => undef,
+            waitingdate => undef,
+            itemnumber  => $hold->item_level_hold ? $hold->itemnumber : undef,
+        }
+    )->store();
+
     _FixPriority( { biblionumber => $reserve->{biblionumber} } );
+
+    return $hold;
 }
 
 =head2 ReserveSlip
 
-  ReserveSlip($branchcode, $borrowernumber, $biblionumber)
+ReserveSlip(
+    {
+        branchcode     => $branchcode,
+        borrowernumber => $borrowernumber,
+        biblionumber   => $biblionumber,
+        [ itemnumber   => $itemnumber, ]
+        [ barcode      => $barcode, ]
+    }
+  )
 
 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
 
@@ -1894,19 +2053,20 @@ available within the slip:
 =cut
 
 sub ReserveSlip {
-    my ($branch, $borrowernumber, $biblionumber) = @_;
-
-#   return unless ( C4::Context->boolean_preference('printreserveslips') );
-    my $patron = Koha::Patrons->find( $borrowernumber );
+    my ($args) = @_;
+    my $branchcode     = $args->{branchcode};
+    my $reserve_id = $args->{reserve_id};
 
-    my $hold = Koha::Holds->search({biblionumber => $biblionumber, borrowernumber => $borrowernumber })->next;
+    my $hold = Koha::Holds->find($reserve_id);
     return unless $hold;
+
+    my $patron = $hold->borrower;
     my $reserve = $hold->unblessed;
 
     return  C4::Letters::GetPreparedLetter (
         module => 'circulation',
         letter_code => 'HOLD_SLIP',
-        branchcode => $branch,
+        branchcode => $branchcode,
         lang => $patron->lang,
         tables => {
             'reserves'    => $reserve,
@@ -2064,24 +2224,41 @@ patron category, itemtype, and library.
 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
+    my $reservesallowed = Koha::CirculationRules->get_effective_rule(
+        {
+            itemtype     => $itemtype,
+            categorycode => $categorycode,
+            branchcode   => $branchcode,
+            rule_name    => 'reservesallowed',
+            order_by     => {
+                -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
+            }
         }
     );
 
-    $sth->execute( $categorycode, $itemtype, $branchcode );
+    my $rules;
+    if ( $reservesallowed ) {
+        $rules->{reservesallowed} = $reservesallowed->rule_value;
+        $rules->{itemtype}        = $reservesallowed->itemtype;
+        $rules->{categorycode}    = $reservesallowed->categorycode;
+        $rules->{branchcode}      = $reservesallowed->branchcode;
+    }
+
+    my $holds_per_x_rules = Koha::CirculationRules->get_effective_rules(
+        {
+            itemtype     => $itemtype,
+            categorycode => $categorycode,
+            branchcode   => $branchcode,
+            rules        => ['holds_per_record', 'holds_per_day'],
+            order_by     => {
+                -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
+            }
+        }
+    );
+    $rules->{holds_per_record} = $holds_per_x_rules->{holds_per_record};
+    $rules->{holds_per_day} = $holds_per_x_rules->{holds_per_day};
 
-    return $sth->fetchrow_hashref();
+    return $rules;
 }
 
 =head1 AUTHOR