Bug 15185: Remove Check*Holidays subroutines in C4::Circulation
[koha.git] / Koha / Calendar.pm
bloba0b642b3cc8bfea5986772e23dea9e87b468c276
1 package Koha::Calendar;
2 use strict;
3 use warnings;
4 use 5.010;
6 use DateTime;
7 use DateTime::Set;
8 use DateTime::Duration;
9 use C4::Context;
10 use Koha::Cache;
11 use Carp;
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};
21 if ( !defined $self->{branchcode} ) {
22 croak 'No branchcode argument passed to Koha::Calendar->new';
24 $self->_init();
25 return $self;
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'
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;
40 my $day_month_closed_days_sth = $dbh->prepare(
41 'SELECT day, month FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NULL'
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} } =
50 $self->{days_mode} = C4::Context->preference('useDaysMode');
51 $self->{test} = 0;
52 return;
56 # FIXME: use of package-level variables for caching the holiday
57 # lists breaks persistance engines. As of 2013-12-10, the RM
58 # is allowing this with the expectation that prior to release of
59 # 3.16, bug 8089 will be fixed and we can switch the caching over
60 # to Koha::Cache.
62 our $exception_holidays;
64 sub exception_holidays {
65 my ( $self ) = @_;
66 my $dbh = C4::Context->dbh;
67 my $branch = $self->{branchcode};
68 if ( $exception_holidays ) {
69 $self->{exception_holidays} = $exception_holidays;
70 return $exception_holidays;
72 my $exception_holidays_sth = $dbh->prepare(
73 'SELECT day, month, year FROM special_holidays WHERE branchcode = ? AND isexception = 1'
75 $exception_holidays_sth->execute( $branch );
76 my $dates = [];
77 while ( my ( $day, $month, $year ) = $exception_holidays_sth->fetchrow ) {
78 push @{$dates},
79 DateTime->new(
80 day => $day,
81 month => $month,
82 year => $year,
83 time_zone => C4::Context->tz()
84 )->truncate( to => 'day' );
86 $self->{exception_holidays} =
87 DateTime::Set->from_datetimes( dates => $dates );
88 $exception_holidays = $self->{exception_holidays};
89 return $exception_holidays;
92 sub single_holidays {
93 my ( $self, $date ) = @_;
94 my $branchcode = $self->{branchcode};
95 my $cache = Koha::Cache->get_instance();
96 my $single_holidays = $cache->get_from_cache('single_holidays');
98 # $single_holidays looks like:
99 # {
100 # CPL => [
101 # [0] 20131122,
102 # ...
103 # ],
104 # ...
107 unless ($single_holidays) {
108 my $dbh = C4::Context->dbh;
109 $single_holidays = {};
111 # push holidays for each branch
112 my $branches_sth =
113 $dbh->prepare('SELECT distinct(branchcode) FROM special_holidays');
114 $branches_sth->execute();
115 while ( my $br = $branches_sth->fetchrow ) {
116 my $single_holidays_sth = $dbh->prepare(
117 'SELECT day, month, year FROM special_holidays WHERE branchcode = ? AND isexception = 0'
119 $single_holidays_sth->execute($branchcode);
121 my @ymd_arr;
122 while ( my ( $day, $month, $year ) =
123 $single_holidays_sth->fetchrow )
125 my $dt = DateTime->new(
126 day => $day,
127 month => $month,
128 year => $year,
129 time_zone => C4::Context->tz()
130 )->truncate( to => 'day' );
131 push @ymd_arr, $dt->ymd('');
133 $single_holidays->{$br} = \@ymd_arr;
134 } # br
135 $cache->set_in_cache( 'single_holidays', $single_holidays,
136 76800 ) #24 hrs ;
138 my $holidays = ( $single_holidays->{$branchcode} );
139 for my $hols (@$holidays ) {
140 return 1 if ( $date == $hols ) #match ymds;
142 return 0;
145 sub addDate {
146 my ( $self, $startdate, $add_duration, $unit ) = @_;
148 # Default to days duration (legacy support I guess)
149 if ( ref $add_duration ne 'DateTime::Duration' ) {
150 $add_duration = DateTime::Duration->new( days => $add_duration );
153 $unit ||= 'days'; # default days ?
154 my $dt;
156 if ( $unit eq 'hours' ) {
157 # Fixed for legacy support. Should be set as a branch parameter
158 my $return_by_hour = 10;
160 $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
161 } else {
162 # days
163 $dt = $self->addDays($startdate, $add_duration);
166 return $dt;
169 sub addHours {
170 my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
171 my $base_date = $startdate->clone();
173 $base_date->add_duration($hours_duration);
175 # If we are using the calendar behave for now as if Datedue
176 # was the chosen option (current intended behaviour)
178 if ( $self->{days_mode} ne 'Days' &&
179 $self->is_holiday($base_date) ) {
181 if ( $hours_duration->is_negative() ) {
182 $base_date = $self->prev_open_day($base_date);
183 } else {
184 $base_date = $self->next_open_day($base_date);
187 $base_date->set_hour($return_by_hour);
191 return $base_date;
194 sub addDays {
195 my ( $self, $startdate, $days_duration ) = @_;
196 my $base_date = $startdate->clone();
198 $self->{days_mode} ||= q{};
200 if ( $self->{days_mode} eq 'Calendar' ) {
201 # use the calendar to skip all days the library is closed
202 # when adding
203 my $days = abs $days_duration->in_units('days');
205 if ( $days_duration->is_negative() ) {
206 while ($days) {
207 $base_date = $self->prev_open_day($base_date);
208 --$days;
210 } else {
211 while ($days) {
212 $base_date = $self->next_open_day($base_date);
213 --$days;
217 } else { # Days or Datedue
218 # use straight days, then use calendar to push
219 # the date to the next open day if Datedue
220 $base_date->add_duration($days_duration);
222 if ( $self->{days_mode} eq 'Datedue' ) {
223 # Datedue, then use the calendar to push
224 # the date to the next open day if holiday
225 if ( $self->is_holiday($base_date) ) {
227 if ( $days_duration->is_negative() ) {
228 $base_date = $self->prev_open_day($base_date);
229 } else {
230 $base_date = $self->next_open_day($base_date);
236 return $base_date;
239 sub is_holiday {
240 my ( $self, $dt ) = @_;
242 my $localdt = $dt->clone();
243 my $day = $localdt->day;
244 my $month = $localdt->month;
246 $localdt->truncate( to => 'day' );
249 if ( $self->exception_holidays->contains($localdt) ) {
250 # exceptions are not holidays
251 return 0;
254 my $dow = $localdt->day_of_week;
255 # Representation fix
256 # DateTime object dow (1-7) where Monday is 1
257 # Arrays are 0-based where 0 = Sunday, not 7.
258 if ( $dow == 7 ) {
259 $dow = 0;
262 if ( $self->{weekly_closed_days}->[$dow] == 1 ) {
263 return 1;
266 if ( exists $self->{day_month_closed_days}->{$month}->{$day} ) {
267 return 1;
270 my $ymd = $localdt->ymd('') ;
271 if ($self->single_holidays( $ymd ) == 1 ) {
272 return 1;
275 # damn have to go to work after all
276 return 0;
279 sub next_open_day {
280 my ( $self, $dt ) = @_;
281 my $base_date = $dt->clone();
283 $base_date->add(days => 1);
285 while ($self->is_holiday($base_date)) {
286 $base_date->add(days => 1);
289 return $base_date;
292 sub prev_open_day {
293 my ( $self, $dt ) = @_;
294 my $base_date = $dt->clone();
296 $base_date->add(days => -1);
298 while ($self->is_holiday($base_date)) {
299 $base_date->add(days => -1);
302 return $base_date;
305 sub days_between {
306 my $self = shift;
307 my $start_dt = shift;
308 my $end_dt = shift;
310 if ( $start_dt->compare($end_dt) > 0 ) {
311 # swap dates
312 my $int_dt = $end_dt;
313 $end_dt = $start_dt;
314 $start_dt = $int_dt;
318 # start and end should not be closed days
319 my $days = $start_dt->delta_days($end_dt)->delta_days;
320 for (my $dt = $start_dt->clone();
321 $dt <= $end_dt;
322 $dt->add(days => 1)
324 if ($self->is_holiday($dt)) {
325 $days--;
328 return DateTime::Duration->new( days => $days );
332 sub hours_between {
333 my ($self, $start_date, $end_date) = @_;
334 my $start_dt = $start_date->clone();
335 my $end_dt = $end_date->clone();
336 my $duration = $end_dt->delta_ms($start_dt);
337 $start_dt->truncate( to => 'day' );
338 $end_dt->truncate( to => 'day' );
339 # NB this is a kludge in that it assumes all days are 24 hours
340 # However for hourly loans the logic should be expanded to
341 # take into account open/close times then it would be a duration
342 # of library open hours
343 my $skipped_days = 0;
344 for (my $dt = $start_dt->clone();
345 $dt <= $end_dt;
346 $dt->add(days => 1)
348 if ($self->is_holiday($dt)) {
349 ++$skipped_days;
352 if ($skipped_days) {
353 $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days));
356 return $duration;
360 sub set_daysmode {
361 my ( $self, $mode ) = @_;
363 # if not testing this is a no op
364 if ( $self->{test} ) {
365 $self->{days_mode} = $mode;
368 return;
371 sub clear_weekly_closed_days {
372 my $self = shift;
373 $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ]; # Sunday only
374 return;
378 __END__
380 =head1 NAME
382 Koha::Calendar - Object containing a branches calendar
384 =head1 VERSION
386 This documentation refers to Koha::Calendar version 0.0.1
388 =head1 SYNOPSIS
390 use Koha::Calendar
392 my $c = Koha::Calendar->new( branchcode => 'MAIN' );
393 my $dt = DateTime->now();
395 # are we open
396 $open = $c->is_holiday($dt);
397 # when will item be due if loan period = $dur (a DateTime::Duration object)
398 $duedate = $c->addDate($dt,$dur,'days');
401 =head1 DESCRIPTION
403 Implements those features of C4::Calendar needed for Staffs Rolling Loans
405 =head1 METHODS
407 =head2 new : Create a calendar object
409 my $calendar = Koha::Calendar->new( branchcode => 'MAIN' );
411 The option branchcode is required
414 =head2 addDate
416 my $dt = $calendar->addDate($date, $dur, $unit)
418 C<$date> is a DateTime object representing the starting date of the interval.
420 C<$offset> is a DateTime::Duration to add to it
422 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
424 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
425 parameter will be removed when issuingrules properly cope with that
428 =head2 addHours
430 my $dt = $calendar->addHours($date, $dur, $return_by_hour )
432 C<$date> is a DateTime object representing the starting date of the interval.
434 C<$offset> is a DateTime::Duration to add to it
436 C<$return_by_hour> is an integer value representing the opening hour for the branch
439 =head2 addDays
441 my $dt = $calendar->addDays($date, $dur)
443 C<$date> is a DateTime object representing the starting date of the interval.
445 C<$offset> is a DateTime::Duration to add to it
447 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
449 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
450 parameter will be removed when issuingrules properly cope with that
453 =head2 single_holidays
455 my $rc = $self->single_holidays( $ymd );
457 Passed a $date in Ymd (yyyymmdd) format - returns 1 if date is a single_holiday, or 0 if not.
460 =head2 is_holiday
462 $yesno = $calendar->is_holiday($dt);
464 passed a DateTime object returns 1 if it is a closed day
465 0 if not according to the calendar
467 =head2 days_between
469 $duration = $calendar->days_between($start_dt, $end_dt);
471 Passed two dates returns a DateTime::Duration object measuring the length between them
472 ignoring closed days. Always returns a positive number irrespective of the
473 relative order of the parameters
475 =head2 next_open_day
477 $datetime = $calendar->next_open_day($duedate_dt)
479 Passed a Datetime returns another Datetime representing the next open day. It is
480 intended for use to calculate the due date when useDaysMode syspref is set to either
481 'Datedue' or 'Calendar'.
483 =head2 prev_open_day
485 $datetime = $calendar->prev_open_day($duedate_dt)
487 Passed a Datetime returns another Datetime representing the previous open day. It is
488 intended for use to calculate the due date when useDaysMode syspref is set to either
489 'Datedue' or 'Calendar'.
491 =head2 set_daysmode
493 For testing only allows the calling script to change days mode
495 =head2 clear_weekly_closed_days
497 In test mode changes the testing set of closed days to a new set with
498 no closed days. TODO passing an array of closed days to this would
499 allow testing of more configurations
501 =head2 add_holiday
503 Passed a datetime object this will add it to the calendar's list of
504 closed days. This is for testing so that we can alter the Calenfar object's
505 list of specified dates
507 =head1 DIAGNOSTICS
509 Will croak if not passed a branchcode in new
511 =head1 BUGS AND LIMITATIONS
513 This only contains a limited subset of the functionality in C4::Calendar
514 Only enough to support Staffs Rolling loans
516 =head1 AUTHOR
518 Colin Campbell colin.campbell@ptfs-europe.com
520 =head1 LICENSE AND COPYRIGHT
522 Copyright (c) 2011 PTFS-Europe Ltd All rights reserved
524 This program is free software: you can redistribute it and/or modify
525 it under the terms of the GNU General Public License as published by
526 the Free Software Foundation, either version 2 of the License, or
527 (at your option) any later version.
529 This program is distributed in the hope that it will be useful,
530 but WITHOUT ANY WARRANTY; without even the implied warranty of
531 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
532 GNU General Public License for more details.
534 You should have received a copy of the GNU General Public License
535 along with this program. If not, see <http://www.gnu.org/licenses/>.