Bug 25444: Simplify the code using a loop
[koha-ffzg.git] / C4 / Reserves.pm
index 00d921d..d328773 100644 (file)
@@ -122,6 +122,7 @@ BEGIN {
         &AutoUnsuspendReserves
 
         &IsAvailableForItemLevelRequest
+        ItemsAnyAvailableForHold
 
         &AlterPriority
         &ToggleLowestPriority
@@ -143,7 +144,7 @@ BEGIN {
 
     AddReserve(
         {
-            branch           => $branchcode,
+            branchcode       => $branchcode,
             borrowernumber   => $borrowernumber,
             biblionumber     => $biblionumber,
             priority         => $priority,
@@ -282,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,
                 }
             );
         }
@@ -587,7 +588,8 @@ sub GetOtherReserves {
             C4::Items::ModItemTransfer(
                 $itemnumber,
                 $item->holdingbranch,
-                $checkreserves->{'branchcode'}
+                $checkreserves->{'branchcode'},
+                'Reserve'
               ),
               ;
         }
@@ -602,7 +604,7 @@ sub GetOtherReserves {
             ModReserveStatus($itemnumber,'W');
         }
 
-        $nextreservinfo = $checkreserves->{'borrowernumber'};
+        $nextreservinfo = $checkreserves;
     }
 
     return ( $messages, $nextreservinfo );
@@ -791,7 +793,9 @@ sub CheckReserves {
     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);
@@ -801,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');
@@ -1047,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();
 
@@ -1137,8 +1145,17 @@ 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 } );
     my $item = Koha::Items->find($itemnumber);
@@ -1147,6 +1164,9 @@ sub ModReserveAffect {
       CartToShelf( $itemnumber );
     }
 
+    logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
+        if C4::Context->preference('HoldsLog');
+
     return;
 }
 
@@ -1171,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
@@ -1223,7 +1243,12 @@ and canreservefromotherbranches.
 =cut
 
 sub IsAvailableForItemLevelRequest {
-    my ( $item, $patron, $pickup_branchcode ) = @_;
+    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
@@ -1240,8 +1265,6 @@ sub IsAvailableForItemLevelRequest {
         $item->withdrawn        ||
         ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
 
-    my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
-
     if ($pickup_branchcode) {
         my $destination = Koha::Libraries->find($pickup_branchcode);
         return 0 unless $destination;
@@ -1255,64 +1278,62 @@ sub IsAvailableForItemLevelRequest {
         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 $reserves_control_branch = GetReservesControlBranch( $i->unblessed(), $patron->unblessed );
-            my $branchitemrule = C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
-            my $item_library = Koha::Libraries->find( {branchcode => $i->homebranch} );
-
-
-            $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 && $patron->branchcode ne $i->homebranch
-              || $branchitemrule->{holdallowed} == 3 && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} );
-        }
 
+        # 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 );
     }
 }
 
-sub _get_itype {
-    my $item = shift;
+=head2 ItemsAnyAvailableForHold
 
-    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;
+  ItemsAnyAvailableForHold( { biblionumber => $biblionumber, patron => $patron });
+
+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 ItemsAnyAvailableForHold {
+    my $param = shift;
+
+    my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
+
+    my $any_available = 0;
+
+    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 } );
+
+        $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 } );
+    }
+
+    return $any_available;
 }
 
 =head2 AlterPriority
@@ -1485,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;
     }
 
@@ -2030,36 +2055,12 @@ available within the slip:
 sub ReserveSlip {
     my ($args) = @_;
     my $branchcode     = $args->{branchcode};
-    my $borrowernumber = $args->{borrowernumber};
-    my $biblionumber   = $args->{biblionumber};
-    my $itemnumber     = $args->{itemnumber};
-    my $barcode        = $args->{barcode};
-
-
-    my $patron = Koha::Patrons->find($borrowernumber);
-
-    my $hold;
-    if ($itemnumber || $barcode ) {
-        $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
-
-        $hold = Koha::Holds->search(
-            {
-                biblionumber   => $biblionumber,
-                borrowernumber => $borrowernumber,
-                itemnumber     => $itemnumber
-            }
-        )->next;
-    }
-    else {
-        $hold = Koha::Holds->search(
-            {
-                biblionumber   => $biblionumber,
-                borrowernumber => $borrowernumber
-            }
-        )->next;
-    }
+    my $reserve_id = $args->{reserve_id};
 
+    my $hold = Koha::Holds->find($reserve_id);
     return unless $hold;
+
+    my $patron = $hold->borrower;
     my $reserve = $hold->unblessed;
 
     return  C4::Letters::GetPreparedLetter (