Bug 11112: (follow-up) repair Koha::Calendar->add_holiday()
[koha.git] / Koha / Calendar.pm
1 package Koha::Calendar;
2 use strict;
3 use warnings;
4 use 5.010;
5
6 use DateTime;
7 use DateTime::Set;
8 use DateTime::Duration;
9 use C4::Context;
10 use Carp;
11 use Readonly;
12
13 sub new {
14     my ( $classname, %options ) = @_;
15     my $self = {};
16     bless $self, $classname;
17     for my $o_name ( keys %options ) {
18         my $o = lc $o_name;
19         $self->{$o} = $options{$o_name};
20     }
21     if ( !defined $self->{branchcode} ) {
22         croak 'No branchcode argument passed to Koha::Calendar->new';
23     }
24     $self->_init();
25     return $self;
26 }
27
28 sub _init {
29     my $self       = shift;
30     my $branch     = $self->{branchcode};
31     my $dbh        = C4::Context->dbh();
32     my $weekly_closed_days_sth = $dbh->prepare(
33 'SELECT weekday FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NOT NULL'
34     );
35     $weekly_closed_days_sth->execute( $branch );
36     $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ];
37     Readonly::Scalar my $sunday => 7;
38     while ( my $tuple = $weekly_closed_days_sth->fetchrow_hashref ) {
39         $self->{weekly_closed_days}->[ $tuple->{weekday} ] = 1;
40     }
41     my $day_month_closed_days_sth = $dbh->prepare(
42 'SELECT day, month FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NULL'
43     );
44     $day_month_closed_days_sth->execute( $branch );
45     $self->{day_month_closed_days} = {};
46     while ( my $tuple = $day_month_closed_days_sth->fetchrow_hashref ) {
47         $self->{day_month_closed_days}->{ $tuple->{month} }->{ $tuple->{day} } =
48           1;
49     }
50
51     $self->{days_mode}       = C4::Context->preference('useDaysMode');
52     $self->{test}            = 0;
53     return;
54 }
55
56
57 our ( $exception_holidays, $single_holidays );
58 sub exception_holidays {
59     my ( $self ) = @_;
60     my $dbh = C4::Context->dbh;
61     my $branch = $self->{branchcode};
62     if ( $exception_holidays ) {
63         $self->{exception_holidays} = $exception_holidays;
64         return $exception_holidays;
65     }
66     my $exception_holidays_sth = $dbh->prepare(
67 'SELECT day, month, year FROM special_holidays WHERE branchcode = ? AND isexception = 1'
68     );
69     $exception_holidays_sth->execute( $branch );
70     my $dates = [];
71     while ( my ( $day, $month, $year ) = $exception_holidays_sth->fetchrow ) {
72         push @{$dates},
73           DateTime->new(
74             day       => $day,
75             month     => $month,
76             year      => $year,
77             time_zone => C4::Context->tz()
78           )->truncate( to => 'day' );
79     }
80     $self->{exception_holidays} =
81       DateTime::Set->from_datetimes( dates => $dates );
82     $exception_holidays = $self->{exception_holidays};
83     return $exception_holidays;
84 }
85
86 sub single_holidays {
87     my ( $self ) = @_;
88     my $dbh = C4::Context->dbh;
89     my $branch = $self->{branchcode};
90     if ( $single_holidays ) {
91         $self->{single_holidays} = $single_holidays;
92         return $single_holidays;
93     }
94     my $single_holidays_sth = $dbh->prepare(
95 'SELECT day, month, year FROM special_holidays WHERE branchcode = ? AND isexception = 0'
96     );
97     $single_holidays_sth->execute( $branch );
98     my $dates = [];
99     while ( my ( $day, $month, $year ) = $single_holidays_sth->fetchrow ) {
100         push @{$dates},
101           DateTime->new(
102             day       => $day,
103             month     => $month,
104             year      => $year,
105             time_zone => C4::Context->tz()
106           )->truncate( to => 'day' );
107     }
108     $self->{single_holidays} = DateTime::Set->from_datetimes( dates => $dates );
109     $single_holidays = $self->{single_holidays};
110     return $single_holidays;
111 }
112 sub addDate {
113     my ( $self, $startdate, $add_duration, $unit ) = @_;
114
115     # Default to days duration (legacy support I guess)
116     if ( ref $add_duration ne 'DateTime::Duration' ) {
117         $add_duration = DateTime::Duration->new( days => $add_duration );
118     }
119
120     $unit ||= 'days'; # default days ?
121     my $dt;
122
123     if ( $unit eq 'hours' ) {
124         # Fixed for legacy support. Should be set as a branch parameter
125         Readonly::Scalar my $return_by_hour => 10;
126
127         $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
128     } else {
129         # days
130         $dt = $self->addDays($startdate, $add_duration);
131     }
132
133     return $dt;
134 }
135
136 sub addHours {
137     my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
138     my $base_date = $startdate->clone();
139
140     $base_date->add_duration($hours_duration);
141
142     # If we are using the calendar behave for now as if Datedue
143     # was the chosen option (current intended behaviour)
144
145     if ( $self->{days_mode} ne 'Days' &&
146           $self->is_holiday($base_date) ) {
147
148         if ( $hours_duration->is_negative() ) {
149             $base_date = $self->prev_open_day($base_date);
150         } else {
151             $base_date = $self->next_open_day($base_date);
152         }
153
154         $base_date->set_hour($return_by_hour);
155
156     }
157
158     return $base_date;
159 }
160
161 sub addDays {
162     my ( $self, $startdate, $days_duration ) = @_;
163     my $base_date = $startdate->clone();
164
165     if ( $self->{days_mode} eq 'Calendar' ) {
166         # use the calendar to skip all days the library is closed
167         # when adding
168         my $days = abs $days_duration->in_units('days');
169
170         if ( $days_duration->is_negative() ) {
171             while ($days) {
172                 $base_date = $self->prev_open_day($base_date);
173                 --$days;
174             }
175         } else {
176             while ($days) {
177                 $base_date = $self->next_open_day($base_date);
178                 --$days;
179             }
180         }
181
182     } else { # Days or Datedue
183         # use straight days, then use calendar to push
184         # the date to the next open day if Datedue
185         $base_date->add_duration($days_duration);
186
187         if ( $self->{days_mode} eq 'Datedue' ) {
188             # Datedue, then use the calendar to push
189             # the date to the next open day if holiday
190             if ( $self->is_holiday($base_date) ) {
191                 if ( $days_duration->is_negative() ) {
192                     $base_date = $self->prev_open_day($base_date);
193                 } else {
194                     $base_date = $self->next_open_day($base_date);
195                 }
196             }
197         }
198     }
199
200     return $base_date;
201 }
202
203 sub is_holiday {
204     my ( $self, $dt ) = @_;
205     my $localdt = $dt->clone();
206     my $day   = $localdt->day;
207     my $month = $localdt->month;
208
209     $localdt->truncate( to => 'day' );
210
211     if ( $self->exception_holidays->contains($localdt) ) {
212         # exceptions are not holidays
213         return 0;
214     }
215
216     my $dow = $localdt->day_of_week;
217     # Representation fix
218     # TODO: Shouldn't we shift the rest of the $dow also?
219     if ( $dow == 7 ) {
220         $dow = 0;
221     }
222
223     if ( $self->{weekly_closed_days}->[$dow] == 1 ) {
224         return 1;
225     }
226
227     if ( exists $self->{day_month_closed_days}->{$month}->{$day} ) {
228         return 1;
229     }
230
231     if ( $self->single_holidays->contains($localdt) ) {
232         return 1;
233     }
234
235     # damn have to go to work after all
236     return 0;
237 }
238
239 sub next_open_day {
240     my ( $self, $dt ) = @_;
241     my $base_date = $dt->clone();
242
243     $base_date->add(days => 1);
244
245     while ($self->is_holiday($base_date)) {
246         $base_date->add(days => 1);
247     }
248
249     return $base_date;
250 }
251
252 sub prev_open_day {
253     my ( $self, $dt ) = @_;
254     my $base_date = $dt->clone();
255
256     $base_date->add(days => -1);
257
258     while ($self->is_holiday($base_date)) {
259         $base_date->add(days => -1);
260     }
261
262     return $base_date;
263 }
264
265 sub days_between {
266     my $self     = shift;
267     my $start_dt = shift;
268     my $end_dt   = shift;
269
270     if ( $start_dt->compare($end_dt) > 0 ) {
271         # swap dates
272         my $int_dt = $end_dt;
273         $end_dt = $start_dt;
274         $start_dt = $int_dt;
275     }
276
277
278     # start and end should not be closed days
279     my $days = $start_dt->delta_days($end_dt)->delta_days;
280     for (my $dt = $start_dt->clone();
281         $dt <= $end_dt;
282         $dt->add(days => 1)
283     ) {
284         if ($self->is_holiday($dt)) {
285             $days--;
286         }
287     }
288     return DateTime::Duration->new( days => $days );
289
290 }
291
292 sub hours_between {
293     my ($self, $start_date, $end_date) = @_;
294     my $start_dt = $start_date->clone();
295     my $end_dt = $end_date->clone();
296     my $duration = $end_dt->delta_ms($start_dt);
297     $start_dt->truncate( to => 'day' );
298     $end_dt->truncate( to => 'day' );
299     # NB this is a kludge in that it assumes all days are 24 hours
300     # However for hourly loans the logic should be expanded to
301     # take into account open/close times then it would be a duration
302     # of library open hours
303     my $skipped_days = 0;
304     for (my $dt = $start_dt->clone();
305         $dt <= $end_dt;
306         $dt->add(days => 1)
307     ) {
308         if ($self->is_holiday($dt)) {
309             ++$skipped_days;
310         }
311     }
312     if ($skipped_days) {
313         $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days));
314     }
315
316     return $duration;
317
318 }
319
320 sub set_daysmode {
321     my ( $self, $mode ) = @_;
322
323     # if not testing this is a no op
324     if ( $self->{test} ) {
325         $self->{days_mode} = $mode;
326     }
327
328     return;
329 }
330
331 sub clear_weekly_closed_days {
332     my $self = shift;
333     $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ];    # Sunday only
334     return;
335 }
336
337 sub add_holiday {
338     my $self = shift;
339     my $new_dt = shift;
340     my @dt = $self->single_holidays->as_list;
341     push @dt, $new_dt;
342     $self->{single_holidays} =
343       DateTime::Set->from_datetimes( dates => \@dt );
344     $single_holidays = $self->{single_holidays};
345
346     return;
347 }
348
349 1;
350 __END__
351
352 =head1 NAME
353
354 Koha::Calendar - Object containing a branches calendar
355
356 =head1 VERSION
357
358 This documentation refers to Koha::Calendar version 0.0.1
359
360 =head1 SYNOPSIS
361
362   use Koha::Calendar
363
364   my $c = Koha::Calendar->new( branchcode => 'MAIN' );
365   my $dt = DateTime->now();
366
367   # are we open
368   $open = $c->is_holiday($dt);
369   # when will item be due if loan period = $dur (a DateTime::Duration object)
370   $duedate = $c->addDate($dt,$dur,'days');
371
372
373 =head1 DESCRIPTION
374
375   Implements those features of C4::Calendar needed for Staffs Rolling Loans
376
377 =head1 METHODS
378
379 =head2 new : Create a calendar object
380
381 my $calendar = Koha::Calendar->new( branchcode => 'MAIN' );
382
383 The option branchcode is required
384
385
386 =head2 addDate
387
388     my $dt = $calendar->addDate($date, $dur, $unit)
389
390 C<$date> is a DateTime object representing the starting date of the interval.
391
392 C<$offset> is a DateTime::Duration to add to it
393
394 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
395
396 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
397 parameter will be removed when issuingrules properly cope with that
398
399
400 =head2 addHours
401
402     my $dt = $calendar->addHours($date, $dur, $return_by_hour )
403
404 C<$date> is a DateTime object representing the starting date of the interval.
405
406 C<$offset> is a DateTime::Duration to add to it
407
408 C<$return_by_hour> is an integer value representing the opening hour for the branch
409
410
411 =head2 addDays
412
413     my $dt = $calendar->addDays($date, $dur)
414
415 C<$date> is a DateTime object representing the starting date of the interval.
416
417 C<$offset> is a DateTime::Duration to add to it
418
419 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
420
421 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
422 parameter will be removed when issuingrules properly cope with that
423
424
425 =head2 is_holiday
426
427 $yesno = $calendar->is_holiday($dt);
428
429 passed a DateTime object returns 1 if it is a closed day
430 0 if not according to the calendar
431
432 =head2 days_between
433
434 $duration = $calendar->days_between($start_dt, $end_dt);
435
436 Passed two dates returns a DateTime::Duration object measuring the length between them
437 ignoring closed days. Always returns a positive number irrespective of the
438 relative order of the parameters
439
440 =head2 next_open_day
441
442 $datetime = $calendar->next_open_day($duedate_dt)
443
444 Passed a Datetime returns another Datetime representing the next open day. It is
445 intended for use to calculate the due date when useDaysMode syspref is set to either
446 'Datedue' or 'Calendar'.
447
448 =head2 prev_open_day
449
450 $datetime = $calendar->prev_open_day($duedate_dt)
451
452 Passed a Datetime returns another Datetime representing the previous open day. It is
453 intended for use to calculate the due date when useDaysMode syspref is set to either
454 'Datedue' or 'Calendar'.
455
456 =head2 set_daysmode
457
458 For testing only allows the calling script to change days mode
459
460 =head2 clear_weekly_closed_days
461
462 In test mode changes the testing set of closed days to a new set with
463 no closed days. TODO passing an array of closed days to this would
464 allow testing of more configurations
465
466 =head2 add_holiday
467
468 Passed a datetime object this will add it to the calendar's list of
469 closed days. This is for testing so that we can alter the Calenfar object's
470 list of specified dates
471
472 =head1 DIAGNOSTICS
473
474 Will croak if not passed a branchcode in new
475
476 =head1 BUGS AND LIMITATIONS
477
478 This only contains a limited subset of the functionality in C4::Calendar
479 Only enough to support Staffs Rolling loans
480
481 =head1 AUTHOR
482
483 Colin Campbell colin.campbell@ptfs-europe.com
484
485 =head1 LICENSE AND COPYRIGHT
486
487 Copyright (c) 2011 PTFS-Europe Ltd All rights reserved
488
489 This program is free software: you can redistribute it and/or modify
490 it under the terms of the GNU General Public License as published by
491 the Free Software Foundation, either version 2 of the License, or
492 (at your option) any later version.
493
494 This program is distributed in the hope that it will be useful,
495 but WITHOUT ANY WARRANTY; without even the implied warranty of
496 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
497 GNU General Public License for more details.
498
499 You should have received a copy of the GNU General Public License
500 along with this program.  If not, see <http://www.gnu.org/licenses/>.