From 00a4bc523c0415bcd98e5f5b9cb6c6129f44f709 Mon Sep 17 00:00:00 2001
From: Martin Renvoize <martin.renvoize@ptfs-europe.com>
Date: Mon, 11 Nov 2019 14:23:44 +0000
Subject: [PATCH] Bug 24009: Add filter_by option to outstanding_debits

This patch adds an optional 'filter_by' argument to
Koha::Account->outstanding_debits which current accepts 'blocks_issue'
and will filter down the result set of outstanding_debits based upon the
values of the following system preferences.

* `HoldsInNoissuesCharge`
* `RentalsInNoissuesCharge`
* `ManInvInNoissuesCharge`

Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>
---
 Koha/Account.pm | 43 ++++++++++++++++++++++++++++++++++++-------
 1 file changed, 36 insertions(+), 7 deletions(-)

diff --git a/Koha/Account.pm b/Koha/Account.pm
index b120faee0f..a594607e55 100644
--- a/Koha/Account.pm
+++ b/Koha/Account.pm
@@ -605,24 +605,53 @@ sub balance {
 
 =head3 outstanding_debits
 
-my $lines = Koha::Account->new({ patron_id => $patron_id })->outstanding_debits;
+  my $lines = Koha::Account->new({ patron_id => $patron_id })->outstanding_debits;
+  my $lines = Koha::Account->new({ patron_id => $patron_id })->outstanding_debits( { filter_by => 'blocks_issue } );
 
 It returns the debit lines with outstanding amounts for the patron.
 
 In scalar context, it returns a Koha::Account::Lines iterator. In list context, it will
 return a list of Koha::Account::Line objects.
 
+Optionally a 'filter_by' arguament can be added to pre-filter the result by certain conditions:
+
+=over
+
+=item blocks_issue
+
+Filter outstanding debits to only those which affect whether a patron may have items issued to them.
+
+=back
+
 =cut
 
 sub outstanding_debits {
-    my ($self) = @_;
+    my ( $self, $args ) = @_;
 
-    return $self->lines->search(
-        {
-            amount            => { '>' => 0 },
-            amountoutstanding => { '>' => 0 }
+    my $where = {
+        amount            => { '>' => 0 },
+        amountoutstanding => { '>' => 0 }
+    };
+
+    if ( exists( $args->{filter_by} ) ) {
+        if ( $args->{filter_by} eq 'blocks_issue' ) {
+            my @not_fines;
+            push @not_fines, 'RESERVE'
+              unless C4::Context->preference('HoldsInNoissuesCharge');
+            push @not_fines,
+              ( 'RENT', 'RENT_DAILY', 'RENT_RENEW', 'RENT_DAILY_RENEW' )
+              unless C4::Context->preference('RentalsInNoissuesCharge');
+            unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
+                my @man_inv =
+                  Koha::Account::DebitTypes->search( { is_system => 0 } )
+                  ->get_column('code');
+                push @not_fines, @man_inv;
+            }
+            $where->{debit_type_code} = { -not_in => \@not_fines };
         }
-    );
+    }
+
+    return $self->lines->search($where);
 }
 
 =head3 outstanding_credits
-- 
2.24.0