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