Bug 26922: Regression tests
[koha.git] / Koha / Calendar.pm
blobc3210d469d7f29bc097df33b0fd723c6e09b1b90
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, MAX(isexception) FROM special_holidays WHERE branchcode = ? GROUP BY day, month, year'
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 ? 0 : 1;
88 $cache->set_in_cache( $key, $holidays, { expiry => 76800 } );
90 return $holidays // {};
93 sub addDate {
94 my ( $self, $startdate, $add_duration, $unit ) = @_;
97 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDate: days_mode")
98 unless exists $self->{days_mode};
100 # Default to days duration (legacy support I guess)
101 if ( ref $add_duration ne 'DateTime::Duration' ) {
102 $add_duration = DateTime::Duration->new( days => $add_duration );
105 $unit ||= 'days'; # default days ?
106 my $dt;
107 if ( $unit eq 'hours' ) {
108 # Fixed for legacy support. Should be set as a branch parameter
109 my $return_by_hour = 10;
111 $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
112 } else {
113 # days
114 $dt = $self->addDays($startdate, $add_duration);
116 return $dt;
119 sub addHours {
120 my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
121 my $base_date = $startdate->clone();
123 $base_date->add_duration($hours_duration);
125 # If we are using the calendar behave for now as if Datedue
126 # was the chosen option (current intended behaviour)
128 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addHours: days_mode")
129 unless exists $self->{days_mode};
131 if ( $self->{days_mode} ne 'Days' &&
132 $self->is_holiday($base_date) ) {
134 if ( $hours_duration->is_negative() ) {
135 $base_date = $self->prev_open_days($base_date, 1);
136 } else {
137 $base_date = $self->next_open_days($base_date, 1);
140 $base_date->set_hour($return_by_hour);
144 return $base_date;
147 sub addDays {
148 my ( $self, $startdate, $days_duration ) = @_;
149 my $base_date = $startdate->clone();
151 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDays: days_mode")
152 unless exists $self->{days_mode};
154 if ( $self->{days_mode} eq 'Calendar' ) {
155 # use the calendar to skip all days the library is closed
156 # when adding
157 my $days = abs $days_duration->in_units('days');
159 if ( $days_duration->is_negative() ) {
160 while ($days) {
161 $base_date = $self->prev_open_days($base_date, 1);
162 --$days;
164 } else {
165 while ($days) {
166 $base_date = $self->next_open_days($base_date, 1);
167 --$days;
171 } else { # Days, Datedue or Dayweek
172 # use straight days, then use calendar to push
173 # the date to the next open day as appropriate
174 # if Datedue or Dayweek
175 $base_date->add_duration($days_duration);
177 if ( $self->{days_mode} eq 'Datedue' ||
178 $self->{days_mode} eq 'Dayweek') {
179 # Datedue or Dayweek, then use the calendar to push
180 # the date to the next open day if holiday
181 if ( $self->is_holiday($base_date) ) {
182 my $dow = $base_date->day_of_week;
183 my $days = $days_duration->in_units('days');
184 # Is it a period based on weeks
185 my $push_amt = $days % 7 == 0 ?
186 $self->get_push_amt($base_date) : 1;
187 if ( $days_duration->is_negative() ) {
188 $base_date = $self->prev_open_days($base_date, $push_amt);
189 } else {
190 $base_date = $self->next_open_days($base_date, $push_amt);
196 return $base_date;
199 sub get_push_amt {
200 my ( $self, $base_date) = @_;
202 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_push_amt: days_mode")
203 unless exists $self->{days_mode};
205 my $dow = $base_date->day_of_week;
206 # Representation fix
207 # DateTime object dow (1-7) where Monday is 1
208 # Arrays are 0-based where 0 = Sunday, not 7.
209 if ( $dow == 7 ) {
210 $dow = 0;
213 return (
214 # We're using Dayweek useDaysMode option
215 $self->{days_mode} eq 'Dayweek' &&
216 # It's not a permanently closed day
217 !$self->{weekly_closed_days}->[$dow]
218 ) ? 7 : 1;
221 sub is_holiday {
222 my ( $self, $dt ) = @_;
224 my $localdt = $dt->clone();
225 my $day = $localdt->day;
226 my $month = $localdt->month;
227 my $ymd = $localdt->ymd('');
229 #Change timezone to "floating" before doing any calculations or comparisons
230 $localdt->set_time_zone("floating");
231 $localdt->truncate( to => 'day' );
233 return $self->_holidays->{$ymd} if defined($self->_holidays->{$ymd});
235 my $dow = $localdt->day_of_week;
236 # Representation fix
237 # DateTime object dow (1-7) where Monday is 1
238 # Arrays are 0-based where 0 = Sunday, not 7.
239 if ( $dow == 7 ) {
240 $dow = 0;
243 if ( $self->{weekly_closed_days}->[$dow] == 1 ) {
244 return 1;
247 if ( exists $self->{day_month_closed_days}->{$month}->{$day} ) {
248 return 1;
251 # damn have to go to work after all
252 return 0;
255 sub next_open_days {
256 my ( $self, $dt, $to_add ) = @_;
258 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->next_open_days: days_mode")
259 unless exists $self->{days_mode};
261 my $base_date = $dt->clone();
263 $base_date->add(days => $to_add);
264 while ($self->is_holiday($base_date)) {
265 my $add_next = $self->get_push_amt($base_date);
266 $base_date->add(days => $add_next);
268 return $base_date;
271 sub prev_open_days {
272 my ( $self, $dt, $to_sub ) = @_;
274 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_open_days: days_mode")
275 unless exists $self->{days_mode};
277 my $base_date = $dt->clone();
279 # It feels logical to be passed a positive number, though we're
280 # subtracting, so do the right thing
281 $to_sub = $to_sub > 0 ? 0 - $to_sub : $to_sub;
283 $base_date->add(days => $to_sub);
285 while ($self->is_holiday($base_date)) {
286 my $sub_next = $self->get_push_amt($base_date);
287 # Ensure we're subtracting when we need to be
288 $sub_next = $sub_next > 0 ? 0 - $sub_next : $sub_next;
289 $base_date->add(days => $sub_next);
292 return $base_date;
295 sub days_forward {
296 my $self = shift;
297 my $start_dt = shift;
298 my $num_days = shift;
300 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->days_forward: days_mode")
301 unless exists $self->{days_mode};
303 return $start_dt unless $num_days > 0;
305 my $base_dt = $start_dt->clone();
307 while ($num_days--) {
308 $base_dt = $self->next_open_days($base_dt, 1);
311 return $base_dt;
314 sub days_between {
315 my $self = shift;
316 my $start_dt = shift;
317 my $end_dt = shift;
319 # Change time zone for date math and swap if needed
320 $start_dt = $start_dt->clone->set_time_zone('floating');
321 $end_dt = $end_dt->clone->set_time_zone('floating');
322 if( $start_dt->compare($end_dt) > 0 ) {
323 ( $start_dt, $end_dt ) = ( $end_dt, $start_dt );
326 # start and end should not be closed days
327 my $delta_days = $start_dt->delta_days($end_dt)->delta_days;
328 while( $start_dt->compare($end_dt) < 1 ) {
329 $delta_days-- if $self->is_holiday($start_dt);
330 $start_dt->add( days => 1 );
332 return DateTime::Duration->new( days => $delta_days );
335 sub hours_between {
336 my ($self, $start_date, $end_date) = @_;
337 my $start_dt = $start_date->clone()->set_time_zone('floating');
338 my $end_dt = $end_date->clone()->set_time_zone('floating');
340 my $duration = $end_dt->delta_ms($start_dt);
341 $start_dt->truncate( to => 'day' );
342 $end_dt->truncate( to => 'day' );
344 # NB this is a kludge in that it assumes all days are 24 hours
345 # However for hourly loans the logic should be expanded to
346 # take into account open/close times then it would be a duration
347 # of library open hours
348 my $skipped_days = 0;
349 while( $start_dt->compare($end_dt) < 1 ) {
350 $skipped_days++ if $self->is_holiday($start_dt);
351 $start_dt->add( days => 1 );
354 if ($skipped_days) {
355 $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days));
358 return $duration;
361 sub set_daysmode {
362 my ( $self, $mode ) = @_;
364 # if not testing this is a no op
365 if ( $self->{test} ) {
366 $self->{days_mode} = $mode;
369 return;
372 sub clear_weekly_closed_days {
373 my $self = shift;
374 $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ]; # Sunday only
375 return;
379 __END__
381 =head1 NAME
383 Koha::Calendar - Object containing a branches calendar
385 =head1 SYNOPSIS
387 use Koha::Calendar
389 my $c = Koha::Calendar->new( branchcode => 'MAIN' );
390 my $dt = dt_from_string();
392 # are we open
393 $open = $c->is_holiday($dt);
394 # when will item be due if loan period = $dur (a DateTime::Duration object)
395 $duedate = $c->addDate($dt,$dur,'days');
398 =head1 DESCRIPTION
400 Implements those features of C4::Calendar needed for Staffs Rolling Loans
402 =head1 METHODS
404 =head2 new : Create a calendar object
406 my $calendar = Koha::Calendar->new( branchcode => 'MAIN' );
408 The option branchcode is required
411 =head2 addDate
413 my $dt = $calendar->addDate($date, $dur, $unit)
415 C<$date> is a DateTime object representing the starting date of the interval.
417 C<$offset> is a DateTime::Duration to add to it
419 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
421 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
422 parameter will be removed when issuingrules properly cope with that
425 =head2 addHours
427 my $dt = $calendar->addHours($date, $dur, $return_by_hour )
429 C<$date> is a DateTime object representing the starting date of the interval.
431 C<$offset> is a DateTime::Duration to add to it
433 C<$return_by_hour> is an integer value representing the opening hour for the branch
435 =head2 get_push_amt
437 my $amt = $calendar->get_push_amt($date)
439 C<$date> is a DateTime object representing a closed return date
441 Using the days_mode syspref value and the nature of the closed return
442 date, return how many days we should jump forward to find another return date
444 =head2 addDays
446 my $dt = $calendar->addDays($date, $dur)
448 C<$date> is a DateTime object representing the starting date of the interval.
450 C<$offset> is a DateTime::Duration to add to it
452 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
454 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
455 parameter will be removed when issuingrules properly cope with that
457 =head2 is_holiday
459 $yesno = $calendar->is_holiday($dt);
461 passed a DateTime object returns 1 if it is a closed day
462 0 if not according to the calendar
464 =head2 days_between
466 $duration = $calendar->days_between($start_dt, $end_dt);
468 Passed two dates returns a DateTime::Duration object measuring the length between them
469 ignoring closed days. Always returns a positive number irrespective of the
470 relative order of the parameters.
472 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
474 =head2 hours_between
476 $duration = $calendar->hours_between($start_dt, $end_dt);
478 Passed two dates returns a DateTime::Duration object measuring the length between them
479 ignoring closed days. Always returns a positive number irrespective of the
480 relative order of the parameters.
482 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
484 =head2 next_open_days
486 $datetime = $calendar->next_open_days($duedate_dt, $to_add)
488 Passed a Datetime and number of days, returns another Datetime representing
489 the next open day after adding the passed number of days. It is intended for
490 use to calculate the due date when useDaysMode syspref is set to either
491 'Datedue', 'Calendar' or 'Dayweek'.
493 =head2 prev_open_days
495 $datetime = $calendar->prev_open_days($duedate_dt, $to_sub)
497 Passed a Datetime and a number of days, returns another Datetime
498 representing the previous open day after subtracting the number of passed
499 days. It is intended for use to calculate the due date when useDaysMode
500 syspref is set to either 'Datedue', 'Calendar' or 'Dayweek'.
502 =head2 days_forward
504 $datetime = $calendar->days_forward($start_dt, $to_add)
506 Passed a Datetime and number of days, returns another Datetime representing
507 the next open day after adding the passed number of days. It is intended for
508 use to calculate the due date when useDaysMode syspref is set to either
509 'Datedue', 'Calendar' or 'Dayweek'.
511 =head2 set_daysmode
513 For testing only allows the calling script to change days mode
515 =head2 clear_weekly_closed_days
517 In test mode changes the testing set of closed days to a new set with
518 no closed days. TODO passing an array of closed days to this would
519 allow testing of more configurations
521 =head2 add_holiday
523 Passed a datetime object this will add it to the calendar's list of
524 closed days. This is for testing so that we can alter the Calenfar object's
525 list of specified dates
527 =head1 DIAGNOSTICS
529 Will croak if not passed a branchcode in new
531 =head1 BUGS AND LIMITATIONS
533 This only contains a limited subset of the functionality in C4::Calendar
534 Only enough to support Staffs Rolling loans
536 =head1 AUTHOR
538 Colin Campbell colin.campbell@ptfs-europe.com
540 =head1 LICENSE AND COPYRIGHT
542 Copyright (c) 2011 PTFS-Europe Ltd All rights reserved
544 Koha is free software; you can redistribute it and/or modify it
545 under the terms of the GNU General Public License as published by
546 the Free Software Foundation; either version 3 of the License, or
547 (at your option) any later version.
549 Koha is distributed in the hope that it will be useful, but
550 WITHOUT ANY WARRANTY; without even the implied warranty of
551 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
552 GNU General Public License for more details.
554 You should have received a copy of the GNU General Public License
555 along with Koha; if not, see <http://www.gnu.org/licenses>.