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