Bug 24152: (QA follow-up) Add tests for alternative from and to pars
[koha.git] / Koha / Calendar.pm
blob0b5ac1862d859bbb1bc74509618ee8ea298ebb88
1 package Koha::Calendar;
3 use Modern::Perl;
5 use Carp;
6 use DateTime;
7 use DateTime::Set;
8 use DateTime::Duration;
9 use C4::Context;
10 use Koha::Caches;
11 use Koha::Exceptions;
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->{test} = 0;
51 return;
54 sub exception_holidays {
55 my ( $self ) = @_;
57 my $cache = Koha::Caches->get_instance();
58 my $cached = $cache->get_from_cache('exception_holidays');
59 return $cached if $cached;
61 my $dbh = C4::Context->dbh;
62 my $branch = $self->{branchcode};
63 my $exception_holidays_sth = $dbh->prepare(
64 'SELECT day, month, year FROM special_holidays WHERE branchcode = ? AND isexception = 1'
66 $exception_holidays_sth->execute( $branch );
67 my $dates = [];
68 while ( my ( $day, $month, $year ) = $exception_holidays_sth->fetchrow ) {
69 push @{$dates},
70 DateTime->new(
71 day => $day,
72 month => $month,
73 year => $year,
74 time_zone => "floating",
75 )->truncate( to => 'day' );
77 $self->{exception_holidays} =
78 DateTime::Set->from_datetimes( dates => $dates );
79 $cache->set_in_cache( 'exception_holidays', $self->{exception_holidays} );
80 return $self->{exception_holidays};
83 sub single_holidays {
84 my ( $self, $date ) = @_;
85 my $branchcode = $self->{branchcode};
86 my $cache = Koha::Caches->get_instance();
87 my $single_holidays = $cache->get_from_cache('single_holidays');
89 # $single_holidays looks like:
90 # {
91 # CPL => [
92 # [0] 20131122,
93 # ...
94 # ],
95 # ...
96 # }
98 unless ($single_holidays) {
99 my $dbh = C4::Context->dbh;
100 $single_holidays = {};
102 # push holidays for each branch
103 my $branches_sth =
104 $dbh->prepare('SELECT distinct(branchcode) FROM special_holidays');
105 $branches_sth->execute();
106 while ( my $br = $branches_sth->fetchrow ) {
107 my $single_holidays_sth = $dbh->prepare(
108 'SELECT day, month, year FROM special_holidays WHERE branchcode = ? AND isexception = 0'
110 $single_holidays_sth->execute($br);
112 my @ymd_arr;
113 while ( my ( $day, $month, $year ) =
114 $single_holidays_sth->fetchrow )
116 my $dt = DateTime->new(
117 day => $day,
118 month => $month,
119 year => $year,
120 time_zone => 'floating',
121 )->truncate( to => 'day' );
122 push @ymd_arr, $dt->ymd('');
124 $single_holidays->{$br} = \@ymd_arr;
125 } # br
126 $cache->set_in_cache( 'single_holidays', $single_holidays,
127 { expiry => 76800 } ) #24 hrs ;
129 my $holidays = ( $single_holidays->{$branchcode} );
130 for my $hols (@$holidays ) {
131 return 1 if ( $date == $hols ) #match ymds;
133 return 0;
136 sub addDate {
137 my ( $self, $startdate, $add_duration, $unit ) = @_;
140 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDate: days_mode")
141 unless exists $self->{days_mode};
143 # Default to days duration (legacy support I guess)
144 if ( ref $add_duration ne 'DateTime::Duration' ) {
145 $add_duration = DateTime::Duration->new( days => $add_duration );
148 $unit ||= 'days'; # default days ?
149 my $dt;
150 if ( $unit eq 'hours' ) {
151 # Fixed for legacy support. Should be set as a branch parameter
152 my $return_by_hour = 10;
154 $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
155 } else {
156 # days
157 $dt = $self->addDays($startdate, $add_duration);
159 return $dt;
162 sub addHours {
163 my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
164 my $base_date = $startdate->clone();
166 $base_date->add_duration($hours_duration);
168 # If we are using the calendar behave for now as if Datedue
169 # was the chosen option (current intended behaviour)
171 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addHours: days_mode")
172 unless exists $self->{days_mode};
174 if ( $self->{days_mode} ne 'Days' &&
175 $self->is_holiday($base_date) ) {
177 if ( $hours_duration->is_negative() ) {
178 $base_date = $self->prev_open_days($base_date, 1);
179 } else {
180 $base_date = $self->next_open_days($base_date, 1);
183 $base_date->set_hour($return_by_hour);
187 return $base_date;
190 sub addDays {
191 my ( $self, $startdate, $days_duration ) = @_;
192 my $base_date = $startdate->clone();
194 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDays: days_mode")
195 unless exists $self->{days_mode};
197 if ( $self->{days_mode} eq 'Calendar' ) {
198 # use the calendar to skip all days the library is closed
199 # when adding
200 my $days = abs $days_duration->in_units('days');
202 if ( $days_duration->is_negative() ) {
203 while ($days) {
204 $base_date = $self->prev_open_days($base_date, 1);
205 --$days;
207 } else {
208 while ($days) {
209 $base_date = $self->next_open_days($base_date, 1);
210 --$days;
214 } else { # Days, Datedue or Dayweek
215 # use straight days, then use calendar to push
216 # the date to the next open day as appropriate
217 # if Datedue or Dayweek
218 $base_date->add_duration($days_duration);
220 if ( $self->{days_mode} eq 'Datedue' ||
221 $self->{days_mode} eq 'Dayweek') {
222 # Datedue or Dayweek, then use the calendar to push
223 # the date to the next open day if holiday
224 if ( $self->is_holiday($base_date) ) {
225 my $dow = $base_date->day_of_week;
226 my $days = $days_duration->in_units('days');
227 # Is it a period based on weeks
228 my $push_amt = $days % 7 == 0 ?
229 $self->get_push_amt($base_date) : 1;
230 if ( $days_duration->is_negative() ) {
231 $base_date = $self->prev_open_days($base_date, $push_amt);
232 } else {
233 $base_date = $self->next_open_days($base_date, $push_amt);
239 return $base_date;
242 sub get_push_amt {
243 my ( $self, $base_date) = @_;
245 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_push_amt: days_mode")
246 unless exists $self->{days_mode};
248 my $dow = $base_date->day_of_week;
249 # Representation fix
250 # DateTime object dow (1-7) where Monday is 1
251 # Arrays are 0-based where 0 = Sunday, not 7.
252 if ( $dow == 7 ) {
253 $dow = 0;
256 return (
257 # We're using Dayweek useDaysMode option
258 $self->{days_mode} eq 'Dayweek' &&
259 # It's not a permanently closed day
260 !$self->{weekly_closed_days}->[$dow]
261 ) ? 7 : 1;
264 sub is_holiday {
265 my ( $self, $dt ) = @_;
267 my $localdt = $dt->clone();
268 my $day = $localdt->day;
269 my $month = $localdt->month;
271 #Change timezone to "floating" before doing any calculations or comparisons
272 $localdt->set_time_zone("floating");
273 $localdt->truncate( to => 'day' );
276 if ( $self->exception_holidays->contains($localdt) ) {
277 # exceptions are not holidays
278 return 0;
281 my $dow = $localdt->day_of_week;
282 # Representation fix
283 # DateTime object dow (1-7) where Monday is 1
284 # Arrays are 0-based where 0 = Sunday, not 7.
285 if ( $dow == 7 ) {
286 $dow = 0;
289 if ( $self->{weekly_closed_days}->[$dow] == 1 ) {
290 return 1;
293 if ( exists $self->{day_month_closed_days}->{$month}->{$day} ) {
294 return 1;
297 my $ymd = $localdt->ymd('') ;
298 if ($self->single_holidays( $ymd ) == 1 ) {
299 return 1;
302 # damn have to go to work after all
303 return 0;
306 sub next_open_days {
307 my ( $self, $dt, $to_add ) = @_;
309 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->next_open_days: days_mode")
310 unless exists $self->{days_mode};
312 my $base_date = $dt->clone();
314 $base_date->add(days => $to_add);
315 while ($self->is_holiday($base_date)) {
316 my $add_next = $self->get_push_amt($base_date);
317 $base_date->add(days => $add_next);
319 return $base_date;
322 sub prev_open_days {
323 my ( $self, $dt, $to_sub ) = @_;
325 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_open_days: days_mode")
326 unless exists $self->{days_mode};
328 my $base_date = $dt->clone();
330 # It feels logical to be passed a positive number, though we're
331 # subtracting, so do the right thing
332 $to_sub = $to_sub > 0 ? 0 - $to_sub : $to_sub;
334 $base_date->add(days => $to_sub);
336 while ($self->is_holiday($base_date)) {
337 my $sub_next = $self->get_push_amt($base_date);
338 # Ensure we're subtracting when we need to be
339 $sub_next = $sub_next > 0 ? 0 - $sub_next : $sub_next;
340 $base_date->add(days => $sub_next);
343 return $base_date;
346 sub days_forward {
347 my $self = shift;
348 my $start_dt = shift;
349 my $num_days = shift;
351 Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->days_forward: days_mode")
352 unless exists $self->{days_mode};
354 return $start_dt unless $num_days > 0;
356 my $base_dt = $start_dt->clone();
358 while ($num_days--) {
359 $base_dt = $self->next_open_days($base_dt, 1);
362 return $base_dt;
365 sub days_between {
366 my $self = shift;
367 my $start_dt = shift;
368 my $end_dt = shift;
370 # Change time zone for date math and swap if needed
371 $start_dt = $start_dt->clone->set_time_zone('floating');
372 $end_dt = $end_dt->clone->set_time_zone('floating');
373 if( $start_dt->compare($end_dt) > 0 ) {
374 ( $start_dt, $end_dt ) = ( $end_dt, $start_dt );
377 # start and end should not be closed days
378 my $delta_days = $start_dt->delta_days($end_dt)->delta_days;
379 while( $start_dt->compare($end_dt) < 1 ) {
380 $delta_days-- if $self->is_holiday($start_dt);
381 $start_dt->add( days => 1 );
383 return DateTime::Duration->new( days => $delta_days );
386 sub hours_between {
387 my ($self, $start_date, $end_date) = @_;
388 my $start_dt = $start_date->clone()->set_time_zone('floating');
389 my $end_dt = $end_date->clone()->set_time_zone('floating');
391 my $duration = $end_dt->delta_ms($start_dt);
392 $start_dt->truncate( to => 'day' );
393 $end_dt->truncate( to => 'day' );
395 # NB this is a kludge in that it assumes all days are 24 hours
396 # However for hourly loans the logic should be expanded to
397 # take into account open/close times then it would be a duration
398 # of library open hours
399 my $skipped_days = 0;
400 while( $start_dt->compare($end_dt) < 1 ) {
401 $skipped_days++ if $self->is_holiday($start_dt);
402 $start_dt->add( days => 1 );
405 if ($skipped_days) {
406 $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days));
409 return $duration;
412 sub set_daysmode {
413 my ( $self, $mode ) = @_;
415 # if not testing this is a no op
416 if ( $self->{test} ) {
417 $self->{days_mode} = $mode;
420 return;
423 sub clear_weekly_closed_days {
424 my $self = shift;
425 $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ]; # Sunday only
426 return;
430 __END__
432 =head1 NAME
434 Koha::Calendar - Object containing a branches calendar
436 =head1 SYNOPSIS
438 use Koha::Calendar
440 my $c = Koha::Calendar->new( branchcode => 'MAIN' );
441 my $dt = dt_from_string();
443 # are we open
444 $open = $c->is_holiday($dt);
445 # when will item be due if loan period = $dur (a DateTime::Duration object)
446 $duedate = $c->addDate($dt,$dur,'days');
449 =head1 DESCRIPTION
451 Implements those features of C4::Calendar needed for Staffs Rolling Loans
453 =head1 METHODS
455 =head2 new : Create a calendar object
457 my $calendar = Koha::Calendar->new( branchcode => 'MAIN' );
459 The option branchcode is required
462 =head2 addDate
464 my $dt = $calendar->addDate($date, $dur, $unit)
466 C<$date> is a DateTime object representing the starting date of the interval.
468 C<$offset> is a DateTime::Duration to add to it
470 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
472 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
473 parameter will be removed when issuingrules properly cope with that
476 =head2 addHours
478 my $dt = $calendar->addHours($date, $dur, $return_by_hour )
480 C<$date> is a DateTime object representing the starting date of the interval.
482 C<$offset> is a DateTime::Duration to add to it
484 C<$return_by_hour> is an integer value representing the opening hour for the branch
486 =head2 get_push_amt
488 my $amt = $calendar->get_push_amt($date)
490 C<$date> is a DateTime object representing a closed return date
492 Using the days_mode syspref value and the nature of the closed return
493 date, return how many days we should jump forward to find another return date
495 =head2 addDays
497 my $dt = $calendar->addDays($date, $dur)
499 C<$date> is a DateTime object representing the starting date of the interval.
501 C<$offset> is a DateTime::Duration to add to it
503 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
505 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
506 parameter will be removed when issuingrules properly cope with that
509 =head2 single_holidays
511 my $rc = $self->single_holidays( $ymd );
513 Passed a $date in Ymd (yyyymmdd) format - returns 1 if date is a single_holiday, or 0 if not.
516 =head2 is_holiday
518 $yesno = $calendar->is_holiday($dt);
520 passed a DateTime object returns 1 if it is a closed day
521 0 if not according to the calendar
523 =head2 days_between
525 $duration = $calendar->days_between($start_dt, $end_dt);
527 Passed two dates returns a DateTime::Duration object measuring the length between them
528 ignoring closed days. Always returns a positive number irrespective of the
529 relative order of the parameters.
531 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
533 =head2 hours_between
535 $duration = $calendar->hours_between($start_dt, $end_dt);
537 Passed two dates returns a DateTime::Duration object measuring the length between them
538 ignoring closed days. Always returns a positive number irrespective of the
539 relative order of the parameters.
541 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
543 =head2 next_open_days
545 $datetime = $calendar->next_open_days($duedate_dt, $to_add)
547 Passed a Datetime and number of days, returns another Datetime representing
548 the next open day after adding the passed number of days. It is intended for
549 use to calculate the due date when useDaysMode syspref is set to either
550 'Datedue', 'Calendar' or 'Dayweek'.
552 =head2 prev_open_days
554 $datetime = $calendar->prev_open_days($duedate_dt, $to_sub)
556 Passed a Datetime and a number of days, returns another Datetime
557 representing the previous open day after subtracting the number of passed
558 days. It is intended for use to calculate the due date when useDaysMode
559 syspref is set to either 'Datedue', 'Calendar' or 'Dayweek'.
561 =head2 set_daysmode
563 For testing only allows the calling script to change days mode
565 =head2 clear_weekly_closed_days
567 In test mode changes the testing set of closed days to a new set with
568 no closed days. TODO passing an array of closed days to this would
569 allow testing of more configurations
571 =head2 add_holiday
573 Passed a datetime object this will add it to the calendar's list of
574 closed days. This is for testing so that we can alter the Calenfar object's
575 list of specified dates
577 =head1 DIAGNOSTICS
579 Will croak if not passed a branchcode in new
581 =head1 BUGS AND LIMITATIONS
583 This only contains a limited subset of the functionality in C4::Calendar
584 Only enough to support Staffs Rolling loans
586 =head1 AUTHOR
588 Colin Campbell colin.campbell@ptfs-europe.com
590 =head1 LICENSE AND COPYRIGHT
592 Copyright (c) 2011 PTFS-Europe Ltd All rights reserved
594 Koha is free software; you can redistribute it and/or modify it
595 under the terms of the GNU General Public License as published by
596 the Free Software Foundation; either version 3 of the License, or
597 (at your option) any later version.
599 Koha is distributed in the hope that it will be useful, but
600 WITHOUT ANY WARRANTY; without even the implied warranty of
601 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
602 GNU General Public License for more details.
604 You should have received a copy of the GNU General Public License
605 along with Koha; if not, see <http://www.gnu.org/licenses>.