322f34b5752e4c6540167fac023e5d34e448fd53
[koha-equinox.git] / Koha / Calendar.pm
1 package Koha::Calendar;
2
3 use Modern::Perl;
4
5 use Carp;
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 exception_holidays {
54     my ( $self ) = @_;
55
56     my $cache              = Koha::Caches->get_instance();
57     my $exception_holidays = $cache->get_from_cache('exception_holidays');
58
59     # Populate the cache is necessary
60     unless ($exception_holidays) {
61         my $dbh = C4::Context->dbh;
62         $exception_holidays = {};
63
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'
67         );
68         $exception_holidays_sth->execute();
69         my $dates = [];
70         while ( my ( $day, $month, $year, $branch ) =
71             $exception_holidays_sth->fetchrow )
72         {
73             my $datestring =
74                 sprintf( "%04d", $year )
75               . sprintf( "%02d", $month )
76               . sprintf( "%02d", $day );
77
78             $exception_holidays->{$branch}->{$datestring} = 1;
79         }
80         $cache->set_in_cache( 'exception_holidays', $exception_holidays,
81             { expiry => 76800 } );
82     }
83
84     return $exception_holidays->{$self->{branchcode}} // {};
85 }
86
87 sub is_exception_holiday {
88     my ( $self, $date ) = @_;
89
90     return 1 if ( $self->exception_holidays->{$date} );
91     return 0;
92 }
93
94 sub single_holidays {
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');
99
100     # $single_holidays looks like:
101     # {
102     #   CPL =>  [
103     #        [0] 20131122,
104     #         ...
105     #    ],
106     #   ...
107     # }
108
109     unless ($single_holidays) {
110         my $dbh = C4::Context->dbh;
111         $single_holidays = {};
112
113         # push holidays for each branch
114         my $branches_sth =
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'
120             );
121             $single_holidays_sth->execute($br);
122
123             my @ymd_arr;
124             while ( my ( $day, $month, $year ) =
125                 $single_holidays_sth->fetchrow )
126             {
127                 my $dt = DateTime->new(
128                     day       => $day,
129                     month     => $month,
130                     year      => $year,
131                     time_zone => 'floating',
132                 )->truncate( to => 'day' );
133                 push @ymd_arr, $dt->ymd('');
134             }
135             $single_holidays->{$br} = \@ymd_arr;
136         }    # br
137         $cache->set_in_cache( 'single_holidays', $single_holidays,
138             { expiry => 76800 } )    #24 hrs ;
139     }
140
141     my $holidays  = ( $single_holidays->{$branchcode} );
142     for my $hols  (@$holidays ) {
143             return 1 if ( $date == $hols )   #match ymds;
144     }
145     return 0;
146 }
147
148 sub addDate {
149     my ( $self, $startdate, $add_duration, $unit ) = @_;
150
151
152     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDate: days_mode")
153         unless exists $self->{days_mode};
154
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 );
158     }
159
160     $unit ||= 'days'; # default days ?
161     my $dt;
162     if ( $unit eq 'hours' ) {
163         # Fixed for legacy support. Should be set as a branch parameter
164         my $return_by_hour = 10;
165
166         $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
167     } else {
168         # days
169         $dt = $self->addDays($startdate, $add_duration);
170     }
171     return $dt;
172 }
173
174 sub addHours {
175     my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
176     my $base_date = $startdate->clone();
177
178     $base_date->add_duration($hours_duration);
179
180     # If we are using the calendar behave for now as if Datedue
181     # was the chosen option (current intended behaviour)
182
183     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addHours: days_mode")
184         unless exists $self->{days_mode};
185
186     if ( $self->{days_mode} ne 'Days' &&
187           $self->is_holiday($base_date) ) {
188
189         if ( $hours_duration->is_negative() ) {
190             $base_date = $self->prev_open_days($base_date, 1);
191         } else {
192             $base_date = $self->next_open_days($base_date, 1);
193         }
194
195         $base_date->set_hour($return_by_hour);
196
197     }
198
199     return $base_date;
200 }
201
202 sub addDays {
203     my ( $self, $startdate, $days_duration ) = @_;
204     my $base_date = $startdate->clone();
205
206     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDays: days_mode")
207         unless exists $self->{days_mode};
208
209     if ( $self->{days_mode} eq 'Calendar' ) {
210         # use the calendar to skip all days the library is closed
211         # when adding
212         my $days = abs $days_duration->in_units('days');
213
214         if ( $days_duration->is_negative() ) {
215             while ($days) {
216                 $base_date = $self->prev_open_days($base_date, 1);
217                 --$days;
218             }
219         } else {
220             while ($days) {
221                 $base_date = $self->next_open_days($base_date, 1);
222                 --$days;
223             }
224         }
225
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);
231
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);
244                 } else {
245                     $base_date = $self->next_open_days($base_date, $push_amt);
246                 }
247             }
248         }
249     }
250
251     return $base_date;
252 }
253
254 sub get_push_amt {
255     my ( $self, $base_date) = @_;
256
257     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_push_amt: days_mode")
258         unless exists $self->{days_mode};
259
260     my $dow = $base_date->day_of_week;
261     # Representation fix
262     # DateTime object dow (1-7) where Monday is 1
263     # Arrays are 0-based where 0 = Sunday, not 7.
264     if ( $dow == 7 ) {
265         $dow = 0;
266     }
267
268     return (
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]
273     ) ? 7 : 1;
274 }
275
276 sub is_holiday {
277     my ( $self, $dt ) = @_;
278
279     my $localdt = $dt->clone();
280     my $day   = $localdt->day;
281     my $month = $localdt->month;
282     my $ymd   = $localdt->ymd('')  ;
283
284     #Change timezone to "floating" before doing any calculations or comparisons
285     $localdt->set_time_zone("floating");
286     $localdt->truncate( to => 'day' );
287
288
289     if ( $self->is_exception_holiday( $ymd ) == 1 ) {
290         # exceptions are not holidays
291         return 0;
292     }
293
294     my $dow = $localdt->day_of_week;
295     # Representation fix
296     # DateTime object dow (1-7) where Monday is 1
297     # Arrays are 0-based where 0 = Sunday, not 7.
298     if ( $dow == 7 ) {
299         $dow = 0;
300     }
301
302     if ( $self->{weekly_closed_days}->[$dow] == 1 ) {
303         return 1;
304     }
305
306     if ( exists $self->{day_month_closed_days}->{$month}->{$day} ) {
307         return 1;
308     }
309
310     if ($self->single_holidays(  $ymd  ) == 1 ) {
311         return 1;
312     }
313
314     # damn have to go to work after all
315     return 0;
316 }
317
318 sub next_open_days {
319     my ( $self, $dt, $to_add ) = @_;
320
321     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->next_open_days: days_mode")
322         unless exists $self->{days_mode};
323
324     my $base_date = $dt->clone();
325
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);
330     }
331     return $base_date;
332 }
333
334 sub prev_open_days {
335     my ( $self, $dt, $to_sub ) = @_;
336
337     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_open_days: days_mode")
338         unless exists $self->{days_mode};
339
340     my $base_date = $dt->clone();
341
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;
345
346     $base_date->add(days => $to_sub);
347
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);
353     }
354
355     return $base_date;
356 }
357
358 sub days_forward {
359     my $self     = shift;
360     my $start_dt = shift;
361     my $num_days = shift;
362
363     Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->days_forward: days_mode")
364         unless exists $self->{days_mode};
365
366     return $start_dt unless $num_days > 0;
367
368     my $base_dt = $start_dt->clone();
369
370     while ($num_days--) {
371         $base_dt = $self->next_open_days($base_dt, 1);
372     }
373
374     return $base_dt;
375 }
376
377 sub days_between {
378     my $self     = shift;
379     my $start_dt = shift;
380     my $end_dt   = shift;
381
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 );
387     }
388
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 );
394     }
395     return DateTime::Duration->new( days => $delta_days );
396 }
397
398 sub hours_between {
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');
402
403     my $duration = $end_dt->delta_ms($start_dt);
404     $start_dt->truncate( to => 'day' );
405     $end_dt->truncate( to => 'day' );
406
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 );
415     }
416
417     if ($skipped_days) {
418         $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days));
419     }
420
421     return $duration;
422 }
423
424 sub set_daysmode {
425     my ( $self, $mode ) = @_;
426
427     # if not testing this is a no op
428     if ( $self->{test} ) {
429         $self->{days_mode} = $mode;
430     }
431
432     return;
433 }
434
435 sub clear_weekly_closed_days {
436     my $self = shift;
437     $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ];    # Sunday only
438     return;
439 }
440
441 1;
442 __END__
443
444 =head1 NAME
445
446 Koha::Calendar - Object containing a branches calendar
447
448 =head1 SYNOPSIS
449
450   use Koha::Calendar
451
452   my $c = Koha::Calendar->new( branchcode => 'MAIN' );
453   my $dt = dt_from_string();
454
455   # are we open
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');
459
460
461 =head1 DESCRIPTION
462
463   Implements those features of C4::Calendar needed for Staffs Rolling Loans
464
465 =head1 METHODS
466
467 =head2 new : Create a calendar object
468
469 my $calendar = Koha::Calendar->new( branchcode => 'MAIN' );
470
471 The option branchcode is required
472
473
474 =head2 addDate
475
476     my $dt = $calendar->addDate($date, $dur, $unit)
477
478 C<$date> is a DateTime object representing the starting date of the interval.
479
480 C<$offset> is a DateTime::Duration to add to it
481
482 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
483
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
486
487
488 =head2 addHours
489
490     my $dt = $calendar->addHours($date, $dur, $return_by_hour )
491
492 C<$date> is a DateTime object representing the starting date of the interval.
493
494 C<$offset> is a DateTime::Duration to add to it
495
496 C<$return_by_hour> is an integer value representing the opening hour for the branch
497
498 =head2 get_push_amt
499
500     my $amt = $calendar->get_push_amt($date)
501
502 C<$date> is a DateTime object representing a closed return date
503
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
506
507 =head2 addDays
508
509     my $dt = $calendar->addDays($date, $dur)
510
511 C<$date> is a DateTime object representing the starting date of the interval.
512
513 C<$offset> is a DateTime::Duration to add to it
514
515 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
516
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
519
520
521 =head2 single_holidays
522
523 my $rc = $self->single_holidays(  $ymd  );
524
525 Passed a $date in Ymd (yyyymmdd) format -  returns 1 if date is a single_holiday, or 0 if not.
526
527 =head2 exception_holidays
528
529 my $exceptions = $self->exception_holidays;
530
531 Returns a hashref of exception holidays for the branch
532
533 =head2 is_exception_holiday
534
535 my $rc = $self->is_exception_holiday( $ymd );
536
537 Passed a $date in Ymd (yyyymmdd) format - returns 1 if the date is an exception_holiday, or 0 if not.
538
539 =head2 is_holiday
540
541 $yesno = $calendar->is_holiday($dt);
542
543 passed a DateTime object returns 1 if it is a closed day
544 0 if not according to the calendar
545
546 =head2 days_between
547
548 $duration = $calendar->days_between($start_dt, $end_dt);
549
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.
553
554 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
555
556 =head2 hours_between
557
558 $duration = $calendar->hours_between($start_dt, $end_dt);
559
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.
563
564 Note: This routine assumes neither the passed start_dt nor end_dt can be a closed day
565
566 =head2 next_open_days
567
568 $datetime = $calendar->next_open_days($duedate_dt, $to_add)
569
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'.
574
575 =head2 prev_open_days
576
577 $datetime = $calendar->prev_open_days($duedate_dt, $to_sub)
578
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'.
583
584 =head2 set_daysmode
585
586 For testing only allows the calling script to change days mode
587
588 =head2 clear_weekly_closed_days
589
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
593
594 =head2 add_holiday
595
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
599
600 =head1 DIAGNOSTICS
601
602 Will croak if not passed a branchcode in new
603
604 =head1 BUGS AND LIMITATIONS
605
606 This only contains a limited subset of the functionality in C4::Calendar
607 Only enough to support Staffs Rolling loans
608
609 =head1 AUTHOR
610
611 Colin Campbell colin.campbell@ptfs-europe.com
612
613 =head1 LICENSE AND COPYRIGHT
614
615 Copyright (c) 2011 PTFS-Europe Ltd All rights reserved
616
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.
621
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.
626
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>.