Bug 3928: Modified date should follow syspref
[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 use warnings;
20 use vars qw($VERSION @EXPORT);
21
22 use Carp;
23 use Date::Calc qw( Date_to_Days );
24
25 use C4::Context;
26
27 BEGIN {
28     # set the version for version checking
29     $VERSION = 3.01;
30     require Exporter;
31     @EXPORT = qw(
32         &get_week_days_holidays
33         &get_day_month_holidays
34         &get_exception_holidays 
35         &get_single_holidays
36         &insert_week_day_holiday
37         &insert_day_month_holiday
38         &insert_single_holiday
39         &insert_exception_holiday
40         &ModWeekdayholiday
41         &ModDaymonthholiday
42         &ModSingleholiday
43         &ModExceptionholiday
44         &delete_holiday
45         &isHoliday
46         &addDate
47         &daysBetween
48     );
49 }
50
51 =head1 NAME
52
53 C4::Calendar::Calendar - Koha module dealing with holidays.
54
55 =head1 SYNOPSIS
56
57     use C4::Calendar::Calendar;
58
59 =head1 DESCRIPTION
60
61 This package is used to deal with holidays. Through this package, you can set all kind of holidays for the library.
62
63 =head1 FUNCTIONS
64
65 =over 2
66
67 =item new
68
69     $calendar = C4::Calendar->new(branchcode => $branchcode);
70
71 Each library branch has its own Calendar.  
72 C<$branchcode> specifies which Calendar you want.
73
74 =cut
75
76 sub new {
77     my $classname = shift @_;
78     my %options = @_;
79     my $self = bless({}, $classname);
80     foreach my $optionName (keys %options) {
81         $self->{lc($optionName)} = $options{$optionName};
82     }
83     defined($self->{branchcode}) or croak "No branchcode argument to new.  Should be C4::Calendar->new(branchcode => \$branchcode)";
84     $self->_init($self->{branchcode});
85     return $self;
86 }
87
88 sub _init {
89     my $self = shift @_;
90     my $branch = shift;
91     defined($branch) or die "No branchcode sent to _init";  # must test for defined here and above to allow ""
92     my $dbh = C4::Context->dbh();
93     my $repeatable = $dbh->prepare( 'SELECT *
94                                        FROM repeatable_holidays
95                                       WHERE ( branchcode = ? )
96                                         AND (ISNULL(weekday) = ?)' );
97     $repeatable->execute($branch,0);
98     my %week_days_holidays;
99     while (my $row = $repeatable->fetchrow_hashref) {
100         my $key = $row->{weekday};
101         $week_days_holidays{$key}{title}       = $row->{title};
102         $week_days_holidays{$key}{description} = $row->{description};
103     }
104     $self->{'week_days_holidays'} = \%week_days_holidays;
105
106     $repeatable->execute($branch,1);
107     my %day_month_holidays;
108     while (my $row = $repeatable->fetchrow_hashref) {
109         my $key = $row->{month} . "/" . $row->{day};
110         $day_month_holidays{$key}{title}       = $row->{title};
111         $day_month_holidays{$key}{description} = $row->{description};
112         $day_month_holidays{$key}{day} = sprintf("%02d", $row->{day});
113         $day_month_holidays{$key}{month} = sprintf("%02d", $row->{month});
114     }
115     $self->{'day_month_holidays'} = \%day_month_holidays;
116
117     my $special = $dbh->prepare( 'SELECT day, month, year, title, description
118                                     FROM special_holidays
119                                    WHERE ( branchcode = ? )
120                                      AND (isexception = ?)' );
121     $special->execute($branch,1);
122     my %exception_holidays;
123     while (my ($day, $month, $year, $title, $description) = $special->fetchrow) {
124         $exception_holidays{"$year/$month/$day"}{title} = $title;
125         $exception_holidays{"$year/$month/$day"}{description} = $description;
126         $exception_holidays{"$year/$month/$day"}{date} = 
127                 sprintf("%04d-%02d-%02d", $year, $month, $day);
128     }
129     $self->{'exception_holidays'} = \%exception_holidays;
130
131     $special->execute($branch,0);
132     my %single_holidays;
133     while (my ($day, $month, $year, $title, $description) = $special->fetchrow) {
134         $single_holidays{"$year/$month/$day"}{title} = $title;
135         $single_holidays{"$year/$month/$day"}{description} = $description;
136         $single_holidays{"$year/$month/$day"}{date} = 
137                 sprintf("%04d-%02d-%02d", $year, $month, $day);
138     }
139     $self->{'single_holidays'} = \%single_holidays;
140     return $self;
141 }
142
143 =item get_week_days_holidays
144
145     $week_days_holidays = $calendar->get_week_days_holidays();
146
147 Returns a hash reference to week days holidays.
148
149 =cut
150
151 sub get_week_days_holidays {
152     my $self = shift @_;
153     my $week_days_holidays = $self->{'week_days_holidays'};
154     return $week_days_holidays;
155 }
156
157 =item get_day_month_holidays
158     
159     $day_month_holidays = $calendar->get_day_month_holidays();
160
161 Returns a hash reference to day month holidays.
162
163 =cut
164
165 sub get_day_month_holidays {
166     my $self = shift @_;
167     my $day_month_holidays = $self->{'day_month_holidays'};
168     return $day_month_holidays;
169 }
170
171 =item get_exception_holidays
172     
173     $exception_holidays = $calendar->exception_holidays();
174
175 Returns a hash reference to exception holidays. This kind of days are those
176 which stands for a holiday, but you wanted to make an exception for this particular
177 date.
178
179 =cut
180
181 sub get_exception_holidays {
182     my $self = shift @_;
183     my $exception_holidays = $self->{'exception_holidays'};
184     return $exception_holidays;
185 }
186
187 =item get_single_holidays
188     
189     $single_holidays = $calendar->get_single_holidays();
190
191 Returns a hash reference to single holidays. This kind of holidays are those which
192 happend just one time.
193
194 =cut
195
196 sub get_single_holidays {
197     my $self = shift @_;
198     my $single_holidays = $self->{'single_holidays'};
199     return $single_holidays;
200 }
201
202 =item insert_week_day_holiday
203
204     insert_week_day_holiday(weekday => $weekday,
205                             title => $title,
206                             description => $description);
207
208 Inserts a new week day for $self->{branchcode}.
209
210 C<$day> Is the week day to make holiday.
211
212 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
213
214 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
215
216 =cut
217
218 sub insert_week_day_holiday {
219     my $self = shift @_;
220     my %options = @_;
221
222     my $dbh = C4::Context->dbh();
223     my $insertHoliday = $dbh->prepare("insert into repeatable_holidays (id,branchcode,weekday,day,month,title,description) values ( '',?,?,NULL,NULL,?,? )"); 
224         $insertHoliday->execute( $self->{branchcode}, $options{weekday},$options{title}, $options{description});
225     $self->{'week_days_holidays'}->{$options{weekday}}{title} = $options{title};
226     $self->{'week_days_holidays'}->{$options{weekday}}{description} = $options{description};
227     return $self;
228 }
229
230 =item insert_day_month_holiday
231
232     insert_day_month_holiday(day => $day,
233                              month => $month,
234                              title => $title,
235                              description => $description);
236
237 Inserts a new day month holiday for $self->{branchcode}.
238
239 C<$day> Is the day month to make the date to insert.
240
241 C<$month> Is month to make the date to insert.
242
243 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
244
245 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
246
247 =cut
248
249 sub insert_day_month_holiday {
250     my $self = shift @_;
251     my %options = @_;
252
253     my $dbh = C4::Context->dbh();
254     my $insertHoliday = $dbh->prepare("insert into repeatable_holidays (id,branchcode,weekday,day,month,title,description) values ('', ?, NULL, ?, ?, ?,? )");
255         $insertHoliday->execute( $self->{branchcode}, $options{day},$options{month},$options{title}, $options{description});
256     $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{title} = $options{title};
257     $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{description} = $options{description};
258     return $self;
259 }
260
261 =item insert_single_holiday
262
263     insert_single_holiday(day => $day,
264                           month => $month,
265                           year => $year,
266                           title => $title,
267                           description => $description);
268
269 Inserts a new single holiday for $self->{branchcode}.
270
271 C<$day> Is the day month to make the date to insert.
272
273 C<$month> Is month to make the date to insert.
274
275 C<$year> Is year to make the date to insert.
276
277 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
278
279 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
280
281 =cut
282
283 sub insert_single_holiday {
284     my $self = shift @_;
285     my %options = @_;
286     
287         my $dbh = C4::Context->dbh();
288     my $isexception = 0;
289     my $insertHoliday = $dbh->prepare("insert into special_holidays (id,branchcode,day,month,year,isexception,title,description) values ('', ?,?,?,?,?,?,?)");
290         $insertHoliday->execute( $self->{branchcode}, $options{day},$options{month},$options{year}, $isexception, $options{title}, $options{description});
291     $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title};
292     $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description};
293     return $self;
294 }
295
296 =item insert_exception_holiday
297
298     insert_exception_holiday(day => $day,
299                              month => $month,
300                              year => $year,
301                              title => $title,
302                              description => $description);
303
304 Inserts a new exception holiday for $self->{branchcode}.
305
306 C<$day> Is the day month to make the date to insert.
307
308 C<$month> Is month to make the date to insert.
309
310 C<$year> Is year to make the date to insert.
311
312 C<$title> Is the title to store for the holiday formed by $year/$month/$day.
313
314 C<$description> Is the description to store for the holiday formed by $year/$month/$day.
315
316 =cut
317
318 sub insert_exception_holiday {
319     my $self = shift @_;
320     my %options = @_;
321
322     my $dbh = C4::Context->dbh();
323     my $isexception = 1;
324     my $insertException = $dbh->prepare("insert into special_holidays (id,branchcode,day,month,year,isexception,title,description) values ('', ?,?,?,?,?,?,?)");
325         $insertException->execute( $self->{branchcode}, $options{day},$options{month},$options{year}, $isexception, $options{title}, $options{description});
326     $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title};
327     $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description};
328     return $self;
329 }
330
331 =item ModWeekdayholiday
332
333     ModWeekdayholiday(weekday =>$weekday,
334                       title => $title,
335                       description => $description)
336
337 Modifies the title and description of a weekday for $self->{branchcode}.
338
339 C<$weekday> Is the title to update for the holiday.
340
341 C<$description> Is the description to update for the holiday.
342
343 =cut
344
345 sub ModWeekdayholiday {
346     my $self = shift @_;
347     my %options = @_;
348
349     my $dbh = C4::Context->dbh();
350     my $updateHoliday = $dbh->prepare("UPDATE repeatable_holidays SET title = ?, description = ? WHERE branchcode = ? AND weekday = ?");
351     $updateHoliday->execute( $options{title},$options{description},$self->{branchcode},$options{weekday}); 
352     $self->{'week_days_holidays'}->{$options{weekday}}{title} = $options{title};
353     $self->{'week_days_holidays'}->{$options{weekday}}{description} = $options{description};
354     return $self;
355 }
356
357 =item ModDaymonthholiday
358
359     ModDaymonthholiday(day => $day,
360                        month => $month,
361                        title => $title,
362                        description => $description);
363
364 Modifies the title and description for a day/month holiday for $self->{branchcode}.
365
366 C<$day> The day of the month for the update.
367
368 C<$month> The month to be used for the update.
369
370 C<$title> The title to be updated for the holiday.
371
372 C<$description> The description to be update for the holiday.
373
374 =cut
375
376 sub ModDaymonthholiday {
377     my $self = shift @_;
378     my %options = @_;
379
380     my $dbh = C4::Context->dbh();
381     my $updateHoliday = $dbh->prepare("UPDATE repeatable_holidays SET title = ?, description = ? WHERE month = ? AND day = ? AND branchcode = ?");
382        $updateHoliday->execute( $options{title},$options{description},$options{month},$options{day},$self->{branchcode}); 
383     $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{title} = $options{title};
384     $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{description} = $options{description};
385     return $self;
386 }
387
388 =item ModSingleholiday
389
390     ModSingleholiday(day => $day,
391                      month => $month,
392                      year => $year,
393                      title => $title,
394                      description => $description);
395
396 Modifies the title and description for a single holiday for $self->{branchcode}.
397
398 C<$day> Is the day of the month to make the update.
399
400 C<$month> Is the month to make the update.
401
402 C<$year> Is the year to make the update.
403
404 C<$title> Is the title to update for the holiday formed by $year/$month/$day.
405
406 C<$description> Is the description to update for the holiday formed by $year/$month/$day.
407
408 =cut
409
410 sub ModSingleholiday {
411     my $self = shift @_;
412     my %options = @_;
413
414     my $dbh = C4::Context->dbh();
415     my $isexception = 0;
416     my $updateHoliday = $dbh->prepare("UPDATE special_holidays SET title = ?, description = ? WHERE day = ? AND month = ? AND year = ? AND branchcode = ? AND isexception = ?");
417       $updateHoliday->execute($options{title},$options{description},$options{day},$options{month},$options{year},$self->{branchcode},$isexception);    
418     $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title};
419     $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description};
420     return $self;
421 }
422
423 =item ModExceptionholiday
424
425     ModExceptionholiday(day => $day,
426                         month => $month,
427                         year => $year,
428                         title => $title,
429                         description => $description);
430
431 Modifies the title and description for an exception holiday for $self->{branchcode}.
432
433 C<$day> Is the day of the month for the holiday.
434
435 C<$month> Is the month for the holiday.
436
437 C<$year> Is the year for the holiday.
438
439 C<$title> Is the title to be modified for the holiday formed by $year/$month/$day.
440
441 C<$description> Is the description to be modified for the holiday formed by $year/$month/$day.
442
443 =cut
444
445 sub ModExceptionholiday {
446     my $self = shift @_;
447     my %options = @_;
448
449     my $dbh = C4::Context->dbh();
450     my $isexception = 1;
451     my $updateHoliday = $dbh->prepare("UPDATE special_holidays SET title = ?, description = ? WHERE day = ? AND month = ? AND year = ? AND branchcode = ? AND isexception = ?");
452     $updateHoliday->execute($options{title},$options{description},$options{day},$options{month},$options{year},$self->{branchcode},$isexception);    
453     $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title};
454     $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description};
455     return $self;
456 }
457
458 =item delete_holiday
459
460     delete_holiday(weekday => $weekday
461                    day => $day,
462                    month => $month,
463                    year => $year);
464
465 Delete a holiday for $self->{branchcode}.
466
467 C<$weekday> Is the week day to delete.
468
469 C<$day> Is the day month to make the date to delete.
470
471 C<$month> Is month to make the date to delete.
472
473 C<$year> Is year to make the date to delete.
474
475 =cut
476
477 sub delete_holiday {
478     my $self = shift @_;
479     my %options = @_;
480
481     # Verify what kind of holiday that day is. For example, if it is
482     # a repeatable holiday, this should check if there are some exception
483         # for that holiday rule. Otherwise, if it is a regular holiday, it´s 
484     # ok just deleting it.
485
486     my $dbh = C4::Context->dbh();
487     my $isSingleHoliday = $dbh->prepare("SELECT id FROM special_holidays WHERE (branchcode = ?) AND (day = ?) AND (month = ?) AND (year = ?)");
488     $isSingleHoliday->execute($self->{branchcode}, $options{day}, $options{month}, $options{year});
489     if ($isSingleHoliday->rows) {
490         my $id = $isSingleHoliday->fetchrow;
491         $isSingleHoliday->finish; # Close the last query
492
493         my $deleteHoliday = $dbh->prepare("DELETE FROM special_holidays WHERE id = ?");
494         $deleteHoliday->execute($id);
495         delete($self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"});
496     } else {
497         $isSingleHoliday->finish; # Close the last query
498
499         my $isWeekdayHoliday = $dbh->prepare("SELECT id FROM repeatable_holidays WHERE branchcode = ? AND weekday = ?");
500         $isWeekdayHoliday->execute($self->{branchcode}, $options{weekday});
501         if ($isWeekdayHoliday->rows) {
502             my $id = $isWeekdayHoliday->fetchrow;
503             $isWeekdayHoliday->finish; # Close the last query
504
505             my $updateExceptions = $dbh->prepare("UPDATE special_holidays SET isexception = 0 WHERE (WEEKDAY(CONCAT(special_holidays.year,'-',special_holidays.month,'-',special_holidays.day)) = ?) AND (branchcode = ?)");
506             $updateExceptions->execute($options{weekday}, $self->{branchcode});
507             $updateExceptions->finish; # Close the last query
508
509             my $deleteHoliday = $dbh->prepare("DELETE FROM repeatable_holidays WHERE id = ?");
510             $deleteHoliday->execute($id);
511             delete($self->{'week_days_holidays'}->{$options{weekday}});
512         } else {
513             $isWeekdayHoliday->finish; # Close the last query
514
515             my $isDayMonthHoliday = $dbh->prepare("SELECT id FROM repeatable_holidays WHERE (branchcode = ?) AND (day = ?) AND (month = ?)");
516             $isDayMonthHoliday->execute($self->{branchcode}, $options{day}, $options{month});
517             if ($isDayMonthHoliday->rows) {
518                 my $id = $isDayMonthHoliday->fetchrow;
519                 $isDayMonthHoliday->finish;
520                 my $updateExceptions = $dbh->prepare("UPDATE special_holidays SET isexception = 0 WHERE (special_holidays.branchcode = ?) AND (special_holidays.day = ?) and (special_holidays.month = ?)");
521                 $updateExceptions->execute($self->{branchcode}, $options{day}, $options{month});
522                 $updateExceptions->finish; # Close the last query
523
524                 my $deleteHoliday = $dbh->prepare("DELETE FROM repeatable_holidays WHERE (id = ?)");
525                 $deleteHoliday->execute($id);
526                 delete($self->{'day_month_holidays'}->{"$options{month}/$options{day}"});
527             }
528         }
529     }
530     return $self;
531 }
532
533 =item isHoliday
534     
535     $isHoliday = isHoliday($day, $month $year);
536
537
538 C<$day> Is the day to check whether if is a holiday or not.
539
540 C<$month> Is the month to check whether if is a holiday or not.
541
542 C<$year> Is the year to check whether if is a holiday or not.
543
544 =cut
545
546 sub isHoliday {
547     my ($self, $day, $month, $year) = @_;
548         # FIXME - date strings are stored in non-padded metric format. should change to iso.
549         # FIXME - should change arguments to accept C4::Dates object
550         $month=$month+0;
551         $year=$year+0;
552         $day=$day+0;
553     my $weekday = &Date::Calc::Day_of_Week($year, $month, $day) % 7; 
554     my $weekDays   = $self->get_week_days_holidays();
555     my $dayMonths  = $self->get_day_month_holidays();
556     my $exceptions = $self->get_exception_holidays();
557     my $singles    = $self->get_single_holidays();
558     if (defined($exceptions->{"$year/$month/$day"})) {
559         return 0;
560     } else {
561         if ((exists($weekDays->{$weekday})) ||
562             (exists($dayMonths->{"$month/$day"})) ||
563             (exists($singles->{"$year/$month/$day"}))) {
564                         return 1;
565         } else {
566             return 0;
567         }
568     }
569
570 }
571
572 =item addDate
573
574     my ($day, $month, $year) = $calendar->addDate($date, $offset)
575
576 C<$date> is a C4::Dates object representing the starting date of the interval.
577
578 C<$offset> Is the number of days that this function has to count from $date.
579
580 =cut
581
582 sub addDate {
583     my ($self, $startdate, $offset) = @_;
584     my ($year,$month,$day) = split("-",$startdate->output('iso'));
585         my $daystep = 1;
586         if ($offset < 0) { # In case $offset is negative
587        # $offset = $offset*(-1);
588                 $daystep = -1;
589     }
590         my $daysMode = C4::Context->preference('useDaysMode');
591     if ($daysMode eq 'Datedue') {
592         ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $offset );
593                 while ($self->isHoliday($day, $month, $year)) {
594             ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $daystep);
595         }
596     } elsif($daysMode eq 'Calendar') {
597         while ($offset !=  0) {
598             ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $daystep);
599             if (!($self->isHoliday($day, $month, $year))) {
600                 $offset = $offset - $daystep;
601                         }
602         }
603         } else { ## ($daysMode eq 'Days') 
604         ($year, $month, $day) = &Date::Calc::Add_Delta_Days($year, $month, $day, $offset );
605     }
606     return(C4::Dates->new( sprintf("%04d-%02d-%02d",$year,$month,$day),'iso'));
607 }
608
609 =item daysBetween
610
611     my $daysBetween = $calendar->daysBetween($startdate, $enddate)
612
613 C<$startdate> and C<$enddate> are C4::Dates objects that define the interval.
614
615 Returns the number of non-holiday days in the interval.
616 useDaysMode syspref has no effect here.
617 =cut
618
619 sub daysBetween ($$$) {
620     my $self      = shift or return undef;
621     my $startdate = shift or return undef;
622     my $enddate   = shift or return undef;
623         my ($yearFrom,$monthFrom,$dayFrom) = split("-",$startdate->output('iso'));
624         my ($yearTo,  $monthTo,  $dayTo  ) = split("-",  $enddate->output('iso'));
625         if (Date_to_Days($yearFrom,$monthFrom,$dayFrom) > Date_to_Days($yearTo,$monthTo,$dayTo)) {
626                 return 0;
627                 # we don't go backwards  ( FIXME - handle this error better )
628         }
629     my $count = 0;
630     while (1) {
631         ($yearFrom != $yearTo or $monthFrom != $monthTo or $dayFrom != $dayTo) or last; # if they all match, it's the last day
632         unless ($self->isHoliday($dayFrom, $monthFrom, $yearFrom)) {
633             $count++;
634         }
635         ($yearFrom, $monthFrom, $dayFrom) = &Date::Calc::Add_Delta_Days($yearFrom, $monthFrom, $dayFrom, 1);
636     }
637     return($count);
638 }
639
640 1;
641
642 __END__
643
644 =back
645
646 =head1 AUTHOR
647
648 Koha Physics Library UNLP <matias_veleda@hotmail.com>
649
650 =cut