From 4200b0bc175ca0219db66f747731c15338504030 Mon Sep 17 00:00:00 2001
From: Kyle M Hall <kyle@bywatersolutions.com>
Date: Thu, 17 Jul 2014 10:57:06 -0400
Subject: [PATCH] Bug 12596 - Backdating returns with SpecifiyReturnDate causes
 fines for items not overdue!

When using the backdating of returns feature, an item that is not
overdue is treated as being as many days overdue as it is *not* overdue.
This is due to the fact that _get_chargeable_units appears to return the
difference between the return date and the due date without
consideration the return date being earlier than the due date.

Test Plan:
1) Apply the unit test patch
2) prove t/db_dependent/Circulation.t
3) Note the failure
4) Apply the second patch
5) prove t/db_dependent/Circulation.t
6) Note there are no failures

Signed-off-by: Chris Cormack <chrisc@catalyst.net.nz>
Fixes some badly named variables also
---
 C4/Overdues.pm | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)

diff --git a/C4/Overdues.pm b/C4/Overdues.pm
index 169b36c..b3ec066 100644
--- a/C4/Overdues.pm
+++ b/C4/Overdues.pm
@@ -282,15 +282,19 @@ C<$branchcode> is the branch whose calendar to use for finding holidays.
 =cut
 
 sub _get_chargeable_units {
-    my ($unit, $dt1, $dt2, $branchcode) = @_;
+    my ($unit, $date_due, $date_returned, $branchcode) = @_;
+
+    # If the due date is later than the return date
+    return 0 unless ( $date_returned > $date_due );
+
     my $charge_units = 0;
     my $charge_duration;
     if ($unit eq 'hours') {
         if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
             my $calendar = Koha::Calendar->new( branchcode => $branchcode );
-            $charge_duration = $calendar->hours_between( $dt1, $dt2 );
+            $charge_duration = $calendar->hours_between( $date_due, $date_returned );
         } else {
-            $charge_duration = $dt2->delta_ms( $dt1 );
+            $charge_duration = $date_returned->delta_ms( $date_due );
         }
         if($charge_duration->in_units('hours') == 0 && $charge_duration->in_units('seconds') > 0){
             return 1;
@@ -300,9 +304,9 @@ sub _get_chargeable_units {
     else { # days
         if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
             my $calendar = Koha::Calendar->new( branchcode => $branchcode );
-            $charge_duration = $calendar->days_between( $dt1, $dt2 );
+            $charge_duration = $calendar->days_between( $date_due, $date_returned );
         } else {
-            $charge_duration = $dt2->delta_days( $dt1 );
+            $charge_duration = $date_returned->delta_days( $date_due );
         }
         return $charge_duration->in_units('days');
     }
-- 
2.0.1