C4::Calendar::addDate now handles negative offsets properly.
[koha.git] / C4 / Calendar.pm
1 package C4::Calendar;
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
16 # Suite 330, Boston, MA  02111-1307 USA
17
18 use strict;
19 require Exporter;
20 use vars qw($VERSION @EXPORT);
21
22 #use Date::Manip;
23 # use Date::Calc;
24
25 # set the version for version checking
26 $VERSION = 3.00;
27
28 =head1 NAME
29
30 C4::Calendar::Calendar - Koha module dealing with holidays.
31
32 =head1 SYNOPSIS
33
34     use C4::Calendar::Calendar;
35
36 =head1 DESCRIPTION
37
38 This package is used to deal with holidays. Through this package, you can set all kind of holidays for the library.
39
40 =head1 FUNCTIONS
41
42 =over 2
43
44 =cut
45
46 @EXPORT = qw(&new 
47              &change_branchcode 
48              &get_week_days_holidays
49              &get_day_month_holidays
50              &get_exception_holidays 
51              &get_single_holidays
52              &insert_week_day_holiday
53              &insert_day_month_holiday
54              &insert_single_holiday
55              &insert_exception_holiday
56              &delete_holiday
57              &isHoliday
58              &addDate
59              &daysBetween);
60
61 =item new
62
63     $calendar = C4::Calendar::Calendar->new(branchcode => $branchcode);
64
65 C<$branchcode> Is the branch code wich you want to use calendar.
66
67 =cut
68
69 sub new {
70     my $classname = shift @_;
71     my %options = @_;
72
73     my %hash;
74     my $self = bless(\%hash, $classname);
75
76     foreach my $optionName (keys %options) {
77         $self->{lc($optionName)} = $options{$optionName};
78     }
79
80     $self->_init;
81
82     return $self;
83 }
84
85 sub _init {
86     my $self = shift @_;
87
88     my $dbh = C4::Context->dbh();
89     my $week_days_sql = $dbh->prepare("select weekday, title, description from repeatable_holidays where ('$self->{branchcode}' = branchcode) and (NOT(ISNULL(weekday)))");
90     $week_days_sql->execute;
91     my %week_days_holidays;
92     while (my ($weekday, $title, $description) = $week_days_sql->fetchrow) {
93         $week_days_holidays{$weekday}{title} = $title;
94         $week_days_holidays{$weekday}{description} = $description;
95     }
96     $week_days_sql->finish;
97     $self->{'week_days_holidays'} = \%week_days_holidays;
98
99     my $day_month_sql = $dbh->prepare("select day, month, title, description from repeatable_holidays where ('$self->{branchcode}' = branchcode) and ISNULL(weekday)");
100     $day_month_sql->execute;
101     my %day_month_holidays;
102     while (my ($day, $month, $title, $description) = $day_month_sql->fetchrow) {
103         $day_month_holidays{"$month/$day"}{title} = $title;
104         $day_month_holidays{"$month/$day"}{description} = $description;
105     }
106     $day_month_sql->finish;
107     $self->{'day_month_holidays'} = \%day_month_holidays;
108
109     my $exception_holidays_sql = $dbh->prepare("select day, month, year, title, description from special_holidays where ('$self->{branchcode}' = branchcode) and (isexception = 1)");
110     $exception_holidays_sql->execute;
111     my %exception_holidays;
112     while (my ($day, $month, $year, $title, $description) = $exception_holidays_sql->fetchrow) {
113         $exception_holidays{"$year/$month/$day"}{title} = $title;
114         $exception_holidays{"$year/$month/$day"}{description} = $description;
115     }
116     $exception_holidays_sql->finish;
117     $self->{'exception_holidays'} = \%exception_holidays;
118
119     my $holidays_sql = $dbh->prepare("select day, month, year, title, description from special_holidays where ('$self->{branchcode}' = branchcode) and (isexception = 0)");
120     $holidays_sql->execute;
121     my %single_holidays;
122     while (my ($day, $month, $year, $title, $description) = $holidays_sql->fetchrow) {
123         $single_holidays{"$year/$month/$day"}{title} = $title;
124         $single_holidays{"$year/$month/$day"}{description} = $description;
125     }
126     $holidays_sql->finish;
127     $self->{'single_holidays'} = \%single_holidays;
128 }
129
130 =item change_branchcode
131
132     $calendar->change_branchcode(branchcode => $branchcode)
133
134 Change the calendar branch code. This means to change the holidays structure.
135
136 C<$branchcode> Is the branch code wich you want to use calendar.
137
138 =cut
139
140 sub change_branchcode {
141     my ($self, $branchcode) = @_;
142     my %options = @_;
143
144     foreach my $optionName (keys %options) {
145         $self->{lc($optionName)} = $options{$optionName};
146     }
147     $self->_init;
148
149     return $self;
150 }
151
152 =item get_week_days_holidays
153
154     $week_days_holidays = $calendar->get_week_days_holidays();
155
156 Returns a hash reference to week days holidays.
157
158 =cut
159
160 sub get_week_days_holidays {
161     my $self = shift @_;
162     my $week_days_holidays = $self->{'week_days_holidays'};
163     return $week_days_holidays;
164 }
165
166 =item get_day_month_holidays
167     
168     $day_month_holidays = $calendar->get_day_month_holidays();
169
170 Returns a hash reference to day month holidays.
171
172 =cut
173
174 sub get_day_month_holidays {
175     my $self = shift @_;
176     my $day_month_holidays = $self->{'day_month_holidays'};
177     return $day_month_holidays;
178 }
179
180 =item get_exception_holidays
181     
182     $exception_holidays = $calendar->exception_holidays();
183
184 Returns a hash reference to exception holidays. This kind of days are those
185 which stands for a holiday, but you wanted to make an exception for this particular
186 date.
187
188 =cut
189
190 sub get_exception_holidays {
191     my $self = shift @_;
192     my $exception_holidays = $self->{'exception_holidays'};
193     return $exception_holidays;
194 }
195
196 =item get_single_holidays
197     
198     $single_holidays = $calendar->get_single_holidays();
199
200 Returns a hash reference to single holidays. This kind of holidays are those which
201 happend just one time.
202
203 =cut
204
205 sub get_single_holidays {
206     my $self = shift @_;
207     my $single_holidays = $self->{'single_holidays'};
208     return $single_holidays;
209 }
210
211 =item insert_week_day_holiday
212
213     insert_week_day_holiday(weekday => $weekday,
214                             title => $title,
215                             description => $description);
216
217 Inserts a new week day for $self->{branchcode}.
218
219 C<$day> Is the week day to make holiday.
220
221 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
222
223 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
224
225 =cut
226
227 sub insert_week_day_holiday {
228     my $self = shift @_;
229     my %options = @_;
230
231     my $dbh = C4::Context->dbh();
232     my $insertHoliday = $dbh->prepare("insert into repeatable_holidays (id,branchcode,weekday,day,month,title,description) values ( '',?,?,NULL,NULL,?,? )"); 
233         $insertHoliday->execute( $self->{branchcode}, $options{weekday},$options{title}, $options{description});
234     $insertHoliday->finish;
235
236     $self->{'week_days_holidays'}->{$options{weekday}}{title} = $options{title};
237     $self->{'week_days_holidays'}->{$options{weekday}}{description} = $options{description};
238     return $self;
239 }
240
241 =item insert_day_month_holiday
242
243     insert_day_month_holiday(day => $day,
244                              month => $month,
245                              title => $title,
246                              description => $description);
247
248 Inserts a new day month holiday for $self->{branchcode}.
249
250 C<$day> Is the day month to make the date to insert.
251
252 C<$month> Is month to make the date to insert.
253
254 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
255
256 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
257
258 =cut
259
260 sub insert_day_month_holiday {
261     my $self = shift @_;
262     my %options = @_;
263
264     my $dbh = C4::Context->dbh();
265     my $insertHoliday = $dbh->prepare("insert into repeatable_holidays (id,branchcode,weekday,day,month,title,description) values ('', ?, NULL, ?, ?, ?,? )");
266         $insertHoliday->execute( $self->{branchcode}, $options{day},$options{month},$options{title}, $options{description});
267     $insertHoliday->finish;
268
269     $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{title} = $options{title};
270     $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{description} = $options{description};
271     return $self;
272 }
273
274 =item insert_single_holiday
275
276     insert_single_holiday(day => $day,
277                           month => $month,
278                           year => $year,
279                           title => $title,
280                           description => $description);
281
282 Inserts a new single holiday for $self->{branchcode}.
283
284 C<$day> Is the day month to make the date to insert.
285
286 C<$month> Is month to make the date to insert.
287
288 C<$year> Is year to make the date to insert.
289
290 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
291
292 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
293
294 =cut
295
296 sub insert_single_holiday {
297     my $self = shift @_;
298     my %options = @_;
299     
300         my $dbh = C4::Context->dbh();
301     my $isexception = 0;
302     my $insertHoliday = $dbh->prepare("insert into special_holidays (id,branchcode,day,month,year,isexception,title,description) values ('', ?,?,?,?,?,?,?)");
303         $insertHoliday->execute( $self->{branchcode}, $options{day},$options{month},$options{year}, $isexception, $options{title}, $options{description});
304     $insertHoliday->finish;
305
306     $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title};
307     $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description};
308     return $self;
309 }
310
311 =item insert_exception_holiday
312
313     insert_exception_holiday(day => $day,
314                              month => $month,
315                              year => $year,
316                              title => $title,
317                              description => $description);
318
319 Inserts a new exception holiday for $self->{branchcode}.
320
321 C<$day> Is the day month to make the date to insert.
322
323 C<$month> Is month to make the date to insert.
324
325 C<$year> Is year to make the date to insert.
326
327 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
328
329 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
330
331 =cut
332
333 sub insert_exception_holiday {
334     my $self = shift @_;
335     my %options = @_;
336
337     my $dbh = C4::Context->dbh();
338     my $isexception = 1;
339     my $insertException = $dbh->prepare("insert into special_holidays (id,branchcode,day,month,year,isexception,title,description) values ('', ?,?,?,?,?,?,?)");
340         $insertException->execute( $self->{branchcode}, $options{day},$options{month},$options{year}, $isexception, $options{title}, $options{description});
341     $insertException->finish;
342
343     $self->{'exceptions_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title};
344     $self->{'exceptions_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description};
345     return $self;
346 }
347
348 =item delete_holiday
349
350     delete_holiday(weekday => $weekday
351                    day => $day,
352                    month => $month,
353                    year => $year);
354
355 Delete a holiday for $self->{branchcode}.
356
357 C<$weekday> Is the week day to delete.
358
359 C<$day> Is the day month to make the date to delete.
360
361 C<$month> Is month to make the date to delete.
362
363 C<$year> Is year to make the date to delete.
364
365 =cut
366
367 sub delete_holiday {
368     my $self = shift @_;
369     my %options = @_;
370
371     # Verify what kind of holiday that day is. For example, if it is
372     # a repeatable holiday, this should check if there are some exception
373         # for that holiday rule. Otherwise, if it is a regular holiday, it´s 
374     # ok just deleting it.
375
376     my $dbh = C4::Context->dbh();
377     my $isSingleHoliday = $dbh->prepare("select id from special_holidays where (branchcode = '$self->{branchcode}') and (day = $options{day}) and (month = $options{month}) and (year = $options{year})");
378     $isSingleHoliday->execute;
379     if ($isSingleHoliday->rows) {
380         my $id = $isSingleHoliday->fetchrow;
381         $isSingleHoliday->finish; # Close the last query
382
383         my $deleteHoliday = $dbh->prepare("delete from special_holidays where (id = $id)");
384         $deleteHoliday->execute;
385         $deleteHoliday->finish; # Close the last query
386         delete($self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"});
387     } else {
388         $isSingleHoliday->finish; # Close the last query
389
390         my $isWeekdayHoliday = $dbh->prepare("select id from repeatable_holidays where (branchcode = '$self->{branchcode}') and (weekday = $options{weekday})");
391         $isWeekdayHoliday->execute;
392         if ($isWeekdayHoliday->rows) {
393             my $id = $isWeekdayHoliday->fetchrow;
394             $isWeekdayHoliday->finish; # Close the last query
395
396             my $updateExceptions = $dbh->prepare("update special_holidays set isexception = 0 where (WEEKDAY(CONCAT(special_holidays.year,'-',special_holidays.month,'-',special_holidays.day)) = $options{weekday}) and (branchcode = '$self->{branchcode}')");
397             $updateExceptions->execute;
398             $updateExceptions->finish; # Close the last query
399
400             my $deleteHoliday = $dbh->prepare("delete from repeatable_holidays where (id = $id)");
401             $deleteHoliday->execute;
402             $deleteHoliday->finish;
403             delete($self->{'week_days_holidays'}->{$options{weekday}});
404         } else {
405             $isWeekdayHoliday->finish; # Close the last query
406
407             my $isDayMonthHoliday = $dbh->prepare("select id from repeatable_holidays where (branchcode = '$self->{branchcode}') and (day = '$options{day}') and (month = '$options{month}')");
408             $isDayMonthHoliday->execute;
409             if ($isDayMonthHoliday->rows) {
410                 my $id = $isDayMonthHoliday->fetchrow;
411                 $isDayMonthHoliday->finish;
412                 my $updateExceptions = $dbh->prepare("update special_holidays set isexception = 0 where (special_holidays.branchcode = '$self->{branchcode}') and (special_holidays.day = '$options{day}') and (special_holidays.month = '$options{month}')");
413                 $updateExceptions->execute;
414                 $updateExceptions->finish; # Close the last query
415
416                 my $deleteHoliday = $dbh->prepare("delete from repeatable_holidays where (id = '$id')");
417                 $deleteHoliday->execute;
418                 $deleteHoliday->finish; # Close the last query
419                 $isDayMonthHoliday->finish; # Close the last query
420                 delete($self->{'day_month_holidays'}->{"$options{month}/$options{day}"});
421             }
422         }
423     }
424     return $self;
425 }
426
427 =item isHoliday
428     
429     $isHoliday = isHoliday($day, $month $year);
430
431
432 C<$day> Is the day to check whether if is a holiday or not.
433
434 C<$month> Is the month to check whether if is a holiday or not.
435
436 C<$year> Is the year to check whether if is a holiday or not.
437
438 =cut
439
440 sub isHoliday {
441     my ($self, $day, $month, $year) = @_;
442     my $weekday = &Date::Calc::Day_of_Week($year, $month, $day) % 7; 
443     my $weekDays = $self->get_week_days_holidays();
444     my $dayMonths = $self->get_day_month_holidays();
445     my $exceptions = $self->get_exception_holidays();
446     my $singles = $self->get_single_holidays();
447     if (defined($exceptions->{"$year/$month/$day"})) {
448         return 0;
449     } else {
450         if ((exists($weekDays->{$weekday})) ||
451             (exists($dayMonths->{"$month/$day"})) ||
452             (exists($singles->{"$year/$month/$day"}))) {
453                         return 1;
454         } else {
455             return 0;
456         }
457     }
458
459 }
460
461 =item addDate
462
463     my ($day, $month, $year) = $calendar->addDate($date, $offset)
464
465 C<$date> is a C4::Dates object representing the starting date of the interval.
466
467 C<$offset> Is the number of days that this function has to count from $date.
468
469 =cut
470
471 sub addDate {
472     my ($self, $startdate, $offset) = @_;
473     my ($year,$month,$day) = split("-",$startdate->output('iso'));
474         my $daystep = 1;
475         if ($offset < 0) { # In case $offset is negative
476        # $offset = $offset*(-1);
477                 $daystep = -1;
478     }
479         my $daysMode = C4::Context->preference('useDaysMode');
480     if ($daysMode eq 'Datedue') {
481         ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $offset );
482                 while ($self->isHoliday($day, $month, $year)) {
483                 ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $daystep);
484         }
485     } elsif($daysMode eq 'Calendar') {
486         while ($offset !=  0) {
487                 ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $daystep);
488             if (!($self->isHoliday($day, $month, $year))) {
489                 $offset = $offset - $daystep;
490                         }
491         }
492         } else { ## ($daysMode eq 'Days') 
493         ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $offset );
494     }
495     return(C4::Dates->new( sprintf("%04d-%02d-%02d",$year,$month,$day),'iso'));
496 }
497
498 =item daysBetween
499
500     my $daysBetween = $calendar->daysBetween($startdate, $enddate )
501
502 C<$startdate>  and C<$enddate> are C4::Dates objects that define the interval.
503
504 Returns the number of non-holiday days in the interval.
505 useDaysMode syspref has no effect here.
506 =cut
507
508 sub daysBetween {
509     my ( $self, $startdate, $enddate ) = @_ ; 
510         my ($yearFrom,$monthFrom,$dayFrom) = split("-",$startdate->output('iso'));
511         my ($yearTo,$monthTo,$dayTo) = split("-",$enddate->output('iso'));
512         if (Date_to_Days($yearFrom,$monthFrom,$dayFrom) > Date_to_Days($yearTo,$monthTo,$dayTo)) {
513                 return 0;
514                 # we don't go backwards  ( FIXME - handle this error better )
515         }
516     my $count = 0;
517     my $continue = 1;
518     while ($continue) {
519         if (($yearFrom != $yearTo) || ($monthFrom != $monthTo) || ($dayFrom != $dayTo)) {
520             if (!($self->isHoliday($dayFrom, $monthFrom, $yearFrom))) {
521                 $count++;
522             }
523             ($yearFrom, $monthFrom, $dayFrom) = &Date::Calc::Add_Delta_Days($yearFrom, $monthFrom, $dayFrom, 1);
524         } else {
525             $continue = 0;
526         }
527     }
528     return($count);
529 }
530
531 1;
532
533 __END__
534
535 =back
536
537 =head1 AUTHOR
538
539 Koha Physics Library UNLP <matias_veleda@hotmail.com>
540
541 =cut