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