From 6fb20bbf8fe269db380c7f4d7eed672936f3c2e5 Mon Sep 17 00:00:00 2001
From: Michael Hafen <michael.hafen@washk12.org>
Date: Thu, 18 Nov 2021 11:50:44 -0700
Subject: [PATCH] Bug 18855: Don't create duplicate overdue fines if an issue
 is returned
Content-Type: text/plain; charset="utf-8"

If cronjobs/fines.pl is running during circulation hours, then an issue may
be considered for having it's overdue fine updated after the issue has been
returned and it's fine status flipped from 'UNRETURNED' to 'RETURNED'.  In
this case UpdateFine will create a duplicate fine because it can't find the
specific accountline for the overdue and unreturned fine.

This changes UpdateFine to not care about status, so the accountline will be
found, until it comes to adjusting the fine.  At this point if the fine is
'UNRETURNED' or 'CalculateFinesOnReturn' is off (the book was returned and
it's overdue fine status flipped, but the amount wasn't updated), then go
ahead and adjust the fine amount.

Test plan:
1. find an overdue fine near the end of the list of overdue fines that
   cronjobs/fines.pl will be considering.
2. start cronjobs/fines.pl.
3. immediately check in the overdue book.
4. once fines.pl is finished observe that a duplicate overdue fine has been
   created on the patrons account.

5. apply patch.
6. repeat 1 - 4 and observe that the duplicate fine was not created.
---
 C4/Overdues.pm | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/C4/Overdues.pm b/C4/Overdues.pm
index faea77e0f3..9c44f21e0c 100644
--- a/C4/Overdues.pm
+++ b/C4/Overdues.pm
@@ -545,7 +545,7 @@ sub UpdateFine {
     # - accumulate fines for other items
     # so we can update $itemnum fine taking in account fine caps
     while (my $overdue = $overdues->next) {
-        if ( defined $overdue->issue_id && $overdue->issue_id == $issue_id && $overdue->status eq 'UNRETURNED' ) {
+        if ( defined $overdue->issue_id && $overdue->issue_id == $issue_id ) {
             if ($accountline) {
                 $debug and warn "Not a unique accountlines record for issue_id $issue_id";
                 #FIXME Should we still count this one in total_amount ??
@@ -574,7 +574,9 @@ sub UpdateFine {
     }
 
     if ( $accountline ) {
-        if ( Koha::Number::Price->new($accountline->amount)->round != Koha::Number::Price->new($amount)->round ) {
+        # a book may be returned while cronjob/fines.pl is running
+        if ( ( $accountline->status eq 'UNRETURNED' || ! C4::Context->preference('CalculateFinesOnReturn') )
+             && Koha::Number::Price->new($accountline->amount)->round != Koha::Number::Price->new($amount)->round ) {
             $accountline->adjust(
                 {
                     amount    => $amount,
-- 
2.25.1