Bug 11112: Koha::Calendar needs some caching
[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
345     return;
346 }
347
348 1;
349 __END__
350
351 =head1 NAME
352
353 Koha::Calendar - Object containing a branches calendar
354
355 =head1 VERSION
356
357 This documentation refers to Koha::Calendar version 0.0.1
358
359 =head1 SYNOPSIS
360
361   use Koha::Calendar
362
363   my $c = Koha::Calendar->new( branchcode => 'MAIN' );
364   my $dt = DateTime->now();
365
366   # are we open
367   $open = $c->is_holiday($dt);
368   # when will item be due if loan period = $dur (a DateTime::Duration object)
369   $duedate = $c->addDate($dt,$dur,'days');
370
371
372 =head1 DESCRIPTION
373
374   Implements those features of C4::Calendar needed for Staffs Rolling Loans
375
376 =head1 METHODS
377
378 =head2 new : Create a calendar object
379
380 my $calendar = Koha::Calendar->new( branchcode => 'MAIN' );
381
382 The option branchcode is required
383
384
385 =head2 addDate
386
387     my $dt = $calendar->addDate($date, $dur, $unit)
388
389 C<$date> is a DateTime object representing the starting date of the interval.
390
391 C<$offset> is a DateTime::Duration to add to it
392
393 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
394
395 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
396 parameter will be removed when issuingrules properly cope with that
397
398
399 =head2 addHours
400
401     my $dt = $calendar->addHours($date, $dur, $return_by_hour )
402
403 C<$date> is a DateTime object representing the starting date of the interval.
404
405 C<$offset> is a DateTime::Duration to add to it
406
407 C<$return_by_hour> is an integer value representing the opening hour for the branch
408
409
410 =head2 addDays
411
412     my $dt = $calendar->addDays($date, $dur)
413
414 C<$date> is a DateTime object representing the starting date of the interval.
415
416 C<$offset> is a DateTime::Duration to add to it
417
418 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
419
420 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
421 parameter will be removed when issuingrules properly cope with that
422
423
424 =head2 is_holiday
425
426 $yesno = $calendar->is_holiday($dt);
427
428 passed a DateTime object returns 1 if it is a closed day
429 0 if not according to the calendar
430
431 =head2 days_between
432
433 $duration = $calendar->days_between($start_dt, $end_dt);
434
435 Passed two dates returns a DateTime::Duration object measuring the length between them
436 ignoring closed days. Always returns a positive number irrespective of the
437 relative order of the parameters
438
439 =head2 next_open_day
440
441 $datetime = $calendar->next_open_day($duedate_dt)
442
443 Passed a Datetime returns another Datetime representing the next open day. It is
444 intended for use to calculate the due date when useDaysMode syspref is set to either
445 'Datedue' or 'Calendar'.
446
447 =head2 prev_open_day
448
449 $datetime = $calendar->prev_open_day($duedate_dt)
450
451 Passed a Datetime returns another Datetime representing the previous open day. It is
452 intended for use to calculate the due date when useDaysMode syspref is set to either
453 'Datedue' or 'Calendar'.
454
455 =head2 set_daysmode
456
457 For testing only allows the calling script to change days mode
458
459 =head2 clear_weekly_closed_days
460
461 In test mode changes the testing set of closed days to a new set with
462 no closed days. TODO passing an array of closed days to this would
463 allow testing of more configurations
464
465 =head2 add_holiday
466
467 Passed a datetime object this will add it to the calendar's list of
468 closed days. This is for testing so that we can alter the Calenfar object's
469 list of specified dates
470
471 =head1 DIAGNOSTICS
472
473 Will croak if not passed a branchcode in new
474
475 =head1 BUGS AND LIMITATIONS
476
477 This only contains a limited subset of the functionality in C4::Calendar
478 Only enough to support Staffs Rolling loans
479
480 =head1 AUTHOR
481
482 Colin Campbell colin.campbell@ptfs-europe.com
483
484 =head1 LICENSE AND COPYRIGHT
485
486 Copyright (c) 2011 PTFS-Europe Ltd All rights reserved
487
488 This program is free software: you can redistribute it and/or modify
489 it under the terms of the GNU General Public License as published by
490 the Free Software Foundation, either version 2 of the License, or
491 (at your option) any later version.
492
493 This program is distributed in the hope that it will be useful,
494 but WITHOUT ANY WARRANTY; without even the implied warranty of
495 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
496 GNU General Public License for more details.
497
498 You should have received a copy of the GNU General Public License
499 along with this program.  If not, see <http://www.gnu.org/licenses/>.