Bug 19074: Fix category display in Batch patron modification.
[koha.git] / Koha / Calendar.pm
1 package Koha::Calendar;
2 use strict;
3 use warnings;
4 use 5.010;
5
6 use DateTime;
7 use DateTime::Set;
8 use DateTime::Duration;
9 use C4::Context;
10 use Koha::Caches;
11 use Carp;
12
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};
20     }
21     if ( !defined $self->{branchcode} ) {
22         croak 'No branchcode argument passed to Koha::Calendar->new';
23     }
24     $self->_init();
25     return $self;
26 }
27
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'
34     );
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;
39     }
40     my $day_month_closed_days_sth = $dbh->prepare(
41 'SELECT day, month FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NULL'
42     );
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} } =
47           1;
48     }
49
50     $self->{days_mode}       = C4::Context->preference('useDaysMode');
51     $self->{test}            = 0;
52     return;
53 }
54
55 sub exception_holidays {
56     my ( $self ) = @_;
57
58     my $cache  = Koha::Caches->get_instance();
59     my $cached = $cache->get_from_cache('exception_holidays');
60     return $cached if $cached;
61
62     my $dbh = C4::Context->dbh;
63     my $branch = $self->{branchcode};
64     my $exception_holidays_sth = $dbh->prepare(
65 'SELECT day, month, year FROM special_holidays WHERE branchcode = ? AND isexception = 1'
66     );
67     $exception_holidays_sth->execute( $branch );
68     my $dates = [];
69     while ( my ( $day, $month, $year ) = $exception_holidays_sth->fetchrow ) {
70         push @{$dates},
71           DateTime->new(
72             day       => $day,
73             month     => $month,
74             year      => $year,
75             time_zone => "floating",
76           )->truncate( to => 'day' );
77     }
78     $self->{exception_holidays} =
79       DateTime::Set->from_datetimes( dates => $dates );
80     $cache->set_in_cache( 'exception_holidays', $self->{exception_holidays} );
81     return $self->{exception_holidays};
82 }
83
84 sub single_holidays {
85     my ( $self, $date ) = @_;
86     my $branchcode = $self->{branchcode};
87     my $cache           = Koha::Caches->get_instance();
88     my $single_holidays = $cache->get_from_cache('single_holidays');
89
90     # $single_holidays looks like:
91     # {
92     #   CPL =>  [
93     #        [0] 20131122,
94     #         ...
95     #    ],
96     #   ...
97     # }
98
99     unless ($single_holidays) {
100         my $dbh = C4::Context->dbh;
101         $single_holidays = {};
102
103         # push holidays for each branch
104         my $branches_sth =
105           $dbh->prepare('SELECT distinct(branchcode) FROM special_holidays');
106         $branches_sth->execute();
107         while ( my $br = $branches_sth->fetchrow ) {
108             my $single_holidays_sth = $dbh->prepare(
109 'SELECT day, month, year FROM special_holidays WHERE branchcode = ? AND isexception = 0'
110             );
111             $single_holidays_sth->execute($br);
112
113             my @ymd_arr;
114             while ( my ( $day, $month, $year ) =
115                 $single_holidays_sth->fetchrow )
116             {
117                 my $dt = DateTime->new(
118                     day       => $day,
119                     month     => $month,
120                     year      => $year,
121                     time_zone => 'floating',
122                 )->truncate( to => 'day' );
123                 push @ymd_arr, $dt->ymd('');
124             }
125             $single_holidays->{$br} = \@ymd_arr;
126         }    # br
127         $cache->set_in_cache( 'single_holidays', $single_holidays,
128             { expiry => 76800 } )    #24 hrs ;
129     }
130     my $holidays  = ( $single_holidays->{$branchcode} );
131     for my $hols  (@$holidays ) {
132             return 1 if ( $date == $hols )   #match ymds;
133     }
134     return 0;
135 }
136
137 sub addDate {
138     my ( $self, $startdate, $add_duration, $unit ) = @_;
139
140     # Default to days duration (legacy support I guess)
141     if ( ref $add_duration ne 'DateTime::Duration' ) {
142         $add_duration = DateTime::Duration->new( days => $add_duration );
143     }
144
145     $unit ||= 'days'; # default days ?
146     my $dt;
147
148     if ( $unit eq 'hours' ) {
149         # Fixed for legacy support. Should be set as a branch parameter
150         my $return_by_hour = 10;
151
152         $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
153     } else {
154         # days
155         $dt = $self->addDays($startdate, $add_duration);
156     }
157
158     return $dt;
159 }
160
161 sub addHours {
162     my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
163     my $base_date = $startdate->clone();
164
165     $base_date->add_duration($hours_duration);
166
167     # If we are using the calendar behave for now as if Datedue
168     # was the chosen option (current intended behaviour)
169
170     if ( $self->{days_mode} ne 'Days' &&
171           $self->is_holiday($base_date) ) {
172
173         if ( $hours_duration->is_negative() ) {
174             $base_date = $self->prev_open_day($base_date);
175         } else {
176             $base_date = $self->next_open_day($base_date);
177         }
178
179         $base_date->set_hour($return_by_hour);
180
181     }
182
183     return $base_date;
184 }
185
186 sub addDays {
187     my ( $self, $startdate, $days_duration ) = @_;
188     my $base_date = $startdate->clone();
189
190     $self->{days_mode} ||= q{};
191
192     if ( $self->{days_mode} eq 'Calendar' ) {
193         # use the calendar to skip all days the library is closed
194         # when adding
195         my $days = abs $days_duration->in_units('days');
196
197         if ( $days_duration->is_negative() ) {
198             while ($days) {
199                 $base_date = $self->prev_open_day($base_date);
200                 --$days;
201             }
202         } else {
203             while ($days) {
204                 $base_date = $self->next_open_day($base_date);
205                 --$days;
206             }
207         }
208
209     } else { # Days or Datedue
210         # use straight days, then use calendar to push
211         # the date to the next open day if Datedue
212         $base_date->add_duration($days_duration);
213
214         if ( $self->{days_mode} eq 'Datedue' ) {
215             # Datedue, then use the calendar to push
216             # the date to the next open day if holiday
217             if ( $self->is_holiday($base_date) ) {
218
219                 if ( $days_duration->is_negative() ) {
220                     $base_date = $self->prev_open_day($base_date);
221                 } else {
222                     $base_date = $self->next_open_day($base_date);
223                 }
224             }
225         }
226     }
227
228     return $base_date;
229 }
230
231 sub is_holiday {
232     my ( $self, $dt ) = @_;
233
234     my $localdt = $dt->clone();
235     my $day   = $localdt->day;
236     my $month = $localdt->month;
237
238     #Change timezone to "floating" before doing any calculations or comparisons
239     $localdt->set_time_zone("floating");
240     $localdt->truncate( to => 'day' );
241
242
243     if ( $self->exception_holidays->contains($localdt) ) {
244         # exceptions are not holidays
245         return 0;
246     }
247
248     my $dow = $localdt->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;
254     }
255
256     if ( $self->{weekly_closed_days}->[$dow] == 1 ) {
257         return 1;
258     }
259
260     if ( exists $self->{day_month_closed_days}->{$month}->{$day} ) {
261         return 1;
262     }
263
264     my $ymd   = $localdt->ymd('')  ;
265     if ($self->single_holidays(  $ymd  ) == 1 ) {
266         return 1;
267     }
268
269     # damn have to go to work after all
270     return 0;
271 }
272
273 sub next_open_day {
274     my ( $self, $dt ) = @_;
275     my $base_date = $dt->clone();
276
277     $base_date->add(days => 1);
278
279     while ($self->is_holiday($base_date)) {
280         $base_date->add(days => 1);
281     }
282
283     return $base_date;
284 }
285
286 sub prev_open_day {
287     my ( $self, $dt ) = @_;
288     my $base_date = $dt->clone();
289
290     $base_date->add(days => -1);
291
292     while ($self->is_holiday($base_date)) {
293         $base_date->add(days => -1);
294     }
295
296     return $base_date;
297 }
298
299 sub days_forward {
300     my $self     = shift;
301     my $start_dt = shift;
302     my $num_days = shift;
303
304     return $start_dt unless $num_days > 0;
305
306     my $base_dt = $start_dt->clone();
307
308     while ($num_days--) {
309         $base_dt = $self->next_open_day($base_dt);
310     }
311
312     return $base_dt;
313 }
314
315 sub days_between {
316     my $self     = shift;
317     my $start_dt = shift;
318     my $end_dt   = shift;
319
320     if ( $start_dt->compare($end_dt) > 0 ) {
321         # swap dates
322         my $int_dt = $end_dt;
323         $end_dt = $start_dt;
324         $start_dt = $int_dt;
325     }
326
327
328     # start and end should not be closed days
329     my $days = $start_dt->delta_days($end_dt)->delta_days;
330     for (my $dt = $start_dt->clone();
331         $dt <= $end_dt;
332         $dt->add(days => 1)
333     ) {
334         if ($self->is_holiday($dt)) {
335             $days--;
336         }
337     }
338     return DateTime::Duration->new( days => $days );
339
340 }
341
342 sub hours_between {
343     my ($self, $start_date, $end_date) = @_;
344     my $start_dt = $start_date->clone();
345     my $end_dt = $end_date->clone();
346     my $duration = $end_dt->delta_ms($start_dt);
347     $start_dt->truncate( to => 'day' );
348     $end_dt->truncate( to => 'day' );
349     # NB this is a kludge in that it assumes all days are 24 hours
350     # However for hourly loans the logic should be expanded to
351     # take into account open/close times then it would be a duration
352     # of library open hours
353     my $skipped_days = 0;
354     for (my $dt = $start_dt->clone();
355         $dt <= $end_dt;
356         $dt->add(days => 1)
357     ) {
358         if ($self->is_holiday($dt)) {
359             ++$skipped_days;
360         }
361     }
362     if ($skipped_days) {
363         $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days));
364     }
365
366     return $duration;
367
368 }
369
370 sub set_daysmode {
371     my ( $self, $mode ) = @_;
372
373     # if not testing this is a no op
374     if ( $self->{test} ) {
375         $self->{days_mode} = $mode;
376     }
377
378     return;
379 }
380
381 sub clear_weekly_closed_days {
382     my $self = shift;
383     $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ];    # Sunday only
384     return;
385 }
386
387 1;
388 __END__
389
390 =head1 NAME
391
392 Koha::Calendar - Object containing a branches calendar
393
394 =head1 SYNOPSIS
395
396   use Koha::Calendar
397
398   my $c = Koha::Calendar->new( branchcode => 'MAIN' );
399   my $dt = DateTime->now();
400
401   # are we open
402   $open = $c->is_holiday($dt);
403   # when will item be due if loan period = $dur (a DateTime::Duration object)
404   $duedate = $c->addDate($dt,$dur,'days');
405
406
407 =head1 DESCRIPTION
408
409   Implements those features of C4::Calendar needed for Staffs Rolling Loans
410
411 =head1 METHODS
412
413 =head2 new : Create a calendar object
414
415 my $calendar = Koha::Calendar->new( branchcode => 'MAIN' );
416
417 The option branchcode is required
418
419
420 =head2 addDate
421
422     my $dt = $calendar->addDate($date, $dur, $unit)
423
424 C<$date> is a DateTime object representing the starting date of the interval.
425
426 C<$offset> is a DateTime::Duration to add to it
427
428 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
429
430 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
431 parameter will be removed when issuingrules properly cope with that
432
433
434 =head2 addHours
435
436     my $dt = $calendar->addHours($date, $dur, $return_by_hour )
437
438 C<$date> is a DateTime object representing the starting date of the interval.
439
440 C<$offset> is a DateTime::Duration to add to it
441
442 C<$return_by_hour> is an integer value representing the opening hour for the branch
443
444
445 =head2 addDays
446
447     my $dt = $calendar->addDays($date, $dur)
448
449 C<$date> is a DateTime object representing the starting date of the interval.
450
451 C<$offset> is a DateTime::Duration to add to it
452
453 C<$unit> is a string value 'days' or 'hours' toflag granularity of duration
454
455 Currently unit is only used to invoke Staffs return Monday at 10 am rule this
456 parameter will be removed when issuingrules properly cope with that
457
458
459 =head2 single_holidays
460
461 my $rc = $self->single_holidays(  $ymd  );
462
463 Passed a $date in Ymd (yyyymmdd) format -  returns 1 if date is a single_holiday, or 0 if not.
464
465
466 =head2 is_holiday
467
468 $yesno = $calendar->is_holiday($dt);
469
470 passed a DateTime object returns 1 if it is a closed day
471 0 if not according to the calendar
472
473 =head2 days_between
474
475 $duration = $calendar->days_between($start_dt, $end_dt);
476
477 Passed two dates returns a DateTime::Duration object measuring the length between them
478 ignoring closed days. Always returns a positive number irrespective of the
479 relative order of the parameters
480
481 =head2 next_open_day
482
483 $datetime = $calendar->next_open_day($duedate_dt)
484
485 Passed a Datetime returns another Datetime representing the next open day. It is
486 intended for use to calculate the due date when useDaysMode syspref is set to either
487 'Datedue' or 'Calendar'.
488
489 =head2 prev_open_day
490
491 $datetime = $calendar->prev_open_day($duedate_dt)
492
493 Passed a Datetime returns another Datetime representing the previous open day. It is
494 intended for use to calculate the due date when useDaysMode syspref is set to either
495 'Datedue' or 'Calendar'.
496
497 =head2 set_daysmode
498
499 For testing only allows the calling script to change days mode
500
501 =head2 clear_weekly_closed_days
502
503 In test mode changes the testing set of closed days to a new set with
504 no closed days. TODO passing an array of closed days to this would
505 allow testing of more configurations
506
507 =head2 add_holiday
508
509 Passed a datetime object this will add it to the calendar's list of
510 closed days. This is for testing so that we can alter the Calenfar object's
511 list of specified dates
512
513 =head1 DIAGNOSTICS
514
515 Will croak if not passed a branchcode in new
516
517 =head1 BUGS AND LIMITATIONS
518
519 This only contains a limited subset of the functionality in C4::Calendar
520 Only enough to support Staffs Rolling loans
521
522 =head1 AUTHOR
523
524 Colin Campbell colin.campbell@ptfs-europe.com
525
526 =head1 LICENSE AND COPYRIGHT
527
528 Copyright (c) 2011 PTFS-Europe Ltd All rights reserved
529
530 This program is free software: you can redistribute it and/or modify
531 it under the terms of the GNU General Public License as published by
532 the Free Software Foundation, either version 2 of the License, or
533 (at your option) any later version.
534
535 This program is distributed in the hope that it will be useful,
536 but WITHOUT ANY WARRANTY; without even the implied warranty of
537 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
538 GNU General Public License for more details.
539
540 You should have received a copy of the GNU General Public License
541 along with this program.  If not, see <http://www.gnu.org/licenses/>.