From 5ed2aa0d283f78d66c0e478ec37ded15ff05f636 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

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.

Signed-off-by: Martin Renvoize <martin.renvoize@ptfs-europe.com>
---
 C4/Overdues.pm | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/C4/Overdues.pm b/C4/Overdues.pm
index 54a42649f7..69421f3a8d 100644
--- a/C4/Overdues.pm
+++ b/C4/Overdues.pm
@@ -535,7 +535,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) {
                 Koha::Logger->get->debug("Not a unique accountlines record for issue_id $issue_id"); # FIXME Do we really need to log that?
                 #FIXME Should we still count this one in total_amount ??
@@ -564,7 +564,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.20.1