View | Details | Raw Unified | Return to bug 17015
Collapse All | Expand All

(-)a/Koha/DiscreteCalendar.pm (+971 lines)
Line 0 Link Here
1
package Koha::DiscreteCalendar;
2
3
# This file is part of Koha.
4
#
5
# Koha is free software; you can redistribute it and/or modify it
6
# under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 3 of the License, or
8
# (at your option) any later version.
9
#
10
# Koha is distributed in the hope that it will be useful, but
11
# WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18
#####Sets holiday periods for each branch. Datedues will be extended if branch is closed -TG
19
use strict;
20
use warnings;
21
22
use CGI qw ( -utf8 );
23
use Carp;
24
use DateTime;
25
use DateTime::Format::Strptime;
26
27
use C4::Context;
28
use C4::Output;
29
use Koha::Database;
30
use Koha::DateUtils;
31
32
sub new {
33
    my ( $classname, %options ) = @_;
34
    my $self = {};
35
    bless $self, $classname;
36
    for my $o_name ( keys %options ) {
37
        my $o = lc $o_name;
38
        $self->{$o} = $options{$o_name};
39
    }
40
    if ( !defined $self->{branchcode} ) {
41
        croak 'No branchcode argument passed to Koha::DiscreteCalendar->new';
42
    }
43
    $self->_init();
44
45
    return $self;
46
}
47
48
sub _init {
49
    my $self = shift;
50
    $self->{days_mode} = C4::Context->preference('useDaysMode');
51
    #If the branchcode doesn't exist we use the default calendar.
52
    my $schema = Koha::Database->new->schema;
53
    my $branchcode = $self->{branchcode};
54
    my $dtf = $schema->storage->datetime_parser;
55
    my $today = $dtf->format_datetime(DateTime->today);
56
    my $rs = $schema->resultset('DiscreteCalendar')->single(
57
        {
58
            branchcode  => $branchcode,
59
            date        => $today
60
        }
61
    );
62
    #use default if no calendar is found
63
    if (!$rs){
64
        $self->{branchcode} = 'DFLT';
65
    }
66
67
}
68
69
sub getDatesInfo {
70
    my $self = shift;
71
    my $branchcode = $self->{branchcode};
72
    my @datesInfos =();
73
    my $schema = Koha::Database->new->schema;
74
75
    my $rs = $schema->resultset('DiscreteCalendar')->search(
76
        {
77
            branchcode  => $branchcode
78
        },
79
        {
80
            select  => [ 'date', { DATE => 'date' } ],
81
            as      => [qw/ date date /],
82
            columns =>[ qw/ holidaytype openhour closehour note/]
83
        },
84
    );
85
86
    while (my $date = $rs->next()){
87
        my $outputdate = dt_from_string( $date->date(), 'iso');
88
        $outputdate = output_pref( { dt => $outputdate, dateonly => 1 } );
89
        push @datesInfos, {
90
            date        => $date->date(),
91
            outputdate  => $outputdate,
92
            holidaytype => $date->holidaytype() ,
93
            openhour    => $date->openhour(),
94
            closehour   => $date->closehour(),
95
            note        => $date->note()
96
        };
97
    }
98
99
    return @datesInfos;
100
}
101
#This methode will copy everything from the first branch found to the new branch
102
sub add_new_branch {
103
    my ($self) = @_;
104
    my $branchcode = $self->{branchcode};
105
    my $schema = Koha::Database->new->schema;
106
    my $branch_rs = $schema->resultset('DiscreteCalendar')->search({},
107
        {
108
            group_by => 'date'
109
        }
110
    );
111
112
    while(my $row = $branch_rs->next()){
113
        $schema->resultset('DiscreteCalendar')->create({
114
            date        => $row->date(),
115
            branchcode  => $branchcode,
116
            isopened    => $row->isopened(),
117
            holidaytype => $row->holidaytype(),
118
            openhour    => $row->openhour(),
119
            closehour   => $row->closehour(),
120
        });
121
    }
122
123
}
124
#DiscreteCalendar data transfer object (DTO)
125
sub get_date_info {
126
    my ($self, $date) = @_;
127
    my $branchcode = $self->{branchcode};
128
    my $schema = Koha::Database->new->schema;
129
    my $dtf = $schema->storage->datetime_parser;
130
    #String dates for Database usage
131
    my $date_string = $dtf->format_datetime($date);
132
133
    my $rs = $schema->resultset('DiscreteCalendar')->search(
134
        {
135
            branchcode  => $branchcode,
136
            date        => $date_string
137
        },
138
        {
139
            select  => [ 'date', { DATE => 'date' } ],
140
            as      => [qw/ date date /],
141
            columns =>[ qw/ branchcode holidaytype openhour closehour note/]
142
        },
143
    );
144
    my $dateDTO;
145
    while (my $date = $rs->next()){
146
        $dateDTO = {
147
            date        => $date->date(),
148
            branchcode  => $date->branchcode(),
149
            holidaytype => $date->holidaytype() ,
150
            openhour    => $date->openhour(),
151
            closehour   => $date->closehour(),
152
            note        => $date->note()
153
        };
154
    }
155
156
    return $dateDTO;
157
}
158
159
160
sub getMaxDate {
161
    my $self       = shift;
162
    my $branchcode     = $self->{branchcode};
163
    my $schema = Koha::Database->new->schema;
164
165
    my $rs = $schema->resultset('DiscreteCalendar')->search(
166
        {
167
            branchcode  => $branchcode
168
        },
169
        {
170
            select => [{ MAX => 'date' } ],
171
            as     => [qw/ max /],
172
        }
173
    );
174
175
    return $rs->next()->get_column('max');
176
}
177
178
sub getMinDate {
179
    my $self       = shift;
180
    my $branchcode     = $self->{branchcode};
181
    my $schema = Koha::Database->new->schema;
182
183
    my $rs = $schema->resultset('DiscreteCalendar')->search(
184
        {
185
            branchcode  => $branchcode
186
        },
187
        {
188
            select => [{ MIN => 'date' } ],
189
            as     => [qw/ min /],
190
        }
191
    );
192
193
    return $rs->next()->get_column('min');
194
}
195
196
sub get_single_holidays {
197
    my $self = shift;
198
    my $branchcode = $self->{branchcode};
199
    my @single_holidays;
200
    my $schema = Koha::Database->new->schema;
201
202
    my $rs = $schema->resultset('DiscreteCalendar')->search(
203
        {
204
            branchcode  => $branchcode,
205
            holidaytype => 'E'
206
        },
207
        {
208
            select => [{ DATE => 'date' }, 'note' ],
209
            as     => [qw/ date note/],
210
        }
211
    );
212
    while (my $date = $rs->next()){
213
        my $outputdate = dt_from_string($date->date(), 'iso');
214
        $outputdate = output_pref( { dt => $outputdate, dateonly => 1 } );
215
        push @single_holidays, {
216
            date =>  $date->date(),
217
            outputdate => $outputdate,
218
            note => $date->note()
219
        }
220
    }
221
222
    return @single_holidays;
223
}
224
225
sub get_float_holidays {
226
    my $self = shift;
227
    my $branchcode = $self->{branchcode};
228
    my @float_holidays;
229
    my $schema = Koha::Database->new->schema;
230
231
    my $rs = $schema->resultset('DiscreteCalendar')->search(
232
        {
233
            branchcode  => $branchcode,
234
            holidaytype => 'F'
235
        },
236
        {
237
            select => [{ DATE => 'date' }, 'note' ],
238
            as     => [qw/ date note/],
239
        }
240
    );
241
    while (my $date = $rs->next()){
242
        my $outputdate = dt_from_string($date->date(), 'iso');
243
        $outputdate = output_pref( { dt => $outputdate, dateonly => 1 } );
244
        push @float_holidays, {
245
            date        =>  $date->date(),
246
            outputdate  => $outputdate,
247
            note        => $date->note()
248
        }
249
    }
250
251
    return @float_holidays;
252
}
253
254
sub get_need_valdation_holidays {
255
    my $self = shift;
256
    my $branchcode = $self->{branchcode};
257
    my @need_validation_holidays;
258
    my $schema = Koha::Database->new->schema;
259
260
    my $rs = $schema->resultset('DiscreteCalendar')->search(
261
        {
262
            branchcode  => $branchcode,
263
            holidaytype => 'N'
264
        },
265
        {
266
            select => [{ DATE => 'date' }, 'note' ],
267
            as     => [qw/ date note/],
268
        }
269
    );
270
    while (my $date = $rs->next()){
271
        my $outputdate = dt_from_string($date->date(), 'iso');
272
        $outputdate = output_pref( { dt => $outputdate, dateonly => 1 } );
273
        push @need_validation_holidays, {
274
            date        =>  $date->date(),
275
            outputdate  => $outputdate,
276
            note        => $date->note()
277
        }
278
    }
279
280
    return @need_validation_holidays;
281
}
282
283
sub get_day_month_holidays {
284
    my $self = shift;
285
    my $branchcode = $self->{branchcode};
286
    my @repeatable_holidays;
287
    my $schema = Koha::Database->new->schema;
288
289
    my $rs = $schema->resultset('DiscreteCalendar')->search(
290
        {
291
            branchcode  => $branchcode,
292
            holidaytype => 'R',
293
294
        },
295
        {
296
            select  => \[ 'distinct DAY(date), MONTH(date), note'],
297
            as      => [qw/ day month note/],
298
        }
299
    );
300
301
    while (my $date = $rs->next()){
302
        push @repeatable_holidays, {
303
            day=> $date->get_column('day'),
304
            month => $date->get_column('month'),
305
            note => $date->note()
306
        };
307
    }
308
309
    return @repeatable_holidays;
310
}
311
312
sub get_week_days_holidays {
313
    my $self = shift;
314
    my $branchcode = $self->{branchcode};
315
    my @week_days;
316
    my $schema = Koha::Database->new->schema;
317
318
    my $rs = $schema->resultset('DiscreteCalendar')->search(
319
        {
320
            holidaytype => 'W',
321
            branchcode  => $branchcode,
322
        },
323
        {
324
            select      => [{ DAYOFWEEK => 'date'}, 'note'],
325
            as          => [qw/ weekday note /],
326
            distinct    => 1,
327
        }
328
    );
329
330
    while (my $date = $rs->next()){
331
        push @week_days, {
332
            weekday => ($date->get_column('weekday') -1),
333
            note    => $date->note()
334
        };
335
    }
336
337
    return @week_days;
338
}
339
=head2 edit_holiday
340
341
Modifies a date or a range of dates
342
343
C<$title> Is the title to be modified for the holiday formed by $year/$month/$day.
344
345
C<$weekday> Is the day of week for the holiday
346
347
C<$holidaytype> Is the type of the holiday :
348
    E : Exception holiday, single day.
349
    F : Floating holiday, differnt day each year.
350
    N : Needs validation, copied float holiday from the past
351
    R : Fixed holiday, repeated on same date.
352
    W : Weekly holiday, same day of the week.
353
354
C<$openHour> Is the opening hour.
355
C<$closeHour> Is the closing hour.
356
C<$startDate> Is the start of the range of dates.
357
C<$endDate> Is the end of the range of dates.
358
359
360
=cut
361
sub edit_holiday {
362
    my ($self, $title, $weekday, $holidaytype, $openHour, $closeHour, $startDate, $endDate, $deleteType) = @_;
363
    my $branchcode = $self->{branchcode};
364
    my $today = DateTime->today;
365
    my $schema = Koha::Database->new->schema;
366
    my $dtf = $schema->storage->datetime_parser;
367
    #String dates for Database usage
368
    my $startDate_String = $dtf->format_datetime($startDate);
369
    my $endDate_String = $dtf->format_datetime($endDate);
370
    $today = $dtf->format_datetime($today);
371
372
    my %updateValues = (
373
        isopened    => 0,
374
        note        => $title,
375
        holidaytype => $holidaytype,
376
    );
377
    $updateValues{openhour}  = $openHour if $openHour ne '';
378
    $updateValues{closehour}  = $closeHour if $closeHour ne '';
379
380
    if($holidaytype eq 'W') {
381
        #Insert/Update weekly holidays
382
        my $rs = $schema->resultset('DiscreteCalendar')->search(
383
            {
384
                branchcode  => $branchcode,
385
            },
386
            {
387
                where => \[ 'DAYOFWEEK(date) = ? and date >= ?', $weekday, $today],
388
            }
389
        );
390
391
        while (my $date = $rs->next()){
392
            $date->update(\%updateValues);
393
        }
394
    }elsif ($holidaytype eq 'E' || $holidaytype eq 'F' || $holidaytype eq 'N') {
395
        #Insert/Update Exception Float and Needs Validation holidays
396
        my $rs = $schema->resultset('DiscreteCalendar')->search(
397
            {
398
                branchcode  => $branchcode,
399
            },
400
            {
401
                where =>  \['date between DATE(?) and DATE(?) and date >= ?',$startDate_String, $endDate_String, $today]
402
            }
403
        );
404
        while (my $date = $rs->next()){
405
            $date->update(\%updateValues);
406
        }
407
408
    }elsif ($holidaytype eq 'R') {
409
        #Insert/Update repeatable holidays
410
        my $parser = DateTime::Format::Strptime->new(
411
    	   pattern  => '%m-%d',
412
    	   on_error => 'croak',
413
    	);
414
        #Format the dates to have only month-day ex: 01-04 for January 4th
415
        $startDate = $parser->format_datetime($startDate);
416
        $endDate = $parser->format_datetime($endDate);
417
        my $rs = $schema->resultset('DiscreteCalendar')->search(
418
            {
419
                branchcode  => $branchcode,
420
            },
421
            {
422
                where =>  \["(DATE_FORMAT(date,'\%m-\%d') BETWEEN ? AND ? ) AND date >= ?", $startDate, $endDate, $today],
423
            }
424
        );
425
        while (my $date = $rs->next()){
426
            $date->update(\%updateValues);
427
        }
428
429
    }else {
430
        #Delete/Update date(s)
431
        my $rs = $schema->resultset('DiscreteCalendar')->search(
432
            {
433
                branchcode  => $branchcode,
434
            },
435
            {
436
                where =>  \['date between DATE(?) and DATE(?) and date >= ?',$startDate_String, $endDate_String, $today],
437
            }
438
        );
439
        #If none, the date(s) will be normal days, else,
440
        if($holidaytype eq 'none'){
441
            $updateValues{holidaytype}  ='';
442
            $updateValues{isopened}  =1;
443
        }else{
444
            delete $updateValues{holidaytype};
445
        }
446
        while (my $date = $rs->next()){
447
            if($deleteType){
448
                if($date->holidaytype() eq 'W' && $startDate_String eq $endDate_String){
449
                    $self->remove_weekly_holidays($weekday, \%updateValues, $today);
450
                }elsif($date->holidaytype() eq 'R'){
451
                    $self->remove_fixed_holidays($startDate, $endDate, \%updateValues, $today);
452
                }
453
            }else{
454
                $date->update(\%updateValues);
455
            }
456
        }
457
    }
458
}
459
460
sub remove_weekly_holidays {
461
    my ($self, $weekday, $updateValues, $today) = @_;
462
    my $branchcode = $self->{branchcode};
463
    my $schema = Koha::Database->new->schema;
464
465
    my $rs = $schema->resultset('DiscreteCalendar')->search(
466
        {
467
            branchcode  => $branchcode,
468
            isopened    => 0,
469
            holidaytype => 'W'
470
        },
471
        {
472
            where => \["DAYOFWEEK(date) = ? and date >= ?", $weekday,$today],
473
        }
474
    );
475
476
    while (my $date = $rs->next()){
477
        $date->update($updateValues);
478
    }
479
}
480
481
sub remove_fixed_holidays {
482
    my ($self, $startDate, $endDate, $updateValues, $today) = @_;
483
    my $branchcode = $self->{branchcode};
484
    my $schema = Koha::Database->new->schema;
485
    my $parser = DateTime::Format::Strptime->new(
486
        pattern   => '%m-%d',
487
        on_error  => 'croak',
488
    );
489
    #Format the dates to have only month-day ex: 01-04 for January 4th
490
    $startDate = $parser->format_datetime($startDate);
491
    $endDate = $parser->format_datetime($endDate);
492
493
    my $rs = $schema->resultset('DiscreteCalendar')->search(
494
        {
495
            branchcode  => $branchcode,
496
            isopened    => 0,
497
            holidaytype => 'R',
498
        },
499
        {
500
            where =>  \["(DATE_FORMAT(date,'\%m-\%d') BETWEEN ? AND ? ) AND date >= ?", $startDate, $endDate, $today],
501
        }
502
    );
503
504
    while (my $date = $rs->next()){
505
        $date->update($updateValues);
506
    }
507
}
508
509
sub copyToBranch {
510
    my ($self,$newBranch) =@_;
511
    my $branchcode = $self->{branchcode};
512
    my $schema = Koha::Database->new->schema;
513
514
    my $copyFrom = $schema->resultset('DiscreteCalendar')->search(
515
        {
516
            branchcode  => $branchcode
517
        },
518
        {
519
            columns     => [ qw/ date isopened note holidaytype openhour closehour /]
520
        }
521
    );
522
    while (my $copyDate = $copyFrom->next()){
523
        my $copyTo = $schema->resultset('DiscreteCalendar')->search(
524
            {
525
                branchcode  => $newBranch,
526
                date        => $copyDate->date(),
527
            },
528
            {
529
                columns => [ qw/ date branchcode isopened note holidaytype openhour closehour /]
530
            }
531
        );
532
        $copyTo->next()->update({
533
            isopened    => $copyDate->isopened(),
534
            holidaytype => $copyDate->holidaytype(),
535
            note        => $copyDate->note(),
536
            openhour    => $copyDate->openhour(),
537
            closehour   => $copyDate->closehour()
538
        });
539
    }
540
}
541
542
sub isOpened {
543
    my($self, $date) = @_;
544
    my $branchcode = $self->{branchcode};
545
    my $schema = Koha::Database->new->schema;
546
    my $dtf = $schema->storage->datetime_parser;
547
    $date= $dtf->format_datetime($date);
548
    #if the date is not found
549
    my $isOpened = -1;
550
    my $rs = $schema->resultset('DiscreteCalendar')->search(
551
        {
552
            branchcode => $branchcode,
553
        },
554
        {
555
            where   => \['date = DATE(?)', $date]
556
        }
557
    );
558
    $isOpened = $rs->next()->isopened() if $rs->count() != 0;
559
560
    return $isOpened;
561
}
562
563
sub is_holiday {
564
    my($self, $date) = @_;
565
    my $branchcode = $self->{branchcode};
566
    my $schema = Koha::Database->new->schema;
567
    my $dtf = $schema->storage->datetime_parser;
568
    $date= $dtf->format_datetime($date);
569
    #if the date is not found
570
    my $isHoliday = -1;
571
    my $rs = $schema->resultset('DiscreteCalendar')->search(
572
        {
573
            branchcode => $branchcode,
574
        },
575
        {
576
            where   => \['date = DATE(?)', $date]
577
        }
578
    );
579
580
    if($rs->count() != 0){
581
        $isHoliday = 0 if $rs->first()->isopened();
582
        $isHoliday = 1 if !$rs->first()->isopened();
583
    }
584
585
    return $isHoliday;
586
}
587
588
sub copyHoliday {
589
    my ($self, $from_startDate, $from_endDate, $to_startDate, $to_endDate, $daysnumber) = @_;
590
    my $branchcode = $self->{branchcode};
591
    my $copyFromType =  $from_startDate && $from_endDate eq '' ? 'oneDay': 'range';
592
    my $schema = Koha::Database->new->schema;
593
    my $dtf = $schema->storage->datetime_parser;
594
    my $parser = DateTime::Format::Strptime->new(
595
        pattern     => '%Y-%m-%d',
596
        on_error    => 'croak',
597
    );
598
599
    if ($copyFromType eq 'oneDay'){
600
        my $where;
601
        $to_startDate = $dtf->format_datetime($to_startDate);
602
        if ($to_startDate && $to_endDate) {
603
            $to_endDate = $dtf->format_datetime($to_endDate);
604
            $where = \["date between ? and ?", $to_startDate, $to_endDate];
605
        } else {
606
            $where = \['date = ?', $to_startDate];
607
        }
608
609
        $from_startDate = $dtf->format_datetime($from_startDate);
610
        my $fromDate = $schema->resultset('DiscreteCalendar')->search(
611
            {
612
                branchcode  => $branchcode,
613
                date        => $from_startDate
614
            }
615
        );
616
        my $toDates = $schema->resultset('DiscreteCalendar')->search(
617
            {
618
                branchcode  => $branchcode,
619
            },
620
            {
621
                where       => $where
622
            }
623
        );
624
625
        my $copyDate = $fromDate->next();
626
        while (my $date = $toDates->next()){
627
            $date->update({
628
                isopened    => $copyDate->isopened(),
629
                holidaytype => $copyDate->holidaytype(),
630
                note        => $copyDate->note(),
631
                openhour    => $copyDate->openhour(),
632
                closehour   => $copyDate->closehour()
633
            })
634
        }
635
636
    }else{
637
        my $endDate = $parser->parse_datetime($from_endDate);
638
        $to_startDate = $dtf->format_datetime($to_startDate);
639
        $to_endDate = $dtf->format_datetime($to_endDate);
640
        if($daysnumber ==6){
641
            for (my $tempDate = $from_startDate->clone(); $tempDate <= $endDate;$tempDate->add(days => 1)){
642
                my $formatedDate = $dtf->format_datetime($tempDate);
643
                my $fromDate = $schema->resultset('DiscreteCalendar')->search(
644
                    {
645
                        branchcode  => $branchcode,
646
                        date        => $formatedDate,
647
                    },
648
                    {
649
                        select  => [{ DAYOFWEEK => 'date' }],
650
                        as      => [qw/ weekday /],
651
                        columns =>[ qw/ holidaytype note openhour closehour note/]
652
                    }
653
                );
654
                my $copyDate = $fromDate->next();
655
                my $weekday = $copyDate->get_column('weekday');
656
657
                my $toDate = $schema->resultset('DiscreteCalendar')->search(
658
                    {
659
                        branchcode  => $branchcode,
660
661
                    },
662
                    {
663
                        where       => \['date between ? and ? and DAYOFWEEK(date) = ?',$to_startDate, $to_endDate, $weekday]
664
                    }
665
                );
666
                my $copyToDate = $toDate->next();
667
                $copyToDate->update({
668
                    isopened    => $copyDate->isopened(),
669
                    holidaytype => $copyDate->holidaytype(),
670
                    note        => $copyDate->note(),
671
                    openhour    => $copyDate->openhour(),
672
                    closehour   => $copyDate->closehour()
673
                });
674
675
            }
676
        }else{
677
            my $to_startDate = $parser->parse_datetime($to_startDate);
678
            my $to_endDate = $parser->parse_datetime($to_endDate);
679
            for (my $tempDate = $from_startDate->clone(); $tempDate <= $endDate;$tempDate->add(days => 1)){
680
                my $from_formatedDate = $dtf->format_datetime($tempDate);
681
                my $fromDate = $schema->resultset('DiscreteCalendar')->search(
682
                    {
683
                        branchcode  => $branchcode,
684
                        date        => $from_formatedDate,
685
                    },
686
                    {
687
                        order_by    => { -asc => 'date' }
688
                    }
689
                );
690
                my $to_formatedDate = $dtf->format_datetime($to_startDate);
691
                my $toDate = $schema->resultset('DiscreteCalendar')->search(
692
                    {
693
                        branchcode  => $branchcode,
694
                        date        => $to_formatedDate
695
                    },
696
                    {
697
                        order_by    => { -asc => 'date' }
698
                    }
699
                );
700
                my $copyDate = $fromDate->next();
701
                $toDate->next()->update({
702
                    isopened    => $copyDate->isopened(),
703
                    holidaytype => $copyDate->holidaytype(),
704
                    note        => $copyDate->note(),
705
                    openhour    => $copyDate->openhour(),
706
                    closehour   => $copyDate->closehour()
707
                });
708
                $to_startDate->add(days =>1);
709
            }
710
        }
711
712
713
    }
714
}
715
716
sub days_between {
717
    my ($self, $start_date, $end_date, ) = @_;
718
    my $branchcode = $self->{branchcode};
719
720
    if ( $start_date->compare($end_date) > 0 ) {
721
        # swap dates
722
        my $int_dt = $end_date;
723
        $end_date = $start_date;
724
        $start_date = $int_dt;
725
    }
726
727
    my $schema = Koha::Database->new->schema;
728
    my $dtf = $schema->storage->datetime_parser;
729
    $start_date = $dtf->format_datetime($start_date);
730
    $end_date = $dtf->format_datetime($end_date);
731
732
    my $days_between = $schema->resultset('DiscreteCalendar')->search(
733
        {
734
            branchcode  => $branchcode,
735
            isopened    => 1,
736
        },
737
        {
738
            where       => \['date >= date(?) and date < date(?)',$start_date, $end_date]
739
        }
740
    );
741
742
    return DateTime::Duration->new( days => $days_between->count());
743
}
744
745
sub next_open_day {
746
    my ( $self, $date ) = @_;
747
    my $branchcode = $self->{branchcode};
748
    my $schema = Koha::Database->new->schema;
749
    my $dtf = $schema->storage->datetime_parser;
750
    $date = $dtf->format_datetime($date);
751
752
    my $rs = $schema->resultset('DiscreteCalendar')->search(
753
        {
754
            branchcode  => $branchcode,
755
            isopened    => 1,
756
        },
757
        {
758
            where       => \['date > date(?)', $date],
759
            order_by    => { -asc => 'date' },
760
            rows        => 1
761
        }
762
    );
763
    return dt_from_string( $rs->next()->date(), 'iso');
764
}
765
766
sub prev_open_day {
767
    my ( $self, $date ) = @_;
768
    my $branchcode = $self->{branchcode};
769
    my $schema = Koha::Database->new->schema;
770
    my $dtf = $schema->storage->datetime_parser;
771
    $date = $dtf->format_datetime($date);
772
773
    my $rs = $schema->resultset('DiscreteCalendar')->search(
774
        {
775
            branchcode  => $branchcode,
776
            isopened    => 1,
777
        },
778
        {
779
            where       => \['date < date(?)', $date],
780
            order_by    => { -desc => 'date' },
781
            rows        => 1
782
        }
783
    );
784
    return dt_from_string( $rs->next()->date(), 'iso');
785
}
786
787
sub hours_between {
788
    my ($self, $start_dt, $end_dt) = @_;
789
    my $branchcode = $self->{branchcode};
790
    my $schema = Koha::Database->new->schema;
791
    my $dtf = $schema->storage->datetime_parser;
792
    my $start_date = $start_dt->clone();
793
    my $end_date = $end_dt->clone();
794
    my $duration = $end_date->delta_ms($start_date);
795
    $start_date->truncate( to => 'day' );
796
    $end_date->truncate( to => 'day' );
797
798
    # NB this is a kludge in that it assumes all days are 24 hours
799
    # However for hourly loans the logic should be expanded to
800
    # take into account open/close times then it would be a duration
801
    # of library open hours
802
    my $skipped_days = 0;
803
    $start_date = $dtf->format_datetime($start_date);
804
    $end_date = $dtf->format_datetime($end_date);
805
    my $hours_between = $schema->resultset('DiscreteCalendar')->search(
806
        {
807
            branchcode  =>  $branchcode,
808
            isopened    => 0
809
        },
810
        {
811
            where  => \[ 'date between ? and ?', $start_date, $end_date],
812
        }
813
    );
814
815
    if ($skipped_days = $hours_between->count()) {
816
        $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days));
817
    }
818
819
    return $duration;
820
}
821
822
sub open_hours_between {
823
    my ($self, $start_date, $end_date) = @_;
824
    my $branchcode = $self->{branchcode};
825
    my $schema = Koha::Database->new->schema;
826
    my $dtf = $schema->storage->datetime_parser;
827
    $start_date = $dtf->format_datetime($start_date);
828
    $end_date = $dtf->format_datetime($end_date);
829
830
    my $working_hours_between = $schema->resultset('DiscreteCalendar')->search(
831
        {
832
            branchcode  => $branchcode,
833
            isopened    => 1,
834
        },
835
        {
836
            select  => \['sum(time_to_sec(timediff(closehour, openhour)) / 3600)'],
837
            as      => [qw /hours_between/],
838
            where   => \['date BETWEEN DATE(?) AND DATE(?)', $start_date, $end_date]
839
        }
840
    );
841
842
    my $loan_day = $schema->resultset('DiscreteCalendar')->search(
843
        {
844
            branchcode  => $branchcode,
845
        },
846
        {
847
            where       => \['date = DATE(?)', $start_date],
848
        }
849
    );
850
851
    my $return_day = $schema->resultset('DiscreteCalendar')->search(
852
        {
853
            branchcode  => $branchcode,
854
        },
855
        {
856
            where       => \['date = DATE(?)', $end_date],
857
        }
858
    );
859
860
    #Capture the time portion of the date
861
    my $loan_date_time = $1 if $start_date =~ /\s(.*)/;
862
    my $return_date_time = $1 if $end_date =~ /\s(.*)/;
863
864
    my $not_used_hours = $schema->resultset('DiscreteCalendar')->search(
865
        {
866
            branchcode  => $branchcode,
867
            isopened    => 1,
868
        },
869
        {
870
            select  => \[ '(time_to_sec(timediff(?, ?)) + time_to_sec(timediff(?, ?)) ) / 3600', $return_day->next()->closehour(), $return_date_time, $loan_date_time, $loan_day->next()->openhour()],
871
            as      => [qw /not_used_hours/],
872
        }
873
    );
874
875
    return ($working_hours_between->next()->get_column('hours_between') - $not_used_hours->next()->get_column('not_used_hours'));
876
}
877
sub addDate {
878
    my ( $self, $startdate, $add_duration, $unit ) = @_;
879
880
    # Default to days duration (legacy support I guess)
881
    if ( ref $add_duration ne 'DateTime::Duration' ) {
882
        $add_duration = DateTime::Duration->new( days => $add_duration );
883
    }
884
885
    $unit ||= 'days'; # default days ?
886
    my $dt;
887
888
    if ( $unit eq 'hours' ) {
889
        # Fixed for legacy support. Should be set as a branch parameter
890
        my $return_by_hour = 10;
891
892
        $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
893
    } else {
894
        # days
895
        $dt = $self->addDays($startdate, $add_duration);
896
    }
897
898
    return $dt;
899
}
900
901
sub addHours {
902
    my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
903
    my $base_date = $startdate->clone();
904
905
    $base_date->add_duration($hours_duration);
906
907
    # If we are using the calendar behave for now as if Datedue
908
    # was the chosen option (current intended behaviour)
909
910
    if ( $self->{days_mode} ne 'Days' &&
911
    $self->is_holiday($base_date) ) {
912
913
        if ( $hours_duration->is_negative() ) {
914
            $base_date = $self->prev_open_day($base_date);
915
        } else {
916
            $base_date = $self->next_open_day($base_date);
917
        }
918
919
        $base_date->set_hour($return_by_hour);
920
921
    }
922
923
    return $base_date;
924
}
925
926
sub addDays {
927
    my ( $self, $startdate, $days_duration ) = @_;
928
    my $base_date = $startdate->clone();
929
930
    $self->{days_mode} ||= q{};
931
932
    if ( $self->{days_mode} eq 'Calendar' ) {
933
        # use the calendar to skip all days the library is closed
934
        # when adding
935
        my $days = abs $days_duration->in_units('days');
936
937
        if ( $days_duration->is_negative() ) {
938
            while ($days) {
939
                $base_date = $self->prev_open_day($base_date);
940
                --$days;
941
            }
942
        } else {
943
            while ($days) {
944
                $base_date = $self->next_open_day($base_date);
945
                --$days;
946
            }
947
        }
948
949
    } else { # Days or Datedue
950
        # use straight days, then use calendar to push
951
        # the date to the next open day if Datedue
952
        $base_date->add_duration($days_duration);
953
954
        if ( $self->{days_mode} eq 'Datedue' ) {
955
            # Datedue, then use the calendar to push
956
            # the date to the next open day if holiday
957
            if (!$self->isOpened($base_date) ) {
958
959
                if ( $days_duration->is_negative() ) {
960
                    $base_date = $self->prev_open_day($base_date);
961
                } else {
962
                    $base_date = $self->next_open_day($base_date);
963
                }
964
            }
965
        }
966
    }
967
968
    return $base_date;
969
}
970
971
1;
(-)a/installer/data/mysql/atomicupdate/bug_17015_koha_discrete_calendar.sql (+15 lines)
Line 0 Link Here
1
-- Bugzilla 17015
2
-- New koha calendar
3
-- Create discrete_calendar table to keep track of library day's information
4
5
CREATE TABLE `discrete_calendar` (
6
    `date` datetime NOT NULL,
7
    `branchcode` varchar(10) NOT NULL,
8
    `isopened` tinyint(1) DEFAULT 1,
9
    `holidaytype` varchar(1) DEFAULT '',
10
    `note` varchar(30) DEFAULT '',
11
    `openhour` time NOT NULL,
12
    `closehour` time NOT NULL,
13
    PRIMARY KEY (`branchcode`,`date`)
14
);
15
(-)a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/discrete_calendar.tt (+615 lines)
Line 0 Link Here
1
[% USE Branches %]
2
[% INCLUDE 'doc-head-open.inc' %]
3
<title>Koha &rsaquo; Tools &rsaquo; [% Branches.GetName( branch ) %] calendar</title>
4
[% INCLUDE 'doc-head-close.inc' %]
5
[% INCLUDE 'calendar.inc' %]
6
<link rel="stylesheet" type="text/css" href="[% interface %]/[% theme %]/css/datatables.css" />
7
<script type="text/javascript" src="/intranet-tmpl/lib/jquery/plugins/jquery-ui-timepicker-addon.min.js"></script>
8
[% INCLUDE 'datatables.inc' %]
9
<script type="text/javascript">
10
//<![CDATA[
11
    var weekdays = new Array(_("Sundays"),_("Mondays"),_("Tuesdays"),_("Wednesdays"),_("Thursdays"),_("Fridays"),_("Saturdays"));
12
    $("#jcalendar-container").datepicker({dateFormat:'mm/dd/yy', minDate: new Date(15,10,14) });
13
    /* Creates all the structures to deal with all different kinds of holidays */
14
    var datesInfos = new Array();
15
    [% FOREACH date IN datesInfos %]
16
    datesInfos["[% date.date %]"] = {title : "[% date.note %]", outputdate : "[% date.outputdate %]", holidaytype:"[% date.holidaytype %]", openhour: "[% date.openhour %]", closehour: "[% date.closehour %]"};
17
    [% END %]
18
19
    function holidayOperation(formObject, opType) {
20
        var op = document.getElementsByName('Operation');
21
        op[0].value = opType;
22
        formObject.submit();
23
    }
24
25
    // This function shows the "Show Holiday" panel
26
    function showHoliday (dayName, day, month, year, weekDay, title, holidayType) {
27
        $("#newHoliday").slideDown("fast");
28
        $("#copyHoliday").slideUp("fast");
29
        $('#newDaynameOutput').html(dayName);
30
        $('#newDayname').val(dayName);
31
        $('#newBranchNameOutput').html($("#branch :selected").text());
32
        $(".newHoliday ,#BranchName").val($('#branch').val());
33
        $('#newDayOutput').html(day);
34
        $(".newHoliday #Day").val(day);
35
        $(".newHoliday #Month").val(month);
36
        $(".newHoliday #Year").val(year);
37
        $("#newMonthOutput").html(month);
38
        $("#newYearOutput").html(year);
39
        $(".newHoliday, #Weekday").val(weekDay);
40
41
        $('.newHoliday #title').val(title);
42
        $('#HolidayType').val(holidayType);
43
44
        //You can't delete holiday based on type  for single, floating, need validation holidays. This will show/hide the option based on type
45
        if(holidayType !='weekday' && holidayType != 'daymonth'){
46
            $('#deleteTypeOption').hide();
47
        }else{
48
            $('#deleteTypeOption').show();
49
        }
50
51
        if(holidayType == 'weekday') {
52
            // $("#showOperationDelLabel").html(_("Delete this holiday."));
53
            $("#holtype").attr("class","key repeatableweekly").html(_("Holiday repeating weekly"));
54
        } else if(holidayType == 'daymonth') {
55
            // $("#showOperationDelLabel").html(_("Delete this holiday."));
56
            $("#holtype").attr("class","key repeatableyearly").html(_("Holiday repeating yearly"));
57
        } else if(holidayType == 'float') {
58
            // $("#showOperationDelLabel").html(_("Delete this holiday."));
59
            $("#holtype").attr("class","key float").html(_("Floating holiday"));
60
        } else if(holidayType == 'N') {
61
            // $("#showOperationDelLabel").html(_("Delete this holiday."));
62
            $("#holtype").attr("class","key exception").html(_("Needs validation"));
63
        } else if(holidayType == 'ymd') {
64
            // $("#showOperationDelLabel").html(_("Delete this holiday."));
65
            $("#holtype").attr("class","key holiday").html(_("Unique holiday"));
66
        } else{
67
            $("#holtype").attr("class","key normalday").html(_("Working day "));
68
        }
69
    }
70
71
    function hidePanel(aPanelName) {
72
        $("#"+aPanelName).slideUp("fast");
73
    }
74
75
    function changeBranch () {
76
        var branch = $("#branch option:selected").val();
77
        location.href='/cgi-bin/koha/tools/discrete_calendar.pl?branch=' + branch + '&calendardate=' + "[% calendardate %]";
78
    }
79
80
    function Help() {
81
        newin=window.open("/cgi-bin/koha/help.pl","KohaHelp",'width=600,height=600,toolbar=false,scrollbars=yes');
82
    }
83
84
    // This function gives css clases to each kind of day
85
    function dateStatusHandler(date) {
86
        date = getSeparetedDate(date);
87
        var day = date.day;
88
        var month = date.month;
89
        var year = date.year;
90
        var weekDay = date.weekDay;
91
        var dayName = weekdays[weekDay];
92
        var dayMonth = date.dayMonth;
93
        var dateString = date.dateString;
94
95
        if (datesInfos[dateString] && datesInfos[dateString].holidaytype =='W'){
96
            return [true, "repeatableweekly", _("Weekly holiday: %s").format(datesInfos[dateString].title)];
97
        } else if (datesInfos[dateString] && datesInfos[dateString].holidaytype == 'R') {
98
            return [true, "repeatableyearly", _("Yearly holiday: %s").format(datesInfos[dateString].title)];
99
        } else if (datesInfos[dateString] && datesInfos[dateString].holidaytype == 'N') {
100
            return [true, "exception", _("Need validation: %s").format(datesInfos[dateString].title)];
101
        } else if (datesInfos[dateString] && datesInfos[dateString].holidaytype == 'F') {
102
            return [true, "float", _("Floating holiday: %s").format(datesInfos[dateString].title)];
103
        } else if (datesInfos[dateString] && datesInfos[dateString].holidaytype == 'E') {
104
            return [true, "holiday", _("Single holiday: %s").format(datesInfos[dateString].title)];
105
        } else {
106
            return [true, "normalday", _("Normal day")];
107
        }
108
    }
109
110
    /* This function is in charge of showing the correct panel considering the kind of holiday */
111
    function dateChanged(text, calendar) {
112
        calendar = getSeparetedDate(calendar);
113
        var day = calendar.day;
114
        var month = calendar.month;
115
        var year = calendar.year;
116
        var weekDay = calendar.weekDay;
117
        var dayName = weekdays[weekDay];
118
        var dayMonth = calendar.dayMonth;
119
        var dateString = calendar.dateString;
120
        //set value of form hidden field
121
        $('#fromDate').val(dateString);
122
        $('#from_copyFrom').val(text);
123
        if (datesInfos[dateString].holidaytype =='E') {
124
            showHoliday(dayName, day, month, year, weekDay, datesInfos[dateString].title,'ymd');
125
            showDateInfo(dateString);
126
        } else if (datesInfos[dateString].holidaytype =='W') {
127
            showHoliday(dayName, day, month, year, weekDay, datesInfos[dateString].title, 'weekday');
128
            showDateInfo(dateString);
129
        } else if (datesInfos[dateString].holidaytype =='R') {
130
            showHoliday(dayName, day, month, year, weekDay, datesInfos[dateString].title, 'daymonth');
131
            showDateInfo(dateString);
132
        } else if (datesInfos[dateString].holidaytype =='F') {
133
            showHoliday(dayName, day, month, year, weekDay, datesInfos[dateString].title, 'float');
134
            showDateInfo(dateString);
135
        } else if (datesInfos[dateString].holidaytype =='N') {
136
            showHoliday(dayName, day, month, year, weekDay, datesInfos[dateString].title, 'N');
137
            showDateInfo(dateString);
138
        }else {
139
            showHoliday(dayName, day, month, year, weekDay, '', 'normalday');
140
            showDateInfo(dateString);
141
        }
142
    }
143
144
    function showDateInfo (date){
145
        $("#dateInfo").css('visibility', 'visible');
146
        $('#openHour').val(datesInfos[date].openhour);
147
        $('#closeHour').val(datesInfos[date].closehour);
148
        $('#openHour').timepicker({
149
            showOn : 'focus',
150
            timeFormat: 'HH:mm:ss',
151
            defaultTime: datesInfos[date].openhour,
152
            showSecond: false,
153
            stepMinute: 5,
154
        });
155
        $('#closeHour').timepicker({
156
            showOn : 'focus',
157
            timeFormat: 'HH:mm:ss',
158
            defaultTime: datesInfos[date].closehour,
159
            showSecond: false,
160
            stepMinute: 5,
161
        });
162
        $('#closeHour').val(datesInfos[date].closehour);
163
        $('#date').html(datesInfos[date].outputdate);
164
165
        if (datesInfos[date].holidaytype !=''){
166
            var type = datesInfos[date].holidaytype;
167
            $('#holidayType option[value="'+ type +'"]').attr('selected', true)
168
        }else{
169
            $('#holidayType option[value="none"]').attr('selected', true)
170
        }
171
        $(".dateDetailsPanel ,#BranchName").val($('#branch').val());
172
        if(datesInfos[date].holidaytype == 'W' || datesInfos[date].holidaytype == 'R'){
173
            $('#deleteType').show("fast");
174
        }else{
175
            $('#deleteType').hide("fast");
176
        }
177
178
    }
179
    function getSeparetedDate(date){
180
        var mydate = new Array();
181
        var day = (date.getDate() < 10 ? '0' : '') + date.getDate();
182
        var month = ((date.getMonth()+1) < 10 ? '0' : '') + (date.getMonth() +1);
183
        var year = date.getFullYear();
184
        var weekDay = date.getDay();
185
        var dayMonth = (date.getMonth()+1) + '/' + date.getDate();
186
        var dateString = year + '-' + month + '-' + day;
187
        mydate = {dateObj : date, date : date ,dateString : dateString, dayMonth: dayMonth, weekDay: weekDay, year: year, month: month, day: day};
188
189
        return mydate;
190
    }
191
192
    function validateForm(form){
193
194
        if(form =='newHoliday' && $('#from_copyToDatePicker').val() && $('#CopyRadioButton').is(':checked')){
195
            var from_DateFrom = new Date($("#jcalendar-container").datepicker("getDate"));
196
            var from_DateTo = new Date($('#from_copyToDatePicker').datepicker("getDate"));
197
            var to_DateFrom = new Date($('#to_copyFromDatePicker').datepicker("getDate"));
198
            var to_DateTo = new Date($('#to_copyToDatePicker').datepicker("getDate"));
199
200
            var from_start = Math.round( from_DateFrom.getTime() / (3600*24*1000)); //days as integer from..
201
            var from_end   = Math.round( from_DateTo.getTime() / (3600*24*1000));
202
            var to_start = Math.round( to_DateFrom.getTime() / (3600*24*1000));
203
            var to_end   = Math.round( to_DateTo.getTime() / (3600*24*1000));
204
205
            var from_daysDiff = from_end - from_start;
206
            var to_daysDiff = to_end - to_start;
207
208
            if(from_daysDiff == to_daysDiff || from_daysDiff ==1){
209
                $('#daysnumber').val(to_daysDiff)
210
                return true;
211
            }else{
212
                alert("You have to pick the same number of days if you choose 2 ranges");
213
                return false;
214
            }
215
        }else {
216
            return 1;
217
        }
218
    }
219
220
    //Check if date range have the same opening, closing hours and holiday type if there's one.
221
    function checkRange(date){
222
        date = new Date(date);
223
        $('#toDate').val(getSeparetedDate(date).dateString);
224
        var fromDate = new Date($("#jcalendar-container").datepicker("getDate"));
225
        var sameHoliday =true;
226
        var sameOpenHours =true;
227
        var sameCloseHours =true;
228
229
        for (var i = fromDate; i <= date ; i.setDate(i.getDate() + 1)) {
230
            var myDate1 = getSeparetedDate(i);
231
            var date1 = myDate1.dateString;
232
            var holidayType1 = datesInfos[date1].holidaytype;
233
            var openhours1 = datesInfos[date1].openhour;
234
            var closehours1 = datesInfos[date1].closehour;
235
            for (var j = fromDate; j <= date ; j.setDate(j.getDate() + 1)) {
236
                var myDate2 = getSeparetedDate(j);
237
                var date2 = myDate2.dateString;
238
                var holidayType2 = datesInfos[date2].holidaytype;
239
                var openhours2 = datesInfos[date2].openhour;
240
                var closehours2 = datesInfos[date2].closehour;
241
242
                if (sameHoliday && holidayType1 != holidayType2){
243
                    $('#holidayType option[value="empty"]').attr('selected', true)
244
                    sameHoliday=false;
245
                }
246
                if(sameOpenHours && (openhours1 != openhours2)){
247
                    $('#openHour').val('');
248
                    sameOpenHours=false;
249
                }
250
                if(sameCloseHours && (closehours1 != closehours2)){
251
                    $('#closeHour').val('');
252
                    sameCloseHours=false;
253
                }
254
            }
255
            if (!sameOpenHours && !sameCloseHours && !sameHoliday){
256
                return false;
257
            }
258
        }
259
        return true;
260
}
261
    $(document).ready(function() {
262
        $(".hint").hide();
263
        $("#branch").change(function(){
264
            changeBranch();
265
        });
266
        $("#holidayweeklyrepeatable>tbody>tr").each(function(){
267
            var first_td = $(this).find('td').first();
268
            first_td.html(weekdays[first_td.html()]);
269
        });
270
        $("a.helptext").click(function(){
271
            $(this).parent().find(".hint").toggle(); return false;
272
        });
273
        $("#from_copyFrom").each(function () { this.value = "" });
274
        $("#copyToDp").each(function () { this.value = "" });
275
        $("#to_copyFrom").each(function () { this.value = "" });
276
        $("#to_copyTo").each(function () { this.value = "" });
277
        $("#jcalendar-container").datepicker({
278
          beforeShowDay: function(thedate) {
279
            return dateStatusHandler(thedate);
280
            },
281
        onSelect: function(dateText, inst) {
282
            dateChanged(dateText, $(this).datepicker("getDate"));
283
        },
284
        defaultDate: new Date("[% keydate %]"),
285
        minDate: new Date("[% minDate %]"),
286
        maxDate: new Date("[% maxDate %]")
287
        });
288
        $("#from_copyToDatePicker").change(function(){
289
            checkRange($(this).datepicker("getDate"));
290
        });
291
292
        $("#from_copyFromDatePicker").change(function(){
293
            $('#from_copyFrom').val(getSeparetedDate($(this).datepicker("getDate")).dateString);
294
        });
295
        $("#from_copyToDatePicker").change(function(){
296
            $('#from_copyTo').val(getSeparetedDate($(this).datepicker("getDate")).dateString);
297
        });
298
        $("#to_copyFromDatePicker").change(function(){
299
            $('#to_copyFrom').val(getSeparetedDate($(this).datepicker("getDate")).dateString);
300
        });
301
        $("#to_copyToDatePicker").change(function(){
302
            $('#to_copyTo').val(getSeparetedDate($(this).datepicker("getDate")).dateString);
303
        });
304
        $('.newHoliday input[type="radio"]').click(function () {
305
            if ($(this).attr("id") == "CopyRadioButton") {
306
                $(".CopyToBranchPanel").hide('fast');
307
                $(".CopyDatePanel").show('fast');
308
            } else if ($(this).attr("id") == "CopyToBranchRadioButton"){
309
                $(".CopyDatePanel").hide('fast');
310
                $(".CopyToBranchPanel").show('fast');
311
            } else{
312
                $(".CopyDatePanel").hide('fast');
313
                $(".CopyToBranchPanel").hide('fast');
314
            }
315
        });
316
        $(".hidePanel").on("click",function(){
317
            if( $(this).hasClass("showHoliday") ){
318
                hidePanel("showHoliday");
319
            }if ($(this).hasClass('newHoliday')) {
320
                hidePanel("newHoliday");
321
            }else {
322
                hidePanel("copyHoliday");
323
            }
324
        })
325
    });
326
//]]>
327
</script>
328
<!-- Datepicker colors -->
329
<style type="text/css"> .key { padding : 3px; white-space:nowrap; line-height:230%; }
330
.ui-datepicker { font-size : 150%; }
331
#jcalendar-container .ui-datepicker { font-size : 185%; }
332
.ui-datepicker th, .ui-datepicker .ui-datepicker-title select { font-size : 80%; }
333
.ui-datepicker td a { padding : .5em; }
334
.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { font-size : 80%; }
335
.key { padding : 3px; white-space:nowrap; line-height:230%; }
336
.normalday { background-color :  #EDEDED; color :  Black; border : 1px solid #BCBCBC; }
337
.ui-datepicker-unselectable { padding :.5em; white-space:nowrap;}
338
.ui-state-disabled { padding :.5em; white-space:nowrap;}
339
.exception { background-color :  #b3d4ff; color :  Black; border : 1px solid #BCBCBC; }
340
.float { background-color :  #66ff33; color :  Black; border : 1px solid #BCBCBC; }
341
.holiday {  background-color :  #ffaeae; color :  Black;  border : 1px solid #BCBCBC; }
342
.repeatableweekly {  background-color :  #FFFF99; color :  Black;  border : 1px solid #BCBCBC; }
343
.repeatableyearly {  background-color :  #FFCC66; color :  Black;  border : 1px solid #BCBCBC; }
344
td.exception a.ui-state-default { background:  #b3d4ff none; color :  Black; border : 1px solid #BCBCBC; }
345
td.float a.ui-state-default { background:  #66ff33 none; color :  Black; border : 1px solid #BCBCBC; }
346
td.holiday a.ui-state-default {  background:  #ffaeae none; color :  Black;  border : 1px solid #BCBCBC; }
347
td.repeatableweekly a.ui-state-default {  background:  #FFFF99 none; color :  Black;  border : 1px solid #BCBCBC; }
348
td.repeatableyearly a.ui-state-default {  background:  #FFCC66 none; color :  Black;  border : 1px solid #BCBCBC; }
349
.information { z-index : ; background-color :  #DCD2F1; width : 300px; display : none; border : 1px solid #000000; color :  #000000; font-size :  8pt; font-weight :  bold; background-color :  #FFD700; cursor :  pointer; padding : 2px; }
350
.panel { z-index : 1; display : none; border : 3px solid #CCC; padding : 3px; margin-top: .3em;  background-color: #FEFEFE; } fieldset.brief { border : 0; margin-top: 0; }
351
#showHoliday { margin : .5em 0; } h1 select { width: 20em; } div.yui-b fieldset.brief ol { font-size:100%; } div.yui-b fieldset.brief li, div.yui-b fieldset.brief li.radio  { padding:0.2em 0; } .help { margin:.3em 0;border:1px solid #EEE;padding:.3em .7em; font-size : 90%; } #holidayweeklyrepeatable, #holidaysyearlyrepeatable, #holidaysunique, #holidayexceptions { font-size : 90%; margin-bottom : 1em;} .calendar td, .calendar th, .calendar .button, .calendar tbody .day { padding : .7em; font-size: 110%; } .calendar { width: auto; border : 0; }
352
.copyHoliday form li{ display:table-row } .copyHoliday form li b, .copyHoliday form li input{ display:table-cell; margin-bottom: 2px; }
353
</style>
354
</head>
355
<body id="tools_holidays" class="tools">
356
[% INCLUDE 'header.inc' %]
357
[% INCLUDE 'cat-search.inc' %]
358
359
<div id="breadcrumbs"><a href="/cgi-bin/koha/mainpage.pl">Home</a> &rsaquo; <a href="/cgi-bin/koha/tools/tools-home.pl">Tools</a> &rsaquo; [% Branches.GetName( branch ) %] calendar</div>
360
361
<div id="doc3" class="yui-t1">
362
363
   <div id="bd">
364
    <div id="yui-main">
365
    <div class="yui-b">
366
    <h2>[% Branches.GetName( branch ) %] calendar</h2>
367
    <div class="yui-g">
368
    <div class="yui-u first" style="width:60%">
369
        <label for="branch">Define the holidays for:</label>
370
            <select id="branch" name="branch">
371
                [% PROCESS options_for_libraries libraries => Branches.all( selected => branch ) %]
372
            </select>
373
374
            <h3>Calendar information</h3>
375
            <div id="jcalendar-container" style="float: left"></div>
376
    <!-- ***************************** Panel to deal with new holidays **********************  -->
377
    <div class="panel newHoliday" id="newHoliday" style="float: left; margin-left:15px">
378
        <form method="post" onsubmit="return validateForm('newHoliday')">
379
            <fieldset class="brief">
380
                <h3>Add new holiday</h3>
381
                <ol>
382
                    <li>
383
                        <strong>Library:</strong>
384
                        <span id="newBranchNameOutput"></span>
385
                        <input type="hidden" id="BranchName" name="BranchName" />
386
                    </li>
387
                    <li>
388
                        <strong>From date:</strong>
389
                        <span id="newDaynameOutput"></span>,
390
391
                        [% IF ( dateformat == "us" ) %]<span id="newMonthOutput"></span>/<span id="newDayOutput"></span>/<span id="newYearOutput"></span>[% ELSIF ( dateformat == "metric" ) %]<span id="newDayOutput"></span>/<span id="newMonthOutput"></span>/<span id="newYearOutput"></span>[% ELSIF ( dateformat == "dmydot" ) %]<span id="newDayOutput"></span>.<span id="newMonthOutput"></span>.<span id="newYearOutput"></span>[% ELSE %]<span id="newYearOutput"></span>/<span id="newMonthOutput"></span>/<span id="newDayOutput"></span>[% END %]
392
393
                        <input type="hidden" id="newDayname" name="showDayname" />
394
                        <input type="hidden" id="Weekday" name="Weekday" />
395
                        <input type="hidden" id="Day" name="Day" />
396
                        <input type="hidden" id="Month" name="Month" />
397
                        <input type="hidden" id="Year" name="Year" />
398
                    </li>
399
                    <li class="dateinsert">
400
                        <b>To date: </b>
401
                        <input type="text" id="from_copyToDatePicker" name="toDate" size="20" class="datepicker" />
402
                    </li>
403
                    <li>
404
                        <label for="title">Title: </label><input type="text" name="Title" id="title" size="35" />
405
                    </li>
406
                    <li id="holidayType">
407
                        <label for="holidayType">Date type</label>
408
                        <select name ='holidayType'>
409
                            <option value="empty"></option>
410
                            <option value="none">Normal day</option>
411
                            <option value="R">Fixed</option>
412
                            <option value="E">Exception</option>
413
                            <option value="W">Weekly</option>
414
                            <option value="F">Floating</option>
415
                            <option value="N" disabled>Need validation</option>
416
                        </select>
417
                    </li>
418
                    <li class="radio" id="deleteType" style="display : none;" >
419
                        <input type="checkbox" name="deleteType" id="deleteType_checkbox" value="1" ><label for="deleteType_checkbox"> Delete this type</label>
420
                        <a href="#" class="helptext">[?]</a>
421
                        <div class="hint">Remove all repeated or weekly holidays of the selected date or week day <br> if normal day is selected.</div>
422
                    </li>
423
                    <li>
424
                        <label for="openHour">Open hours: </label><input type="text" name="openHour" id='openHour' style="display :flex"  >
425
                    </li>
426
                    <li>
427
                        <label for="closeHour">Close hours: </label><input type="text" name="closeHour" id='closeHour' style="display :flex" >
428
                    </li>
429
                    <li class="radio">
430
                        <input type="radio" name="action" id="EditRadioButton" value="edit" checked/>
431
                        <label for="EditRadioButton">Edit selected dates</label>
432
                    </li>
433
                    <li class="radio">
434
                        <input type="radio" name="action" id="CopyRadioButton" value="copyDates" />
435
                        <label for="CopyRadioButton">Copy to different dates</label>
436
                        <div class="CopyDatePanel" style="display:none; padding-left:15px">
437
438
                            <b>From : </b>
439
        	                <input type="text" id="to_copyFromDatePicker" size="20" class="datepicker"/>
440
        	                <b>To : </b>
441
        	                <input type="text" id="to_copyToDatePicker" size="20" class="datepicker"/>
442
                        </div>
443
                        <input type="hidden" name="daysnumber" id='daysnumber'>
444
                        <!-- These  yyyy-mm-dd -->
445
                        <input type="hidden" name="from_copyFrom" id='from_copyFrom'>
446
                        <input type="hidden" name="from_copyTo" id='from_copyTo'>
447
                        <input type="hidden" name="to_copyFrom" id='to_copyFrom'>
448
                        <input type="hidden" name="to_copyTo" id='to_copyTo'>
449
                    </li>
450
                    <li class="radio">
451
                        <input type="radio" name="action" id="CopyToBranchRadioButton" value="copyBranch" />
452
                        <label for="CopyToBranchRadioButton">Copy calendar to an other branch</label>
453
                        <div class="CopyToBranchPanel" style="display:none; padding-left:15px">
454
                            <label>Copy to : </label>
455
                            <select name ='newBranch'>
456
                                [% PROCESS options_for_libraries libraries => Branches.all( selected => branch ) %]
457
                            </select>
458
                        </div>
459
                    </li>
460
                </ol>
461
                <fieldset class="action">
462
                    <input type="submit" name="submit" value="Save" />
463
                    <a href="#" class="cancel hidePanel newHoliday">Cancel</a>
464
                </fieldset>
465
            </fieldset>
466
        </form>
467
    </div>
468
469
<!-- ************************************************************************************** -->
470
<!-- ******                              MAIN SCREEN CODE                            ****** -->
471
<!-- ************************************************************************************** -->
472
473
</div>
474
<div class="yui-u" style="width : 40%">
475
    <div class="help">
476
        <h4>Hints</h4>
477
        <ul>
478
            <li>Search in the calendar the day you want to set as holiday.</li>
479
            <li>Click the date to add or edit a holiday.</li>
480
            <li>Specify how the holiday should repeat.</li>
481
            <li>Click Save to finish.</li>
482
            <li>PS:
483
                <ul>
484
                    <li>You can't edit passed dates</li>
485
                    <li>Weekly holidays change open/close hours for all the days affected unless inputs are empty</li>
486
                </ul>
487
            </li>
488
        </ul>
489
        <h4>Key</h4>
490
        <p>
491
            <span class="key normalday">Working day </span>
492
            <span class="key holiday">Unique holiday</span>
493
            <span class="key repeatableweekly">Holiday repeating weekly</span>
494
            <span class="key repeatableyearly">Holiday repeating yearly</span>
495
            <span class="key float">Floating holiday</span>
496
            <span class="key exception">Need validation</span>
497
        </p>
498
    </div>
499
<div id="holiday-list">
500
501
    [% IF ( NEED_VALIDATION_HOLIDAYS ) %]
502
    <h3>Need validation holidays</h3>
503
    <table id="holidaysunique">
504
        <thead>
505
            <tr>
506
                <th class="exception">Date</th>
507
                <th class="exception">Title</th>
508
            </tr>
509
        </thead>
510
        <tbody>
511
            [% FOREACH need_validation_holiday IN NEED_VALIDATION_HOLIDAYS %]
512
            <tr>
513
                <td><a href="/cgi-bin/koha/tools/discrete_calendarte_holiday.pl?branch=[% branch %]&amp;calendardate=[% need_validation_holiday.date %]"><span title="[% need_validation_holiday.DATE_SORT %]">[% need_validation_holiday.outputdate %]</span></a></td>
514
                <td>[% need_validation_holiday.note %]</td>
515
            </tr>
516
            [% END %]
517
        </tbody>
518
    </table>
519
    [% END %]
520
521
    [% IF ( week_days ) %]
522
    <h3>Weekly - Repeatable holidays</h3>
523
    <table id="holidayweeklyrepeatable">
524
        <thead>
525
            <tr>
526
                <th class="repeatableweekly">Day of week</th>
527
                <th class="repeatableweekly">Title</th>
528
            </tr>
529
        </thead>
530
        <tbody>
531
            [% FOREACH WEEK_DAYS_LOO IN week_days %]
532
            <tr>
533
                <td>[% WEEK_DAYS_LOO.weekday %]</td>
534
            </td>
535
            <td>[% WEEK_DAYS_LOO.note %]</td>
536
        </tr>
537
        [% END %]
538
    </tbody>
539
</table>
540
[% END %]
541
542
[% IF ( repeatable_holidays ) %]
543
<h3>Yearly - Repeatable holidays</h3>
544
<table id="holidaysyearlyrepeatable">
545
    <thead>
546
        <tr>
547
            [% IF ( dateformat == "metric" ) %]
548
            <th class="repeatableyearly">Day/month</th>
549
            [% ELSE %]
550
            <th class="repeatableyearly">Month/day</th>
551
            [% END %]
552
            <th class="repeatableyearly">Title</th>
553
        </tr>
554
    </thead>
555
    <tbody>
556
        [% FOREACH DAY_MONTH_HOLIDAYS_LOO IN repeatable_holidays %]
557
        <tr>
558
            <td><span title="[% DAY_MONTH_HOLIDAYS_LOO.DATE_SORT %]">[%DAY_MONTH_HOLIDAYS_LOO.month%]/[% DAY_MONTH_HOLIDAYS_LOO.day %]</span></td>
559
            <td>[% DAY_MONTH_HOLIDAYS_LOO.note %]</td>
560
        </tr>
561
        [% END %]
562
    </tbody>
563
</table>
564
[% END %]
565
566
[% IF ( HOLIDAYS_LOOP ) %]
567
<h3>Unique holidays</h3>
568
<table id="holidaysunique">
569
    <thead>
570
        <tr>
571
            <th class="holiday">Date</th>
572
            <th class="holiday">Title</th>
573
        </tr>
574
    </thead>
575
    <tbody>
576
        [% FOREACH HOLIDAYS_LOO IN HOLIDAYS_LOOP %]
577
        <tr>
578
            <td><a href="/cgi-bin/koha/tools/discrete_calendarte_holiday.pl?branch=[% branch %]&amp;calendardate=[% HOLIDAYS_LOO.date %]"><span title="[% HOLIDAYS_LOO.DATE_SORT %]">[% HOLIDAYS_LOO.outputdate %]</span></a></td>
579
            <td>[% HOLIDAYS_LOO.note %]</td>
580
        </tr>
581
        [% END %]
582
    </tbody>
583
</table>
584
[% END %]
585
586
[% IF ( FLOAT_HOLIDAYS ) %]
587
<h3>Floating upcoming holidays</h3>
588
<table id="holidaysunique">
589
    <thead>
590
        <tr>
591
            <th class="float">Date</th>
592
            <th class="float">Title</th>
593
        </tr>
594
    </thead>
595
    <tbody>
596
        [% FOREACH float_holiday IN FLOAT_HOLIDAYS %]
597
        <tr>
598
            <td><a href="/cgi-bin/koha/tools/discrete_calendarte_holiday.pl?branch=[% branch %]&amp;calendardate=[% float_holiday.date %]"><span title="[% float_holiday.DATE_SORT %]">[% float_holiday.outputdate %]</span></a></td>
599
            <td>[% float_holiday.note %]</td>
600
        </tr>
601
        [% END %]
602
    </tbody>
603
</table>
604
[% END %]
605
</div>
606
</div>
607
</div>
608
</div>
609
</div>
610
611
<div class="yui-b noprint">
612
[% INCLUDE 'tools-menu.inc' %]
613
</div>
614
</div>
615
[% INCLUDE 'intranet-bottom.inc' %]
(-)a/misc/cronjobs/add_days_discrete_calendar.pl (+113 lines)
Line 0 Link Here
1
#!/usr/bin/perl
2
3
#
4
#   This script adds one day into discrete_calendar table based on the same day from the week before
5
#
6
use strict;
7
use warnings;
8
use DateTime;
9
use DateTime::Format::Strptime;
10
use Getopt::Long;
11
use C4::Context;
12
13
# Options
14
my $help = 0;
15
my $daysInFuture =1;
16
GetOptions (
17
    'help|?|h'  => \$help,
18
    'n=i'       => \$daysInFuture);
19
20
my $usage = << 'ENDUSAGE';
21
22
This script adds days into discrete_calendar table based on the same day from the week before.
23
24
Examples :
25
    The latest date on discrete_calendar is : 28-07-2017
26
    The current date : 01-08-2016
27
    The dates that will be added are : 29-07-2017, 30-07-2017, 31-07-2017, 01-08-2017
28
Open close exemples :
29
    Date added is : 29-07-2017
30
    Opening/closing hours will be base on : 22-07-2017 (- 7 days)
31
    Library open or closed will be based on : 29-07-2017 (- 1 year)
32
This script has the following parameters:
33
    -h --help: this message
34
    -n : number of days to add in the futre, default : 1
35
36
PS: This is for testing purposes, the method of knowing whether it's opened or not may be changed.
37
38
ENDUSAGE
39
my $dbh = C4::Context->dbh;
40
my $query = "SELECT distinct weekday(date), note FROM discrete_calendar where holidaytype='W'";
41
my $stmt = $dbh->prepare($query);
42
$stmt->execute();
43
my @week_days_discrete;
44
while (my ($weekday,$note) = $stmt->fetchrow_array){
45
    push @week_days_discrete, {weekday => $weekday, note => $note};
46
}
47
48
if ($help) {
49
    print $usage;
50
    exit;
51
}
52
53
#getting the all the branches
54
my $selectBranchesSt = 'SELECT branchcode FROM branches';
55
my $selectBranchesSth = $dbh->prepare($selectBranchesSt);
56
$selectBranchesSth->execute();
57
my @branches = ();
58
while ( my $branchCode = $selectBranchesSth->fetchrow_array ) {
59
60
    push @branches,$branchCode;
61
}
62
63
#get the latest date in the table
64
$query = "SELECT MAX(date) FROM discrete_calendar";
65
$stmt = $dbh->prepare($query);
66
$stmt->execute();
67
my $latestedDate = $stmt->fetchrow_array;
68
my $parser = DateTime::Format::Strptime->new(
69
    pattern => '%Y-%m-%d %H:%M:%S',
70
    on_error => 'croak',
71
);
72
$latestedDate = $parser->parse_datetime($latestedDate);
73
74
my $endDate = DateTime->today->add( years => 1, days => $daysInFuture);
75
my $newDay = $latestedDate->clone();
76
77
for ($newDay->add(days => 1);$newDay <= $endDate;$newDay->add(days => 1)){
78
    my $lastWeekDay = $newDay->clone();
79
    $lastWeekDay->add(days=> -8);
80
    my $dayOfWeek = $lastWeekDay->day_of_week;
81
    # Representation fix
82
    # DateTime object dow (1-7) where Monday is 1
83
    # Arrays are 0-based where 0 = Sunday, not 7.
84
    $dayOfWeek -= 1 unless $dayOfWeek == 7;
85
    $dayOfWeek = 0 if $dayOfWeek == 7;
86
87
    #checking if it was open on the same day from last year
88
    my $yearAgo = $newDay->clone();
89
    $yearAgo = $yearAgo->add(years => -1);
90
    my $last_year = 'SELECT isopened, holidaytype, note, openhour, closehour FROM discrete_calendar WHERE date=? AND branchcode=?';
91
    my $day_last_week = "SELECT openhour, closehour FROM discrete_calendar WHERE DAYOFWEEk(date)=DAYOFWEEK(?) and date < ? order by date desc limit 1";
92
    my $add_Day = 'INSERT INTO discrete_calendar (date,branchcode,isopened,openhour,closehour) VALUES (?,?,?,?,?)';
93
    my $note ='';
94
    #insert into discrete_calendar for each branch
95
    foreach my $branchCode(@branches){
96
        $stmt = $dbh->prepare($last_year);
97
        $stmt->execute($yearAgo,$branchCode);
98
        my ($isOpened, $holidaytype, $note) = $stmt->fetchrow_array;
99
        if ($holidaytype && $holidaytype eq "W"){
100
            $isOpened = 1;
101
            $note='';
102
        }elsif ($holidaytype && $holidaytype eq "F" || $holidaytype eq 'E'){
103
            $holidaytype = 'N';
104
        }
105
        $holidaytype = '' if $isOpened;
106
        $stmt = $dbh->prepare($day_last_week);
107
        $stmt->execute($newDay, $newDay);
108
        my ($openhour,$closehour ) = $stmt->fetchrow_array;
109
        my $add_Day = 'INSERT INTO discrete_calendar (date,branchcode,isopened,holidaytype, note,openhour,closehour) VALUES (?,?,?,?,?,?,?)';
110
        $stmt = $dbh->prepare($add_Day);
111
        $stmt->execute($newDay,$branchCode,$isOpened,$holidaytype,$note, $openhour,$closehour);
112
    }
113
}
(-)a/misc/generate_discrete_calendar.pl (+165 lines)
Line 0 Link Here
1
#!/usr/bin/perl
2
3
#
4
#   Script that fills the discrete_calendar table with dates, using the other date-related tables
5
#
6
use strict;
7
use warnings;
8
use DateTime;
9
use DateTime::Format::Strptime;
10
use Getopt::Long;
11
use C4::Context;
12
13
# Options
14
my $help = 0;
15
my $daysInFuture = 365;
16
GetOptions (
17
            'days|?|d=i' => \$daysInFuture,
18
            'help|?|h' => \$help);
19
my $usage = << 'ENDUSAGE';
20
21
Script that manages the discrete_calendar table.
22
23
This script has the following parameters :
24
    --days --d : how many days in the future will be created, by default it's 365
25
    -h --help: this message
26
    --generate: fills discrete_calendar table with dates from the last two years and the next one
27
28
ENDUSAGE
29
30
if ($help) {
31
    print $usage;
32
    exit;
33
}
34
my $dbh = C4::Context->dbh;
35
36
my $currentDate = DateTime->today;
37
38
# two years ago
39
my $startDate = DateTime->new(
40
day       => $currentDate->day(),
41
month     => $currentDate->month(),
42
year      => $currentDate->year()-2,
43
time_zone => C4::Context->tz()
44
)->truncate( to => 'day' );
45
46
# a year into the future
47
my $endDate = DateTime->new(
48
day       => $currentDate->day(),
49
month     => $currentDate->month(),
50
year      => $currentDate->year(),
51
time_zone => C4::Context->tz()
52
)->truncate( to => 'day' );
53
$endDate->add(days => $daysInFuture);
54
55
#Added a default (standard) branch.
56
my $add_default_branch = 'INSERT INTO branches (branchname, branchcode) VALUES(?,?)';
57
my $add_Branch_Sth = $dbh->prepare($add_default_branch);
58
$add_Branch_Sth->execute('Default', 'DFLT');
59
# finds branches;
60
my $selectBranchesSt = 'SELECT branchcode FROM branches';
61
my $selectBranchesSth = $dbh->prepare($selectBranchesSt);
62
$selectBranchesSth->execute();
63
my @branches = ();
64
while ( my $branchCode = $selectBranchesSth->fetchrow_array ) {
65
66
    push @branches,$branchCode;
67
}
68
69
# finds what days are closed for each branch
70
my %repeatableHolidaysPerBranch = ();
71
my %specialHolidaysPerBranch = ();
72
my $selectWeeklySt;
73
my $selectWeeklySth;
74
75
76
foreach my $branch (@branches){
77
78
    $selectWeeklySt = 'SELECT weekday, title, day, month FROM repeatable_holidays WHERE branchcode = ?';
79
    $selectWeeklySth = $dbh->prepare($selectWeeklySt);
80
    $selectWeeklySth->execute($branch);
81
82
    my @weeklyHolidays = ();
83
84
    while ( my ($weekDay, $title, $day, $month) = $selectWeeklySth->fetchrow_array ) {
85
        push @weeklyHolidays,{weekday => $weekDay, title => $title, day => $day, month => $month};
86
87
    }
88
89
    $repeatableHolidaysPerBranch{$branch} = \@weeklyHolidays;
90
91
    my $selectSpecialHolidayDateSt = 'SELECT day,month,year,title FROM special_holidays WHERE branchcode = ? AND isexception = 0';
92
    my $specialHolidayDatesSth = $dbh->prepare($selectSpecialHolidayDateSt);
93
    $specialHolidayDatesSth -> execute($branch);
94
    # Tranforms dates from specialHolidays table in DateTime for our new table
95
    my @specialHolidayDates = ();
96
    while ( my ($day, $month, $year, $title) = $specialHolidayDatesSth->fetchrow_array ) {
97
98
        my $specialHolidayDate = DateTime->new(
99
        day       => $day,
100
        month     => $month,
101
        year      => $year,
102
        time_zone => C4::Context->tz()
103
        )->truncate( to => 'day' );
104
        push @specialHolidayDates,{date=>$specialHolidayDate, title=> $title};
105
    }
106
107
    $specialHolidaysPerBranch{$branch} = \@specialHolidayDates;
108
}
109
# Fills table with dates and sets 'isopened' according to the branch's weekly restrictions (repeatable_holidays)
110
my $insertDateSt;
111
my $insertDateSth;
112
113
# Loop that does everything in the world
114
for (my $tempDate = $startDate->clone(); $tempDate <= $endDate;$tempDate->add(days => 1)){
115
    foreach my $branch (@branches){
116
        my $dayOfWeek = $tempDate->day_of_week;
117
        # Representation fix
118
        # DateTime object dow (1-7) where Monday is 1
119
        # Arrays are 0-based where 0 = Sunday, not 7.
120
        $dayOfWeek -=1 unless $dayOfWeek ==7;
121
        $dayOfWeek =0 if $dayOfWeek ==7;
122
123
        my $openhour = "09:00:00";
124
        my $closehour = "17:00:00";
125
126
        # Finds closed days
127
        my $isOpened =1;
128
        my $specialDescription = "";
129
        my $holidaytype ='';
130
        $dayOfWeek = $tempDate->day_of_week;
131
        foreach my $holidayWeekDay (@{$repeatableHolidaysPerBranch{$branch}}){
132
            if($holidayWeekDay->{weekday} && $dayOfWeek == $holidayWeekDay->{weekday}){
133
                $isOpened = 0;
134
                $specialDescription = $holidayWeekDay->{title};
135
                $holidaytype = 'W';
136
            }elsif($holidayWeekDay->{day} && $holidayWeekDay->{month}){
137
                my $date = DateTime->new(
138
                day       => $holidayWeekDay->{day},
139
                month     => $holidayWeekDay->{month},
140
                year      => $tempDate->year(),
141
                time_zone => C4::Context->tz()
142
                )->truncate( to => 'day' );
143
144
                if ($tempDate == $date) {
145
                    $isOpened = 0;
146
                    $specialDescription = $holidayWeekDay->{title};
147
                    $holidaytype = 'R';
148
                }
149
            }
150
        }
151
152
        foreach my $specialDate (@{$specialHolidaysPerBranch{$branch}}){
153
            if($tempDate->datetime() eq $specialDate->{date}->datetime() ){
154
                $isOpened = 0;
155
                $specialDescription = $specialDate->{title};
156
                $holidaytype = 'E';
157
            }
158
        }
159
        #final insert statement
160
161
        $insertDateSt = 'INSERT INTO discrete_calendar (date,branchcode,isopened,holidaytype,note,openhour,closehour) VALUES (?,?,?,?,?,?,?)';
162
        $insertDateSth = $dbh->prepare($insertDateSt);
163
        $insertDateSth->execute($tempDate,$branch,$isOpened,$holidaytype,$specialDescription,$openhour,$closehour);
164
    }
165
}
(-)a/tools/discrete_calendar.pl (-1 / +157 lines)
Line 0 Link Here
0
- 
1
#!/usr/bin/perl
2
3
# This file is part of Koha.
4
#
5
# Koha is free software; you can redistribute it and/or modify it
6
# under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 3 of the License, or
8
# (at your option) any later version.
9
#
10
# Koha is distributed in the hope that it will be useful, but
11
# WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18
#####Sets holiday periods for each branch. Datedues will be extended if branch is closed -TG
19
use strict;
20
use warnings;
21
22
use CGI qw ( -utf8 );
23
24
use C4::Auth;
25
use C4::Output;
26
27
use Koha::DateUtils;
28
use Koha::DiscreteCalendar;
29
30
my $input = new CGI;
31
32
# Get the template to use
33
my ($template, $loggedinuser, $cookie)
34
    = get_template_and_user({template_name => "tools/discrete_calendar.tt",
35
                             type => "intranet",
36
                             query => $input,
37
                             authnotrequired => 0,
38
                             flagsrequired => {tools => 'edit_calendar'},
39
                             debug => 1,
40
                           });
41
42
my $branchcode = $input->param('BranchName');
43
my $branch = $input->param('branch') || C4::Context->userenv->{'branch'};
44
my $calendar = Koha::DiscreteCalendar->new(branchcode => $branch);
45
46
my $weekday = $input->param('Weekday');
47
48
my $holidaytype = $input->param('holidayType');
49
my $allbranches = $input->param('allBranches');
50
51
my $title = $input->param('Title');
52
53
my $action = $input->param('action') || '';
54
55
# calendardate - date passed in url for human readability (syspref)
56
# if the url has an invalid date default to 'now.'
57
my $calendarinput_dt = eval { dt_from_string( scalar $input->param('calendardate')); } || dt_from_string;
58
my $calendardate = output_pref( { dt => $calendarinput_dt, dateonly => 1 } );
59
60
if($action eq 'copyBranch'){
61
    copyToBranch();
62
} elsif($action eq 'copyDates'){
63
    copyDates();
64
} elsif($action eq 'edit'){
65
    edit_holiday();
66
}
67
68
sub copyToBranch {
69
    $calendar->copyToBranch(scalar $input->param('newBranch'));
70
}
71
sub copyDates {
72
    my $from_startDate = $input->param('from_copyFrom') ||'';
73
    my $from_endDate = $input->param('toDate') || '';
74
    my $to_startDate = $input->param('to_copyFrom') || '';
75
    my $to_endDate = $input->param('to_copyTo') || '';
76
    my $daysnumber= $input->param('daysnumber');
77
78
    $from_startDate = dt_from_string(scalar $from_startDate) if$from_startDate  ne '';
79
    $to_startDate = dt_from_string(scalar $to_startDate) if $to_startDate ne '';
80
    $to_startDate = dt_from_string(scalar $to_startDate) if $to_startDate ne '';
81
    $to_endDate = dt_from_string(scalar $to_endDate) if $to_endDate ne '';
82
83
    $calendar->copyHoliday($from_startDate, $from_endDate, $to_startDate, $to_endDate, $daysnumber);
84
}
85
86
sub edit_holiday {
87
    my $openHour = $input->param('openHour');
88
    my $closeHour = $input->param('closeHour');
89
    my $toDate = $input->param('toDate');
90
    my $deleteType = $input->param('deleteType') || 0;
91
92
    my $startDate = dt_from_string(scalar $input->param('from_copyFrom'));
93
94
    if($toDate ne '' ) {
95
        $toDate = dt_from_string(scalar $toDate);
96
    } else{
97
        $toDate = $startDate->clone();
98
    }
99
    #MYSQL DAYOFWEEK Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday).
100
    #JavaScript getDay() Returns the day of the week (from 0 to 6) for the specified date. Sunday is 0, Monday is 1, and so on.
101
    $weekday+=1;
102
    $calendar->edit_holiday($title, $weekday, $holidaytype, $openHour, $closeHour, $startDate, $toDate, $deleteType);
103
}
104
# keydate - date passed to calendar.js.  calendar.js does not process dashes within a date.
105
106
my $keydate = output_pref( { dt => $calendarinput_dt, dateonly => 1, dateformat => 'iso' } );
107
$keydate =~ s/-/\//g;
108
109
# Set all the branches.
110
my $onlymine =
111
  (      C4::Context->preference('IndependentBranches')
112
      && C4::Context->userenv
113
      && !C4::Context->IsSuperLibrarian()
114
      && C4::Context->userenv->{branch} ? 1 : 0 );
115
if ( $onlymine ) {
116
    $branch = C4::Context->userenv->{'branch'};
117
}
118
119
# Get all the holidays
120
121
#discrete_calendar weekdays
122
my @week_days = $calendar->get_week_days_holidays();
123
124
#discrete_calendar repeatable
125
my @repeatable_holidays = $calendar->get_day_month_holidays();
126
127
#single hildays (exceptions)
128
my @single_holidays =$calendar->get_single_holidays();
129
#floating holidays
130
my @float_holidays =$calendar->get_float_holidays();
131
#need validation holidays
132
my @need_validation_holidays =$calendar->get_need_valdation_holidays();
133
134
#Calendar maximum date
135
my $minDate = $calendar->getMinDate($branch);
136
137
#Calendar minimum date
138
my $maxDate = $calendar->getMaxDate($branch);
139
140
my @datesInfos = $calendar->getDatesInfo($branch);
141
142
$template->param(
143
    HOLIDAYS_LOOP            => \@single_holidays,
144
    FLOAT_HOLIDAYS           => \@float_holidays,
145
    NEED_VALIDATION_HOLIDAYS => \@need_validation_holidays,
146
    calendardate             => $calendardate,
147
    keydate                  => $keydate,
148
    branch                   => $branch,
149
    week_days                => \@week_days,
150
    repeatable_holidays      => \@repeatable_holidays,
151
    minDate                  => $minDate,
152
    maxDate                  => $maxDate,
153
    datesInfos               => \@datesInfos,
154
);
155
156
# Shows the template with the real values replaced
157
output_html_with_http_headers $input, $cookie, $template->output;

Return to bug 17015