Bug 21909: Make Koha::Account::outstanding_* preserve context
[srvgit] / Koha / Account.pm
index 4356411..304d0e2 100644 (file)
@@ -428,13 +428,12 @@ my $lines = Koha::Account->new({ patron_id => $patron_id })->outstanding_debits;
 sub outstanding_debits {
     my ($self) = @_;
 
-    my $lines = $self->lines->search(
+    return $self->lines->search(
         {
+            amount            => { '>' => 0 },
             amountoutstanding => { '>' => 0 }
         }
     );
-
-    return $lines;
 }
 
 =head3 outstanding_credits
@@ -446,13 +445,12 @@ my $lines = Koha::Account->new({ patron_id => $patron_id })->outstanding_credits
 sub outstanding_credits {
     my ($self) = @_;
 
-    my $lines = $self->lines->search(
+    return $self->lines->search(
         {
+            amount            => { '<' => 0 },
             amountoutstanding => { '<' => 0 }
         }
     );
-
-    return $lines;
 }
 
 =head3 non_issues_charges
@@ -515,6 +513,35 @@ sub lines {
     );
 }
 
+=head3 reconcile_balance
+
+$account->reconcile_balance();
+
+Find outstanding credits and use them to pay outstanding debits.
+Currently, this implicitly uses the 'First In First Out' rule for
+applying credits against debits.
+
+=cut
+
+sub reconcile_balance {
+    my ($self) = @_;
+
+    my $outstanding_debits  = $self->outstanding_debits;
+    my $outstanding_credits = $self->outstanding_credits;
+
+    while (     $outstanding_debits->total_outstanding > 0
+            and my $credit = $outstanding_credits->next )
+    {
+        # there's both outstanding debits and credits
+        $credit->apply( { debits => $outstanding_debits } );    # applying credit, no special offset
+
+        $outstanding_debits = $self->outstanding_debits;
+
+    }
+
+    return $self;
+}
+
 1;
 
 =head2 Name mappings