Bug 25723: (QA follow-up) Silent POD warning
[koha.git] / Koha / Calendar.pm
blobc0dcd8e93dcedeabd52465dc1f7b840294e64dcf
1 package Koha::Calendar;
3 use Modern::Perl;
5 use Carp;
6 use DateTime;
7 use DateTime::Duration;
8 use C4::Context;
9 use Koha::Caches;
10 use Koha::Exceptions;
12 sub new {
13 my ( $classname, %options ) = @_;
14 my $self = {};
15 bless $self, $classname;
16 for my $o_name ( keys %options ) {
17 my $o = lc $o_name;
18 $self->{$o} = $options{$o_name};
20 if ( !defined $self->{branchcode} ) {
21 croak 'No branchcode argument passed to Koha::Calendar->new';
23 $self->_init();
24 return $self;
27 sub _init {
28 my $self = shift;
29 my $branch = $self->{branchcode};
30 my $dbh = C4::Context->dbh();
31 my $weekly_closed_days_sth = $dbh->prepare(
32 'SELECT weekday FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NOT NULL'
34 $weekly_closed_days_sth->execute( $branch );
35 $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ];
36 while ( my $tuple = $weekly_closed_days_sth->fetchrow_hashref ) {
37 $self->{weekly_closed_days}->[ $tuple->{weekday} ] = 1;
39 my $day_month_closed_days_sth = $dbh->prepare(
40 'SELECT day, month FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NULL'
42 $day_month_closed_days_sth->execute( $branch );
43 $self->{day_month_closed_days} = {};
44 while ( my $tuple = $day_month_closed_days_sth->fetchrow_hashref ) {
45 $self->{day_month_closed_days}->{ $tuple->{month} }->{ $tuple->{day} } =
49 $self->{test} = 0;
50 return;
53 sub _holidays {
54 my ($self) = @_;
56 my $key = $self->{branchcode} . "_holidays";
57 my $cache = Koha::Caches->get_instance();
58 my $holidays = $cache->get_from_cache($key);
60 # $holidays looks like:
61 # {
62 # 20131122 => 1, # single_holiday
63 # 20131123 => 0, # exception_holiday
64 # ...
65 # }
67 # Populate the cache if necessary
68 unless ($holidays) {
69 my $dbh = C4::Context->dbh;
70 $holidays = {};
72 # Add holidays for each branch
73 my $holidays_sth = $dbh->prepare(
74 'SELECT day, month, year, isexception FROM special_holidays WHERE branchcode = ?'
76 $holidays_sth->execute($self->{branchcode});
78 while ( my ( $day, $month, $year, $exception ) =
79 $holidays_sth->fetchrow )
81 my $datestring =
82 sprintf( "%04d", $year )
83 . sprintf( "%02d", $month )
84 . sprintf( "%02d", $day );
86 $holidays->{$datestring} = !$exception;
88 $cache->set_in_cache( $key, $holidays, { expiry => 76800 } );
91 return $holidays // {};
94 sub addDate {
95 my ( $self, $startdate, $add_duration, $unit ) = @_;
98 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDate: days_mode")
99 unless exists $self->{days_mode};
101 # Default to days duration (legacy support I guess)
102 if ( ref $add_duration ne 'DateTime::Duration' ) {
103 $add_duration = DateTime::Duration->new( days => $add_duration );
106 $unit ||= 'days'; # default days ?
107 my $dt;
108 if ( $unit eq 'hours' ) {
109 # Fixed for legacy support. Should be set as a branch parameter
110 my $return_by_hour = 10;
112 $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
113 } else {
114 # days
115 $dt = $self->addDays($startdate, $add_duration);
117 return $dt;
120 sub addHours {
121 my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
122 my $base_date = $startdate->clone();
124 $base_date->add_duration($hours_duration);
126 # If we are using the calendar behave for now as if Datedue
127 # was the chosen option (current intended behaviour)
129 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addHours: days_mode")
130 unless exists $self->{days_mode};
132 if ( $self->{days_mode} ne 'Days' &&
133 $self->is_holiday($base_date) ) {
135 if ( $hours_duration->is_negative() ) {
136 $base_date = $self->prev_open_days($base_date, 1);
137 } else {
138 $base_date = $self->next_open_days($base_date, 1);
141 $base_date->set_hour($return_by_hour);
145 return $base_date;
148 sub addDays {
149 my ( $self, $startdate, $days_duration ) = @_;
150 my $base_date = $startdate->clone();
152 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDays: days_mode")
153 unless exists $self->{days_mode};
155 if ( $self->{days_mode} eq 'Calendar' ) {
156 # use the calendar to skip all days the library is closed
157 # when adding
158 my $days = abs $days_duration->in_units('days');
160 if ( $days_duration->is_negative() ) {
161 while ($days) {
162 $base_date = $self->prev_open_days($base_date, 1);
163 --$days;
165 } else {
166 while ($days) {
167 $base_date = $self->next_open_days($base_date, 1);
168 --$days;
172 } else { # Days, Datedue or Dayweek
173 # use straight days, then use calendar to push
174 # the date to the next open day as appropriate
175 # if Datedue or Dayweek
176 $base_date->add_duration($days_duration);
178 if ( $self->{days_mode} eq 'Datedue' ||
179 $self->{days_mode} eq 'Dayweek') {
180 # Datedue or Dayweek, then use the calendar to push
181 # the date to the next open day if holiday
182 if ( $self->is_holiday($base_date) ) {
183 my $dow = $base_date->day_of_week;
184 my $days = $days_duration->in_units('days');
185 # Is it a period based on weeks
186 my $push_amt = $days % 7 == 0 ?
187 $self->get_push_amt($base_date) : 1;
188 if ( $days_duration->is_negative() ) {
189 $base_date = $self->prev_open_days($base_date, $push_amt);
190 } else {
191 $base_date = $self->next_open_days($base_date, $push_amt);
197 return $base_date;
200 sub get_push_amt {
201 my ( $self, $base_date) = @_;
203 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_push_amt: days_mode")
204 unless exists $self->{days_mode};
206 my $dow = $base_date->day_of_week;
207 # Representation fix
208 # DateTime object dow (1-7) where Monday is 1
209 # Arrays are 0-based where 0 = Sunday, not 7.
210 if ( $dow == 7 ) {
211 $dow = 0;
214 return (
215 # We're using Dayweek useDaysMode option
216 $self->{days_mode} eq 'Dayweek' &&
217 # It's not a permanently closed day
218 !$self->{weekly_closed_days}->[$dow]
219 ) ? 7 : 1;
222 sub is_holiday {
223 my ( $self, $dt ) = @_;
225 my $localdt = $dt->clone();
226 my $day = $localdt->day;
227 my $month = $localdt->month;
228 my $ymd = $localdt->ymd('');
230 #Change timezone to "floating" before doing any calculations or comparisons
231 $localdt->set_time_zone("floating");
232 $localdt->truncate( to => 'day' );
234 return $self->_holidays->{$ymd} if defined($self->_holidays->{$ymd});
236 my $dow = $localdt->day_of_week;
237 # Representation fix
238 # DateTime object dow (1-7) where Monday is 1
239 # Arrays are 0-based where 0 = Sunday, not 7.
240 if ( $dow == 7 ) {
241 $dow = 0;
244 if ( $self->{weekly_closed_days}->[$dow] == 1 ) {
245 return 1;
248 if ( exists $self->{day_month_closed_days}->{$month}->{$day} ) {
249 return 1;
252 # damn have to go to work after all
253 return 0;
256 sub next_open_days {
257 my ( $self, $dt, $to_add ) = @_;
259 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->next_open_days: days_mode")
260 unless exists $self->{days_mode};
262 my $base_date = $dt->clone();
264 $base_date->add(days => $to_add);
265 while ($self->is_holiday($base_date)) {
266 my $add_next = $self->get_push_amt($base_date);
267 $base_date->add(days => $add_next);
269 return $base_date;
272 sub prev_open_days {
273 my ( $self, $dt, $to_sub ) = @_;
275 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_open_days: days_mode")
276 unless exists $self->{days_mode};
278 my $base_date = $dt->clone();
280 # It feels logical to be passed a positive number, though we're
281 # subtracting, so do the right thing
282 $to_sub = $to_sub > 0 ? 0 - $to_sub : $to_sub;
284 $base_date->add(days => $to_sub);
286 while ($self->is_holiday($base_date)) {
287 my $sub_next = $self->get_push_amt($base_date);
288 # Ensure we're subtracting when we need to be
289 $sub_next = $sub_next > 0 ? 0 - $sub_next : $sub_next;
290 $base_date->add(days => $sub_next);
293 return $base_date;
296 sub days_forward {
297 my $self = shift;
298 my $start_dt = shift;
299 my $num_days = shift;
301 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->days_forward: days_mode")
302 unless exists $self->{days_mode};
304 return $start_dt unless $num_days > 0;
306 my $base_dt = $start_dt->clone();
308 while ($num_days--) {
309 $base_dt = $self->next_open_days($base_dt, 1);
312 return $base_dt;
315 sub days_between {
316 my $self = shift;
317 my $start_dt = shift;
318 my $end_dt = shift;
320 # Change time zone for date math and swap if needed
321 $start_dt = $start_dt->clone->set_time_zone('floating');
322 $end_dt = $end_dt->clone->set_time_zone('floating');
323 if( $start_dt->compare($end_dt) > 0 ) {
324 ( $start_dt, $end_dt ) = ( $end_dt, $start_dt );
327 # start and end should not be closed days
328 my $delta_days = $start_dt->delta_days($end_dt)->delta_days;
329 while( $start_dt->compare($end_dt) < 1 ) {
330 $delta_days-- if $self->is_holiday($start_dt);
331 $start_dt->add( days => 1 );
333 return DateTime::Duration->new( days => $delta_days );
336 sub hours_between {
337 my ($self, $start_date, $end_date) = @_;
338 my $start_dt = $start_date->clone()->set_time_zone('floating');
339 my $end_dt = $end_date->clone()->set_time_zone('floating');
341 my $duration = $end_dt->delta_ms($start_dt);
342 $start_dt->truncate( to => 'day' );
343 $end_dt->truncate( to => 'day' );
345 # NB this is a kludge in that it assumes all days are 24 hours
346 # However for hourly loans the logic should be expanded to
347 # take into account open/close times then it would be a duration
348 # of library open hours
349 my $skipped_days = 0;
350 while( $start_dt->compare($end_dt) < 1 ) {
351 $skipped_days++ if $self->is_holiday($start_dt);
352 $start_dt->add( days => 1 );
355 if ($skipped_days) {
356 $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days));
359 return $duration;
362 sub set_daysmode {
363 my ( $self, $mode ) = @_;
365 # if not testing this is a no op
366 if ( $self->{test} ) {
367 $self->{days_mode} = $mode;
370 return;
373 sub clear_weekly_closed_days {
374 my $self = shift;
375 $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ]; # Sunday only
376 return;
380 __END__
382 =head1 NAME
384 Koha::Calendar - Object containing a branches calendar
386 =head1 SYNOPSIS
388 use Koha::Calendar
390 my $c = Koha::Calendar->new( branchcode => 'MAIN' );
391 my $dt = dt_from_string();
393 # are we open
394 $open = $c->is_holiday($dt);
395 # when will item be due if loan period = $dur (a DateTime::Duration object)
396 $duedate = $c->addDate($dt,$dur,'days');
399 =head1 DESCRIPTION
401 Implements those features of C4::Calendar needed for Staffs Rolling Loans
403 =head1 METHODS
405 =head2 new : Create a calendar object
407 my $calendar = Koha::Calendar->new( branchcode => 'MAIN' );
409 The option branchcode is required
412 =head2 addDate
414 my $dt = $calendar->addDate($date, $dur, $unit)
416 C<$date> is a DateTime object representing the starting date of the interval.
418 C<$offset> is a DateTime::Duration to add to it
420 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
422 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
423 parameter will be removed when issuingrules properly cope with that
426 =head2 addHours
428 my $dt = $calendar->addHours($date, $dur, $return_by_hour )
430 C<$date> is a DateTime object representing the starting date of the interval.
432 C<$offset> is a DateTime::Duration to add to it
434 C<$return_by_hour> is an integer value representing the opening hour for the branch
436 =head2 get_push_amt
438 my $amt = $calendar->get_push_amt($date)
440 C<$date> is a DateTime object representing a closed return date
442 Using the days_mode syspref value and the nature of the closed return
443 date, return how many days we should jump forward to find another return date
445 =head2 addDays
447 my $dt = $calendar->addDays($date, $dur)
449 C<$date> is a DateTime object representing the starting date of the interval.
451 C<$offset> is a DateTime::Duration to add to it
453 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
455 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
456 parameter will be removed when issuingrules properly cope with that
458 =head2 is_holiday
460 $yesno = $calendar->is_holiday($dt);
462 passed a DateTime object returns 1 if it is a closed day
463 0 if not according to the calendar
465 =head2 days_between
467 $duration = $calendar->days_between($start_dt, $end_dt);
469 Passed two dates returns a DateTime::Duration object measuring the length between them
470 ignoring closed days. Always returns a positive number irrespective of the
471 relative order of the parameters.
473 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
475 =head2 hours_between
477 $duration = $calendar->hours_between($start_dt, $end_dt);
479 Passed two dates returns a DateTime::Duration object measuring the length between them
480 ignoring closed days. Always returns a positive number irrespective of the
481 relative order of the parameters.
483 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
485 =head2 next_open_days
487 $datetime = $calendar->next_open_days($duedate_dt, $to_add)
489 Passed a Datetime and number of days, returns another Datetime representing
490 the next open day after adding the passed number of days. It is intended for
491 use to calculate the due date when useDaysMode syspref is set to either
492 'Datedue', 'Calendar' or 'Dayweek'.
494 =head2 prev_open_days
496 $datetime = $calendar->prev_open_days($duedate_dt, $to_sub)
498 Passed a Datetime and a number of days, returns another Datetime
499 representing the previous open day after subtracting the number of passed
500 days. It is intended for use to calculate the due date when useDaysMode
501 syspref is set to either 'Datedue', 'Calendar' or 'Dayweek'.
503 =head2 days_forward
505 $datetime = $calendar->days_forward($start_dt, $to_add)
507 Passed a Datetime and number of days, returns another Datetime representing
508 the next open day after adding the passed number of days. It is intended for
509 use to calculate the due date when useDaysMode syspref is set to either
510 'Datedue', 'Calendar' or 'Dayweek'.
512 =head2 set_daysmode
514 For testing only allows the calling script to change days mode
516 =head2 clear_weekly_closed_days
518 In test mode changes the testing set of closed days to a new set with
519 no closed days. TODO passing an array of closed days to this would
520 allow testing of more configurations
522 =head2 add_holiday
524 Passed a datetime object this will add it to the calendar's list of
525 closed days. This is for testing so that we can alter the Calenfar object's
526 list of specified dates
528 =head1 DIAGNOSTICS
530 Will croak if not passed a branchcode in new
532 =head1 BUGS AND LIMITATIONS
534 This only contains a limited subset of the functionality in C4::Calendar
535 Only enough to support Staffs Rolling loans
537 =head1 AUTHOR
539 Colin Campbell colin.campbell@ptfs-europe.com
541 =head1 LICENSE AND COPYRIGHT
543 Copyright (c) 2011 PTFS-Europe Ltd All rights reserved
545 Koha is free software; you can redistribute it and/or modify it
546 under the terms of the GNU General Public License as published by
547 the Free Software Foundation; either version 3 of the License, or
548 (at your option) any later version.
550 Koha is distributed in the hope that it will be useful, but
551 WITHOUT ANY WARRANTY; without even the implied warranty of
552 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
553 GNU General Public License for more details.
555 You should have received a copy of the GNU General Public License
556 along with Koha; if not, see <http://www.gnu.org/licenses>.