Use hour or day deltas to calculate overdue durations
[koha.git] / Koha / Calendar.pm
index bdd4b8f..75c5c9e 100644 (file)
@@ -83,10 +83,12 @@ sub _init {
 }
 
 sub addDate {
-    my ( $self, $base_date, $add_duration, $unit ) = @_;
+    my ( $self, $startdate, $add_duration, $unit ) = @_;
+    my $base_date = $startdate->clone();
     if ( ref $add_duration ne 'DateTime::Duration' ) {
         $add_duration = DateTime::Duration->new( days => $add_duration );
     }
+    $unit ||= q{};    # default days ?
     my $days_mode = $self->{days_mode};
     Readonly::Scalar my $return_by_hour => 10;
     my $day_dur = DateTime::Duration->new( days => 1 );
@@ -114,7 +116,7 @@ sub addDate {
             }
 
         } else {
-            my $days = $add_duration->in_units('days');
+            my $days = abs $add_duration->in_units('days');
             while ($days) {
                 $base_date->add_duration($day_dur);
                 if ( $self->is_holiday($base_date) ) {
@@ -166,11 +168,9 @@ sub days_between {
     my $self     = shift;
     my $start_dt = shift;
     my $end_dt   = shift;
-    $start_dt->truncate( to => 'hours' );
-    $end_dt->truncate( to => 'hours' );
 
     # start and end should not be closed days
-    my $duration = $end_dt - $start_dt;
+    my $duration = $end_dt->delta_days($start_dt);
     $start_dt->truncate( to => 'days' );
     $end_dt->truncate( to => 'days' );
     while ( DateTime->compare( $start_dt, $end_dt ) == -1 ) {
@@ -183,6 +183,25 @@ sub days_between {
 
 }
 
+sub hours_between {
+    my ($self, $start_dt, $end_dt) = @_;
+    my $duration = $end_dt->delta_ms($start_dt);
+    $start_dt->truncate( to => 'days' );
+    $end_dt->truncate( to => 'days' );
+    # NB this is a kludge in that it assumes all days are 24 hours
+    # However for hourly loans the logic should be expanded to
+    # take into account open/close times then it would be a duration
+    # of library open hours
+    while ( DateTime->compare( $start_dt, $end_dt ) == -1 ) {
+        $start_dt->add( days => 1 );
+        if ( $self->is_holiday($start_dt) ) {
+            $duration->subtract( hours => 24 );
+        }
+    }
+    return $duration;
+
+}
+
 sub _mockinit {
     my $self = shift;
     $self->{weekly_closed_days} = [ 1, 0, 0, 0, 0, 0, 0 ];    # Sunday only