Bug 20473: Whitespace
[koha.git] / Koha / Calendar.pm
1 package Koha::Calendar;
2
3 use Modern::Perl;
4
5 use Carp qw( croak );
6 use DateTime;
7 use DateTime::Duration;
8 use C4::Context;
9 use Koha::Caches;
10 use Koha::Exceptions;
11
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};
19     }
20     if ( !defined $self->{branchcode} ) {
21         croak 'No branchcode argument passed to Koha::Calendar->new';
22     }
23     $self->_init();
24     return $self;
25 }
26
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'
33     );
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;
38     }
39     my $day_month_closed_days_sth = $dbh->prepare(
40 'SELECT day, month FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NULL'
41     );
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} } =
46           1;
47     }
48
49     $self->{test}            = 0;
50     return;
51 }
52
53 sub _holidays {
54     my ($self) = @_;
55
56     my $key      = $self->{branchcode} . "_holidays";
57     my $cache    = Koha::Caches->get_instance();
58     my $holidays = $cache->get_from_cache($key);
59
60     # $holidays looks like:
61     # {
62     #    20131122 => 1, # single_holiday
63     #    20131123 => 0, # exception_holiday
64     #    ...
65     # }
66
67     # Populate the cache if necessary
68     unless ($holidays) {
69         my $dbh = C4::Context->dbh;
70         $holidays = {};
71
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'
75         );
76         $holidays_sth->execute($self->{branchcode});
77
78         while ( my ( $day, $month, $year, $exception ) =
79             $holidays_sth->fetchrow )
80         {
81             my $datestring =
82                 sprintf( "%04d", $year )
83               . sprintf( "%02d", $month )
84               . sprintf( "%02d", $day );
85
86             $holidays->{$datestring} = $exception ? 0 : 1;
87         }
88         $cache->set_in_cache( $key, $holidays, { expiry => 76800 } );
89     }
90     return $holidays // {};
91 }
92
93 sub addDuration {
94     my ( $self, $startdate, $add_duration, $unit ) = @_;
95
96
97     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDuration: days_mode")
98         unless exists $self->{days_mode};
99
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 );
103     }
104
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;
110
111         $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
112     } else {
113         # days
114         $dt = $self->addDays($startdate, $add_duration);
115     }
116     return $dt;
117 }
118
119 sub addHours {
120     my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
121     my $base_date = $startdate->clone();
122
123     $base_date->add_duration($hours_duration);
124
125     # If we are using the calendar behave for now as if Datedue
126     # was the chosen option (current intended behaviour)
127
128     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addHours: days_mode")
129         unless exists $self->{days_mode};
130
131     if ( $self->{days_mode} ne 'Days' &&
132           $self->is_holiday($base_date) ) {
133
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);
138         }
139
140         $base_date->set_hour($return_by_hour);
141
142     }
143
144     return $base_date;
145 }
146
147 sub addDays {
148     my ( $self, $startdate, $days_duration ) = @_;
149     my $base_date = $startdate->clone();
150
151     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDays: days_mode")
152         unless exists $self->{days_mode};
153
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');
158
159         if ( $days_duration->is_negative() ) {
160             while ($days) {
161                 $base_date = $self->prev_open_days($base_date, 1);
162                 --$days;
163             }
164         } else {
165             while ($days) {
166                 $base_date = $self->next_open_days($base_date, 1);
167                 --$days;
168             }
169         }
170
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);
176
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);
191                 }
192             }
193         }
194     }
195
196     return $base_date;
197 }
198
199 sub get_push_amt {
200     my ( $self, $base_date) = @_;
201
202     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_push_amt: days_mode")
203         unless exists $self->{days_mode};
204
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;
211     }
212
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;
219 }
220
221 sub is_holiday {
222     my ( $self, $dt ) = @_;
223
224     my $localdt = $dt->clone();
225     my $day   = $localdt->day;
226     my $month = $localdt->month;
227     my $ymd   = $localdt->ymd('');
228
229     #Change timezone to "floating" before doing any calculations or comparisons
230     $localdt->set_time_zone("floating");
231     $localdt->truncate( to => 'day' );
232
233     return $self->_holidays->{$ymd} if defined($self->_holidays->{$ymd});
234
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;
241     }
242
243     if ( $self->{weekly_closed_days}->[$dow] == 1 ) {
244         return 1;
245     }
246
247     if ( exists $self->{day_month_closed_days}->{$month}->{$day} ) {
248         return 1;
249     }
250
251     # damn have to go to work after all
252     return 0;
253 }
254
255 sub next_open_days {
256     my ( $self, $dt, $to_add ) = @_;
257
258     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->next_open_days: days_mode")
259         unless exists $self->{days_mode};
260
261     my $base_date = $dt->clone();
262
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);
267     }
268     return $base_date;
269 }
270
271 sub prev_open_days {
272     my ( $self, $dt, $to_sub ) = @_;
273
274     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_open_days: days_mode")
275         unless exists $self->{days_mode};
276
277     my $base_date = $dt->clone();
278
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;
282
283     $base_date->add(days => $to_sub);
284
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);
290     }
291
292     return $base_date;
293 }
294
295 sub days_forward {
296     my $self     = shift;
297     my $start_dt = shift;
298     my $num_days = shift;
299
300     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->days_forward: days_mode")
301         unless exists $self->{days_mode};
302
303     return $start_dt unless $num_days > 0;
304
305     my $base_dt = $start_dt->clone();
306
307     while ($num_days--) {
308         $base_dt = $self->next_open_days($base_dt, 1);
309     }
310
311     return $base_dt;
312 }
313
314 sub days_between {
315     my $self     = shift;
316     my $start_dt = shift;
317     my $end_dt   = shift;
318
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 );
324     }
325
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 );
331     }
332     return DateTime::Duration->new( days => $delta_days );
333 }
334
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');
339
340     my $duration = $end_dt->delta_ms($start_dt);
341     $start_dt->truncate( to => 'day' );
342     $end_dt->truncate( to => 'day' );
343
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 );
352     }
353
354     if ($skipped_days) {
355         $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days));
356     }
357
358     return $duration;
359 }
360
361 sub set_daysmode {
362     my ( $self, $mode ) = @_;
363
364     # if not testing this is a no op
365     if ( $self->{test} ) {
366         $self->{days_mode} = $mode;
367     }
368
369     return;
370 }
371
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;
376 }
377
378 1;
379 __END__
380
381 =head1 NAME
382
383 Koha::Calendar - Object containing a branches calendar
384
385 =head1 SYNOPSIS
386
387   use Koha::Calendar
388
389   my $c = Koha::Calendar->new( branchcode => 'MAIN' );
390   my $dt = dt_from_string();
391
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->addDuration($dt,$dur,'days');
396
397
398 =head1 DESCRIPTION
399
400   Implements those features of C4::Calendar needed for Staffs Rolling Loans
401
402 =head1 METHODS
403
404 =head2 new : Create a calendar object
405
406 my $calendar = Koha::Calendar->new( branchcode => 'MAIN' );
407
408 The option branchcode is required
409
410
411 =head2 addDuration
412
413     my $dt = $calendar->addDuration($date, $dur, $unit)
414
415 C<$date> is a DateTime object representing the starting date of the interval.
416
417 C<$offset> is a DateTime::Duration to add to it
418
419 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
420
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
423
424
425 =head2 addHours
426
427     my $dt = $calendar->addHours($date, $dur, $return_by_hour )
428
429 C<$date> is a DateTime object representing the starting date of the interval.
430
431 C<$offset> is a DateTime::Duration to add to it
432
433 C<$return_by_hour> is an integer value representing the opening hour for the branch
434
435 =head2 get_push_amt
436
437     my $amt = $calendar->get_push_amt($date)
438
439 C<$date> is a DateTime object representing a closed return date
440
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
443
444 =head2 addDays
445
446     my $dt = $calendar->addDays($date, $dur)
447
448 C<$date> is a DateTime object representing the starting date of the interval.
449
450 C<$offset> is a DateTime::Duration to add to it
451
452 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
453
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
456
457 =head2 is_holiday
458
459 $yesno = $calendar->is_holiday($dt);
460
461 passed a DateTime object returns 1 if it is a closed day
462 0 if not according to the calendar
463
464 =head2 days_between
465
466 $duration = $calendar->days_between($start_dt, $end_dt);
467
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.
471
472 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
473
474 =head2 hours_between
475
476 $duration = $calendar->hours_between($start_dt, $end_dt);
477
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.
481
482 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
483
484 =head2 next_open_days
485
486 $datetime = $calendar->next_open_days($duedate_dt, $to_add)
487
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'.
492
493 =head2 prev_open_days
494
495 $datetime = $calendar->prev_open_days($duedate_dt, $to_sub)
496
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'.
501
502 =head2 days_forward
503
504 $datetime = $calendar->days_forward($start_dt, $to_add)
505
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'.
510
511 =head2 set_daysmode
512
513 For testing only allows the calling script to change days mode
514
515 =head2 clear_weekly_closed_days
516
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
520
521 =head2 add_holiday
522
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
526
527 =head1 DIAGNOSTICS
528
529 Will croak if not passed a branchcode in new
530
531 =head1 BUGS AND LIMITATIONS
532
533 This only contains a limited subset of the functionality in C4::Calendar
534 Only enough to support Staffs Rolling loans
535
536 =head1 AUTHOR
537
538 Colin Campbell colin.campbell@ptfs-europe.com
539
540 =head1 LICENSE AND COPYRIGHT
541
542 Copyright (c) 2011 PTFS-Europe Ltd All rights reserved
543
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.
548
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.
553
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>.