1 package Koha::Calendar;
7 use DateTime::Duration;
13 my ( $classname, %options ) = @_;
15 bless $self, $classname;
16 for my $o_name ( keys %options ) {
18 $self->{$o} = $options{$o_name};
20 if ( !defined $self->{branchcode} ) {
21 croak 'No branchcode argument passed to Koha::Calendar->new';
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} } =
53 sub exception_holidays {
56 my $cache = Koha::Caches->get_instance();
57 my $exception_holidays = $cache->get_from_cache('exception_holidays');
59 # Populate the cache is necessary
60 unless ($exception_holidays) {
61 my $dbh = C4::Context->dbh;
62 $exception_holidays = {};
64 # Push holidays for each branch
65 my $exception_holidays_sth = $dbh->prepare(
66 'SELECT day, month, year, branchcode FROM special_holidays WHERE isexception = 1'
68 $exception_holidays_sth->execute();
70 while ( my ( $day, $month, $year, $branch ) =
71 $exception_holidays_sth->fetchrow )
74 sprintf( "%04d", $year )
75 . sprintf( "%02d", $month )
76 . sprintf( "%02d", $day );
78 $exception_holidays->{$branch}->{$datestring} = 1;
80 $cache->set_in_cache( 'exception_holidays', $exception_holidays,
81 { expiry => 76800 } );
84 return $exception_holidays->{$self->{branchcode}} // {};
87 sub is_exception_holiday {
88 my ( $self, $date ) = @_;
90 return 1 if ( $self->exception_holidays->{$date} );
95 my ( $self, $date ) = @_;
96 my $branchcode = $self->{branchcode};
97 my $cache = Koha::Caches->get_instance();
98 my $single_holidays = $cache->get_from_cache('single_holidays');
100 # $single_holidays looks like:
109 unless ($single_holidays) {
110 my $dbh = C4::Context->dbh;
111 $single_holidays = {};
113 # push holidays for each branch
115 $dbh->prepare('SELECT distinct(branchcode) FROM special_holidays');
116 $branches_sth->execute();
117 while ( my $br = $branches_sth->fetchrow ) {
118 my $single_holidays_sth = $dbh->prepare(
119 'SELECT day, month, year FROM special_holidays WHERE branchcode = ? AND isexception = 0'
121 $single_holidays_sth->execute($br);
124 while ( my ( $day, $month, $year ) =
125 $single_holidays_sth->fetchrow )
127 my $dt = DateTime->new(
131 time_zone => 'floating',
132 )->truncate( to => 'day' );
133 push @ymd_arr, $dt->ymd('');
135 $single_holidays->{$br} = \@ymd_arr;
137 $cache->set_in_cache( 'single_holidays', $single_holidays,
138 { expiry => 76800 } ) #24 hrs ;
141 my $holidays = ( $single_holidays->{$branchcode} );
142 for my $hols (@$holidays ) {
143 return 1 if ( $date == $hols ) #match ymds;
149 my ( $self, $startdate, $add_duration, $unit ) = @_;
152 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDate: days_mode")
153 unless exists $self->{days_mode};
155 # Default to days duration (legacy support I guess)
156 if ( ref $add_duration ne 'DateTime::Duration' ) {
157 $add_duration = DateTime::Duration->new( days => $add_duration );
160 $unit ||= 'days'; # default days ?
162 if ( $unit eq 'hours' ) {
163 # Fixed for legacy support. Should be set as a branch parameter
164 my $return_by_hour = 10;
166 $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
169 $dt = $self->addDays($startdate, $add_duration);
175 my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
176 my $base_date = $startdate->clone();
178 $base_date->add_duration($hours_duration);
180 # If we are using the calendar behave for now as if Datedue
181 # was the chosen option (current intended behaviour)
183 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addHours: days_mode")
184 unless exists $self->{days_mode};
186 if ( $self->{days_mode} ne 'Days' &&
187 $self->is_holiday($base_date) ) {
189 if ( $hours_duration->is_negative() ) {
190 $base_date = $self->prev_open_days($base_date, 1);
192 $base_date = $self->next_open_days($base_date, 1);
195 $base_date->set_hour($return_by_hour);
203 my ( $self, $startdate, $days_duration ) = @_;
204 my $base_date = $startdate->clone();
206 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDays: days_mode")
207 unless exists $self->{days_mode};
209 if ( $self->{days_mode} eq 'Calendar' ) {
210 # use the calendar to skip all days the library is closed
212 my $days = abs $days_duration->in_units('days');
214 if ( $days_duration->is_negative() ) {
216 $base_date = $self->prev_open_days($base_date, 1);
221 $base_date = $self->next_open_days($base_date, 1);
226 } else { # Days, Datedue or Dayweek
227 # use straight days, then use calendar to push
228 # the date to the next open day as appropriate
229 # if Datedue or Dayweek
230 $base_date->add_duration($days_duration);
232 if ( $self->{days_mode} eq 'Datedue' ||
233 $self->{days_mode} eq 'Dayweek') {
234 # Datedue or Dayweek, then use the calendar to push
235 # the date to the next open day if holiday
236 if ( $self->is_holiday($base_date) ) {
237 my $dow = $base_date->day_of_week;
238 my $days = $days_duration->in_units('days');
239 # Is it a period based on weeks
240 my $push_amt = $days % 7 == 0 ?
241 $self->get_push_amt($base_date) : 1;
242 if ( $days_duration->is_negative() ) {
243 $base_date = $self->prev_open_days($base_date, $push_amt);
245 $base_date = $self->next_open_days($base_date, $push_amt);
255 my ( $self, $base_date) = @_;
257 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_push_amt: days_mode")
258 unless exists $self->{days_mode};
260 my $dow = $base_date->day_of_week;
262 # DateTime object dow (1-7) where Monday is 1
263 # Arrays are 0-based where 0 = Sunday, not 7.
269 # We're using Dayweek useDaysMode option
270 $self->{days_mode} eq 'Dayweek' &&
271 # It's not a permanently closed day
272 !$self->{weekly_closed_days}->[$dow]
277 my ( $self, $dt ) = @_;
279 my $localdt = $dt->clone();
280 my $day = $localdt->day;
281 my $month = $localdt->month;
282 my $ymd = $localdt->ymd('') ;
284 #Change timezone to "floating" before doing any calculations or comparisons
285 $localdt->set_time_zone("floating");
286 $localdt->truncate( to => 'day' );
289 if ( $self->is_exception_holiday( $ymd ) == 1 ) {
290 # exceptions are not holidays
294 my $dow = $localdt->day_of_week;
296 # DateTime object dow (1-7) where Monday is 1
297 # Arrays are 0-based where 0 = Sunday, not 7.
302 if ( $self->{weekly_closed_days}->[$dow] == 1 ) {
306 if ( exists $self->{day_month_closed_days}->{$month}->{$day} ) {
310 if ($self->single_holidays( $ymd ) == 1 ) {
314 # damn have to go to work after all
319 my ( $self, $dt, $to_add ) = @_;
321 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->next_open_days: days_mode")
322 unless exists $self->{days_mode};
324 my $base_date = $dt->clone();
326 $base_date->add(days => $to_add);
327 while ($self->is_holiday($base_date)) {
328 my $add_next = $self->get_push_amt($base_date);
329 $base_date->add(days => $add_next);
335 my ( $self, $dt, $to_sub ) = @_;
337 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_open_days: days_mode")
338 unless exists $self->{days_mode};
340 my $base_date = $dt->clone();
342 # It feels logical to be passed a positive number, though we're
343 # subtracting, so do the right thing
344 $to_sub = $to_sub > 0 ? 0 - $to_sub : $to_sub;
346 $base_date->add(days => $to_sub);
348 while ($self->is_holiday($base_date)) {
349 my $sub_next = $self->get_push_amt($base_date);
350 # Ensure we're subtracting when we need to be
351 $sub_next = $sub_next > 0 ? 0 - $sub_next : $sub_next;
352 $base_date->add(days => $sub_next);
360 my $start_dt = shift;
361 my $num_days = shift;
363 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->days_forward: days_mode")
364 unless exists $self->{days_mode};
366 return $start_dt unless $num_days > 0;
368 my $base_dt = $start_dt->clone();
370 while ($num_days--) {
371 $base_dt = $self->next_open_days($base_dt, 1);
379 my $start_dt = shift;
382 # Change time zone for date math and swap if needed
383 $start_dt = $start_dt->clone->set_time_zone('floating');
384 $end_dt = $end_dt->clone->set_time_zone('floating');
385 if( $start_dt->compare($end_dt) > 0 ) {
386 ( $start_dt, $end_dt ) = ( $end_dt, $start_dt );
389 # start and end should not be closed days
390 my $delta_days = $start_dt->delta_days($end_dt)->delta_days;
391 while( $start_dt->compare($end_dt) < 1 ) {
392 $delta_days-- if $self->is_holiday($start_dt);
393 $start_dt->add( days => 1 );
395 return DateTime::Duration->new( days => $delta_days );
399 my ($self, $start_date, $end_date) = @_;
400 my $start_dt = $start_date->clone()->set_time_zone('floating');
401 my $end_dt = $end_date->clone()->set_time_zone('floating');
403 my $duration = $end_dt->delta_ms($start_dt);
404 $start_dt->truncate( to => 'day' );
405 $end_dt->truncate( to => 'day' );
407 # NB this is a kludge in that it assumes all days are 24 hours
408 # However for hourly loans the logic should be expanded to
409 # take into account open/close times then it would be a duration
410 # of library open hours
411 my $skipped_days = 0;
412 while( $start_dt->compare($end_dt) < 1 ) {
413 $skipped_days++ if $self->is_holiday($start_dt);
414 $start_dt->add( days => 1 );
418 $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days));
425 my ( $self, $mode ) = @_;
427 # if not testing this is a no op
428 if ( $self->{test} ) {
429 $self->{days_mode} = $mode;
435 sub clear_weekly_closed_days {
437 $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ]; # Sunday only
446 Koha::Calendar - Object containing a branches calendar
452 my $c = Koha::Calendar->new( branchcode => 'MAIN' );
453 my $dt = dt_from_string();
456 $open = $c->is_holiday($dt);
457 # when will item be due if loan period = $dur (a DateTime::Duration object)
458 $duedate = $c->addDate($dt,$dur,'days');
463 Implements those features of C4::Calendar needed for Staffs Rolling Loans
467 =head2 new : Create a calendar object
469 my $calendar = Koha::Calendar->new( branchcode => 'MAIN' );
471 The option branchcode is required
476 my $dt = $calendar->addDate($date, $dur, $unit)
478 C<$date> is a DateTime object representing the starting date of the interval.
480 C<$offset> is a DateTime::Duration to add to it
482 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
484 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
485 parameter will be removed when issuingrules properly cope with that
490 my $dt = $calendar->addHours($date, $dur, $return_by_hour )
492 C<$date> is a DateTime object representing the starting date of the interval.
494 C<$offset> is a DateTime::Duration to add to it
496 C<$return_by_hour> is an integer value representing the opening hour for the branch
500 my $amt = $calendar->get_push_amt($date)
502 C<$date> is a DateTime object representing a closed return date
504 Using the days_mode syspref value and the nature of the closed return
505 date, return how many days we should jump forward to find another return date
509 my $dt = $calendar->addDays($date, $dur)
511 C<$date> is a DateTime object representing the starting date of the interval.
513 C<$offset> is a DateTime::Duration to add to it
515 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
517 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
518 parameter will be removed when issuingrules properly cope with that
521 =head2 single_holidays
523 my $rc = $self->single_holidays( $ymd );
525 Passed a $date in Ymd (yyyymmdd) format - returns 1 if date is a single_holiday, or 0 if not.
527 =head2 exception_holidays
529 my $exceptions = $self->exception_holidays;
531 Returns a hashref of exception holidays for the branch
533 =head2 is_exception_holiday
535 my $rc = $self->is_exception_holiday( $ymd );
537 Passed a $date in Ymd (yyyymmdd) format - returns 1 if the date is an exception_holiday, or 0 if not.
541 $yesno = $calendar->is_holiday($dt);
543 passed a DateTime object returns 1 if it is a closed day
544 0 if not according to the calendar
548 $duration = $calendar->days_between($start_dt, $end_dt);
550 Passed two dates returns a DateTime::Duration object measuring the length between them
551 ignoring closed days. Always returns a positive number irrespective of the
552 relative order of the parameters.
554 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
558 $duration = $calendar->hours_between($start_dt, $end_dt);
560 Passed two dates returns a DateTime::Duration object measuring the length between them
561 ignoring closed days. Always returns a positive number irrespective of the
562 relative order of the parameters.
564 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
566 =head2 next_open_days
568 $datetime = $calendar->next_open_days($duedate_dt, $to_add)
570 Passed a Datetime and number of days, returns another Datetime representing
571 the next open day after adding the passed number of days. It is intended for
572 use to calculate the due date when useDaysMode syspref is set to either
573 'Datedue', 'Calendar' or 'Dayweek'.
575 =head2 prev_open_days
577 $datetime = $calendar->prev_open_days($duedate_dt, $to_sub)
579 Passed a Datetime and a number of days, returns another Datetime
580 representing the previous open day after subtracting the number of passed
581 days. It is intended for use to calculate the due date when useDaysMode
582 syspref is set to either 'Datedue', 'Calendar' or 'Dayweek'.
586 For testing only allows the calling script to change days mode
588 =head2 clear_weekly_closed_days
590 In test mode changes the testing set of closed days to a new set with
591 no closed days. TODO passing an array of closed days to this would
592 allow testing of more configurations
596 Passed a datetime object this will add it to the calendar's list of
597 closed days. This is for testing so that we can alter the Calenfar object's
598 list of specified dates
602 Will croak if not passed a branchcode in new
604 =head1 BUGS AND LIMITATIONS
606 This only contains a limited subset of the functionality in C4::Calendar
607 Only enough to support Staffs Rolling loans
611 Colin Campbell colin.campbell@ptfs-europe.com
613 =head1 LICENSE AND COPYRIGHT
615 Copyright (c) 2011 PTFS-Europe Ltd All rights reserved
617 Koha is free software; you can redistribute it and/or modify it
618 under the terms of the GNU General Public License as published by
619 the Free Software Foundation; either version 3 of the License, or
620 (at your option) any later version.
622 Koha is distributed in the hope that it will be useful, but
623 WITHOUT ANY WARRANTY; without even the implied warranty of
624 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
625 GNU General Public License for more details.
627 You should have received a copy of the GNU General Public License
628 along with Koha; if not, see <http://www.gnu.org/licenses>.