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

(-)a/Koha/DiscreteCalendar.pm (+973 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 a given branch found to the new branch
102
sub add_new_branch {
103
    my ($self, $copyBranch, $newBranch) = @_;
104
    $copyBranch = 'DFLT' unless $copyBranch;
105
    my $schema = Koha::Database->new->schema;
106
107
    my $branch_rs = $schema->resultset('DiscreteCalendar')->search({
108
            branchcode => $copyBranch
109
    });
110
111
    while(my $row = $branch_rs->next()){
112
        $schema->resultset('DiscreteCalendar')->create({
113
            date        => $row->date(),
114
            branchcode  => $newBranch,
115
            isopened    => $row->isopened(),
116
            holidaytype => $row->holidaytype(),
117
            openhour    => $row->openhour(),
118
            closehour   => $row->closehour(),
119
        });
120
    }
121
122
}
123
#DiscreteCalendar data transfer object (DTO)
124
sub get_date_info {
125
    my ($self, $date) = @_;
126
    my $branchcode = $self->{branchcode};
127
    my $schema = Koha::Database->new->schema;
128
    my $dtf = $schema->storage->datetime_parser;
129
    #String dates for Database usage
130
    my $date_string = $dtf->format_datetime($date);
131
132
    my $rs = $schema->resultset('DiscreteCalendar')->search(
133
        {
134
            branchcode  => $branchcode,
135
        },
136
        {
137
            select  => [ 'date', { DATE => 'date' } ],
138
            as      => [qw/ date date /],
139
            where   => \['DATE(?) = date', $date_string ],
140
            columns =>[ qw/ branchcode holidaytype openhour closehour note/]
141
        },
142
    );
143
    my $dateDTO;
144
    while (my $date = $rs->next()){
145
        $dateDTO = {
146
            date        => $date->date(),
147
            branchcode  => $date->branchcode(),
148
            holidaytype => $date->holidaytype() ,
149
            openhour    => $date->openhour(),
150
            closehour   => $date->closehour(),
151
            note        => $date->note()
152
        };
153
    }
154
155
    return $dateDTO;
156
}
157
158
159
sub getMaxDate {
160
    my $self       = shift;
161
    my $branchcode     = $self->{branchcode};
162
    my $schema = Koha::Database->new->schema;
163
164
    my $rs = $schema->resultset('DiscreteCalendar')->search(
165
        {
166
            branchcode  => $branchcode
167
        },
168
        {
169
            select => [{ MAX => 'date' } ],
170
            as     => [qw/ max /],
171
        }
172
    );
173
174
    return $rs->next()->get_column('max');
175
}
176
177
sub getMinDate {
178
    my $self       = shift;
179
    my $branchcode     = $self->{branchcode};
180
    my $schema = Koha::Database->new->schema;
181
182
    my $rs = $schema->resultset('DiscreteCalendar')->search(
183
        {
184
            branchcode  => $branchcode
185
        },
186
        {
187
            select => [{ MIN => 'date' } ],
188
            as     => [qw/ min /],
189
        }
190
    );
191
192
    return $rs->next()->get_column('min');
193
}
194
195
196
sub get_unique_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_repeatable_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
=head1 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, different day each year.
350
    N : Needs validation, copied float holiday from the past
351
    R : Repeatable 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
=back
359
=cut
360
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_repeatable_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_repeatable_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
        #if the date does not exist in the copyTO branch, than skip it.
533
        if($copyTo->count ==0){
534
            next;
535
        }
536
        $copyTo->next()->update({
537
            isopened    => $copyDate->isopened(),
538
            holidaytype => $copyDate->holidaytype(),
539
            note        => $copyDate->note(),
540
            openhour    => $copyDate->openhour(),
541
            closehour   => $copyDate->closehour()
542
        });
543
    }
544
}
545
546
sub isOpened {
547
    my($self, $date) = @_;
548
    my $branchcode = $self->{branchcode};
549
    my $schema = Koha::Database->new->schema;
550
    my $dtf = $schema->storage->datetime_parser;
551
    $date= $dtf->format_datetime($date);
552
    #if the date is not found
553
    my $isOpened = -1;
554
    my $rs = $schema->resultset('DiscreteCalendar')->search(
555
        {
556
            branchcode => $branchcode,
557
        },
558
        {
559
            where   => \['date = DATE(?)', $date]
560
        }
561
    );
562
    $isOpened = $rs->next()->isopened() if $rs->count() != 0;
563
564
    return $isOpened;
565
}
566
567
sub is_holiday {
568
    my($self, $date) = @_;
569
    my $branchcode = $self->{branchcode};
570
    my $schema = Koha::Database->new->schema;
571
    my $dtf = $schema->storage->datetime_parser;
572
    $date= $dtf->format_datetime($date);
573
    #if the date is not found
574
    my $isHoliday = -1;
575
    my $rs = $schema->resultset('DiscreteCalendar')->search(
576
        {
577
            branchcode => $branchcode,
578
        },
579
        {
580
            where   => \['date = DATE(?)', $date]
581
        }
582
    );
583
584
    if($rs->count() != 0){
585
        $isHoliday = 0 if $rs->first()->isopened();
586
        $isHoliday = 1 if !$rs->first()->isopened();
587
    }
588
589
    return $isHoliday;
590
}
591
592
sub copyHoliday {
593
    my ($self, $from_startDate, $from_endDate, $to_startDate, $to_endDate, $daysnumber) = @_;
594
    my $branchcode = $self->{branchcode};
595
    my $copyFromType =  $from_startDate && $from_endDate eq '' ? 'oneDay': 'range';
596
    my $schema = Koha::Database->new->schema;
597
    my $dtf = $schema->storage->datetime_parser;
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 = dt_from_string($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 = dt_from_string($to_startDate);
678
            my $to_endDate = dt_from_string($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
    $start_date =~ /\s(.*)/;
862
    my $loan_date_time = $1;
863
    $end_date =~ /\s(.*)/;
864
    my $return_date_time = $1;
865
866
    my $not_used_hours = $schema->resultset('DiscreteCalendar')->search(
867
        {
868
            branchcode  => $branchcode,
869
            isopened    => 1,
870
        },
871
        {
872
            select  => \[ '(time_to_sec(timediff(?, ?)) + time_to_sec(timediff(?, ?)) ) / 3600', $return_day->next()->closehour(), $return_date_time, $loan_date_time, $loan_day->next()->openhour()],
873
            as      => [qw /not_used_hours/],
874
        }
875
    );
876
877
    return ($working_hours_between->next()->get_column('hours_between') - $not_used_hours->next()->get_column('not_used_hours'));
878
}
879
sub addDate {
880
    my ( $self, $startdate, $add_duration, $unit ) = @_;
881
882
    # Default to days duration (legacy support I guess)
883
    if ( ref $add_duration ne 'DateTime::Duration' ) {
884
        $add_duration = DateTime::Duration->new( days => $add_duration );
885
    }
886
887
    $unit ||= 'days'; # default days ?
888
    my $dt;
889
890
    if ( $unit eq 'hours' ) {
891
        # Fixed for legacy support. Should be set as a branch parameter
892
        my $return_by_hour = 10;
893
894
        $dt = $self->addHours($startdate, $add_duration, $return_by_hour);
895
    } else {
896
        # days
897
        $dt = $self->addDays($startdate, $add_duration);
898
    }
899
900
    return $dt;
901
}
902
903
sub addHours {
904
    my ( $self, $startdate, $hours_duration, $return_by_hour ) = @_;
905
    my $base_date = $startdate->clone();
906
907
    $base_date->add_duration($hours_duration);
908
909
    # If we are using the calendar behave for now as if Datedue
910
    # was the chosen option (current intended behaviour)
911
912
    if ( $self->{days_mode} ne 'Days' &&
913
    $self->is_holiday($base_date) ) {
914
915
        if ( $hours_duration->is_negative() ) {
916
            $base_date = $self->prev_open_day($base_date);
917
        } else {
918
            $base_date = $self->next_open_day($base_date);
919
        }
920
921
        $base_date->set_hour($return_by_hour);
922
923
    }
924
925
    return $base_date;
926
}
927
928
sub addDays {
929
    my ( $self, $startdate, $days_duration ) = @_;
930
    my $base_date = $startdate->clone();
931
932
    $self->{days_mode} ||= q{};
933
934
    if ( $self->{days_mode} eq 'Calendar' ) {
935
        # use the calendar to skip all days the library is closed
936
        # when adding
937
        my $days = abs $days_duration->in_units('days');
938
939
        if ( $days_duration->is_negative() ) {
940
            while ($days) {
941
                $base_date = $self->prev_open_day($base_date);
942
                --$days;
943
            }
944
        } else {
945
            while ($days) {
946
                $base_date = $self->next_open_day($base_date);
947
                --$days;
948
            }
949
        }
950
951
    } else { # Days or Datedue
952
        # use straight days, then use calendar to push
953
        # the date to the next open day if Datedue
954
        $base_date->add_duration($days_duration);
955
956
        if ( $self->{days_mode} eq 'Datedue' ) {
957
            # Datedue, then use the calendar to push
958
            # the date to the next open day if holiday
959
            if (!$self->isOpened($base_date) ) {
960
961
                if ( $days_duration->is_negative() ) {
962
                    $base_date = $self->prev_open_day($base_date);
963
                } else {
964
                    $base_date = $self->next_open_day($base_date);
965
                }
966
            }
967
        }
968
    }
969
970
    return $base_date;
971
}
972
973
1;
(-)a/installer/data/mysql/atomicupdate/bug_17015_koha_discrete_calendar.sql (+14 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
);
(-)a/installer/data/mysql/atomicupdate/generate_discrete_calendar.perl (+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/koha-tmpl/intranet-tmpl/prog/en/modules/tools/discrete_calendar.tt (+656 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="[% interface %]/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
    // Array containing all the information about each date in the calendar.
13
    var datesInfos = new Array();
14
    [% FOREACH date IN datesInfos %]
15
        datesInfos["[% date.date %]"] = {
16
            title : "[% date.note %]",
17
            outputdate : "[% date.outputdate %]",
18
            holidaytype:"[% date.holidaytype %]",
19
            openhour: "[% date.openhour %]",
20
            closehour: "[% date.closehour %]"
21
        };
22
    [% END %]
23
24
    /**
25
    * Displays the details of the selected date on a side panel
26
    */
27
    function showHoliday (date_obj, dateString, dayName, day, month, year, weekDay, title, holidayType) {
28
        $("#newHoliday").slideDown("fast");
29
        $("#copyHoliday").slideUp("fast");
30
        $('#newDaynameOutput').html(dayName);
31
        $('#newDayname').val(dayName);
32
        $('#newBranchNameOutput').html($("#branch :selected").text());
33
        $(".newHoliday ,#BranchName").val($('#branch').val());
34
        $('#newDayOutput').html(day);
35
        $(".newHoliday #Day").val(day);
36
        $(".newHoliday #Month").val(month);
37
        $(".newHoliday #Year").val(year);
38
        $("#newMonthOutput").html(month);
39
        $("#newYearOutput").html(year);
40
        $(".newHoliday, #Weekday").val(weekDay);
41
42
        $('.newHoliday #title').val(title);
43
        $('#HolidayType').val(holidayType);
44
        $('#openHour').val(datesInfos[dateString].openhour);
45
        $('#closeHour').val(datesInfos[dateString].closehour);
46
47
        //This changes the label of the date type on the edit panel
48
        if(holidayType == 'W') {
49
            $("#holtype").attr("class","key repeatableweekly").html(_("Holiday repeating weekly"));
50
        } else if(holidayType == 'R') {
51
            $("#holtype").attr("class","key repeatableyearly").html(_("Holiday repeating yearly"));
52
        } else if(holidayType == 'F') {
53
            $("#holtype").attr("class","key float").html(_("Floating holiday"));
54
        } else if(holidayType == 'N') {
55
            $("#holtype").attr("class","key exception").html(_("Needs validation"));
56
        } else if(holidayType == 'E') {
57
            $("#holtype").attr("class","key holiday").html(_("Unique holiday"));
58
        } else{
59
            $("#holtype").attr("class","key normalday").html(_("Working day "));
60
        }
61
62
        //Select the correct holiday type on the dropdown menu
63
        if (datesInfos[dateString].holidaytype !=''){
64
            var type = datesInfos[dateString].holidaytype;
65
            $('#holidayType option[value="'+ type +'"]').attr('selected', true)
66
        }else{
67
            $('#holidayType option[value="none"]').attr('selected', true)
68
        }
69
70
        //If it is a weekly or repeatable holiday show the option to delete the type
71
        if(datesInfos[dateString].holidaytype == 'W' || datesInfos[dateString].holidaytype == 'R'){
72
            $('#deleteType').show("fast");
73
        }else{
74
            $('#deleteType').hide("fast");
75
        }
76
77
        //This value is to disable and hide input when the date is in the past, because you can't edit it.
78
        var value = false;
79
        var today = new Date();
80
        today.setHours(0,0,0,0);
81
        if(date_obj < today ){
82
            $("#holtype").attr("class","key past-date").html(_("Past date"));
83
            $("#CopyRadioButton").attr("checked", "checked");
84
            value = true;
85
            $(".CopyDatePanel").toggle(value);
86
        }
87
        $("#title").prop('disabled', value);
88
        $("#holidayType select").prop('disabled', value);
89
        $("#openHour").prop('disabled', value);
90
        $("#closeHour").prop('disabled', value);
91
        $("#EditRadioButton").parent().toggle(!value);
92
93
    }
94
95
    function hidePanel(aPanelName) {
96
        $("#"+aPanelName).slideUp("fast");
97
    }
98
99
    function changeBranch () {
100
        var branch = $("#branch option:selected").val();
101
        location.href='/cgi-bin/koha/tools/discrete_calendar.pl?branch=' + branch + '&calendardate=' + "[% calendardate %]";
102
    }
103
104
    function Help() {
105
        newin=window.open("/cgi-bin/koha/help.pl","KohaHelp",'width=600,height=600,toolbar=false,scrollbars=yes');
106
    }
107
108
    // This function gives css clases to each kind of day
109
    function dateStatusHandler(date) {
110
        date = getSeparetedDate(date);
111
        var day = date.day;
112
        var month = date.month;
113
        var year = date.year;
114
        var weekDay = date.weekDay;
115
        var dayName = weekdays[weekDay];
116
        var dateString = date.dateString;
117
        var today = new Date();
118
        today.setHours(0,0,0,0);
119
120
        if (datesInfos[dateString] && datesInfos[dateString].holidaytype =='W'){
121
            return [true, "repeatableweekly", _("Weekly holiday: %s").format(datesInfos[dateString].title)];
122
        } else if (datesInfos[dateString] && datesInfos[dateString].holidaytype == 'R') {
123
            return [true, "repeatableyearly", _("Yearly holiday: %s").format(datesInfos[dateString].title)];
124
        } else if (datesInfos[dateString] && datesInfos[dateString].holidaytype == 'N') {
125
            return [true, "exception", _("Need validation: %s").format(datesInfos[dateString].title)];
126
        } else if (datesInfos[dateString] && datesInfos[dateString].holidaytype == 'F') {
127
            return [true, "float", _("Floating holiday: %s").format(datesInfos[dateString].title)];
128
        } else if (datesInfos[dateString] && datesInfos[dateString].holidaytype == 'E') {
129
            return [true, "holiday", _("Single holiday: %s").format(datesInfos[dateString].title)];
130
        } else {
131
            if(date.date_obj < today ){
132
                return [true, "past-date", _("Past day")];
133
            }else{
134
                return [true, "normalday", _("Normal day")];
135
            }
136
        }
137
    }
138
139
    /* This function is in charge of showing the correct panel considering the kind of holiday */
140
    function dateChanged(text, date) {
141
        date = getSeparetedDate(date);
142
        var day = date.day;
143
        var month = date.month;
144
        var year = date.year;
145
        var weekDay = date.weekDay;
146
        var dayName = weekdays[weekDay];
147
        var dateString = date.dateString;
148
        var date_obj = date.date_obj;
149
        //set value of form hidden field
150
        $('#from_copyFrom').val(text);
151
152
        showHoliday(date_obj, dateString, dayName, day, month, year, weekDay, datesInfos[dateString].title, datesInfos[dateString].holidaytype);
153
    }
154
155
    /**
156
    * This function seperate a given date object a returns an array containing all needed information about the date.
157
    */
158
    function getSeparetedDate(date){
159
        var mydate = new Array();
160
        var day = (date.getDate() < 10 ? '0' : '') + date.getDate();
161
        var month = ((date.getMonth()+1) < 10 ? '0' : '') + (date.getMonth() +1);
162
        var year = date.getFullYear();
163
        var weekDay = date.getDay();
164
        //iso date string
165
        var dateString = year + '-' + month + '-' + day;
166
        mydate = {
167
            date_obj : date,
168
            dateString : dateString,
169
            weekDay: weekDay,
170
            year: year,
171
            month: month,
172
            day: day
173
        };
174
175
        return mydate;
176
    }
177
178
    /**
179
    * Valide the forms before send them to the backend
180
    */
181
    function validateForm(form){
182
        if(form =='newHoliday' && $('#CopyRadioButton').is(':checked')){
183
            if($('#to_copyFromDatePicker').val() =='' || $('#to_copyToDatePicker').val() ==''){
184
                alert("You have to pick a FROM and TO in the Copy to different dates.");
185
                return false;
186
            }else if ($('#from_copyToDatePicker').val()){
187
                var from_DateFrom = new Date($("#jcalendar-container").datepicker("getDate"));
188
                var from_DateTo = new Date($('#from_copyToDatePicker').datepicker("getDate"));
189
                var to_DateFrom = new Date($('#to_copyFromDatePicker').datepicker("getDate"));
190
                var to_DateTo = new Date($('#to_copyToDatePicker').datepicker("getDate"));
191
192
                var from_start = Math.round( from_DateFrom.getTime() / (3600*24*1000)); //days as integer from..
193
                var from_end   = Math.round( from_DateTo.getTime() / (3600*24*1000));
194
                var to_start = Math.round( to_DateFrom.getTime() / (3600*24*1000));
195
                var to_end   = Math.round( to_DateTo.getTime() / (3600*24*1000));
196
197
                var from_daysDiff = from_end - from_start;
198
                var to_daysDiff = to_end - to_start;
199
200
                if(from_daysDiff == to_daysDiff || from_daysDiff ==1){
201
                    $('#daysnumber').val(to_daysDiff);
202
                    return true;
203
                }else{
204
                    alert("You have to pick the same number of days if you choose 2 ranges");
205
                    return false;
206
                }
207
            }
208
        }else if(form == 'CopyCalendar'){
209
            if ($('#newBranch').val() ==''){
210
                alert("Please select a copy to calendar.");
211
                return false;
212
            }else{
213
                return true;
214
            }
215
        }else {
216
            return true;
217
        }
218
    }
219
220
    function go_to_date(isoDate){
221
        //I added the time to get around the timezone
222
        var date = getSeparetedDate(new Date(isoDate + " 00:00:00"));
223
        var day = date.day;
224
        var month = date.month;
225
        var year = date.year;
226
        var weekDay = date.weekDay;
227
        var dayName = weekdays[weekDay];
228
        var dateString = date.dateString;
229
        var date_obj = date.date_obj;
230
231
        $("#jcalendar-container").datepicker("setDate", date_obj);
232
        showHoliday(date_obj, dateString, dayName, day, month, year, weekDay, datesInfos[dateString].title, datesInfos[dateString].holidaytype);
233
    }
234
235
    /**
236
    *Check if date range have the same opening, closing hours and holiday type if there's one.
237
    */
238
    function checkRange(date){
239
        date = new Date(date);
240
        $('#toDate').val(getSeparetedDate(date).dateString);
241
        var fromDate = new Date($("#jcalendar-container").datepicker("getDate"));
242
        var sameHoliday =true;
243
        var sameOpenHours =true;
244
        var sameCloseHours =true;
245
246
        for (var i = fromDate; i <= date ; i.setDate(i.getDate() + 1)) {
247
            var myDate1 = getSeparetedDate(i);
248
            var date1 = myDate1.dateString;
249
            var holidayType1 = datesInfos[date1].holidaytype;
250
            var openhours1 = datesInfos[date1].openhour;
251
            var closehours1 = datesInfos[date1].closehour;
252
            for (var j = fromDate; j <= date ; j.setDate(j.getDate() + 1)) {
253
                var myDate2 = getSeparetedDate(j);
254
                var date2 = myDate2.dateString;
255
                var holidayType2 = datesInfos[date2].holidaytype;
256
                var openhours2 = datesInfos[date2].openhour;
257
                var closehours2 = datesInfos[date2].closehour;
258
259
                if (sameHoliday && holidayType1 != holidayType2){
260
                    $('#holidayType option[value="empty"]').attr('selected', true)
261
                    sameHoliday=false;
262
                }
263
                if(sameOpenHours && (openhours1 != openhours2)){
264
                    $('#openHour').val('');
265
                    sameOpenHours=false;
266
                }
267
                if(sameCloseHours && (closehours1 != closehours2)){
268
                    $('#closeHour').val('');
269
                    sameCloseHours=false;
270
                }
271
            }
272
            if (!sameOpenHours && !sameCloseHours && !sameHoliday){
273
                return false;
274
            }
275
        }
276
        return true;
277
    }
278
279
    $(document).ready(function() {
280
        $(".hint").hide();
281
        $("#branch").change(function(){
282
            changeBranch();
283
        });
284
        $("#holidayweeklyrepeatable>tbody>tr").each(function(){
285
            var first_td = $(this).find('td').first();
286
            first_td.html(weekdays[first_td.html()]);
287
        });
288
        $("a.helptext").click(function(){
289
            $(this).parent().find(".hint").toggle(); return false;
290
        });
291
        //Set the correct coloring, default date and the date ranges for all datepickers
292
        $.datepicker.setDefaults({
293
            beforeShowDay: function(thedate) {
294
                return dateStatusHandler(thedate);
295
            },
296
            defaultDate: new Date("[% keydate %]"),
297
            minDate: new Date("[% minDate %]"),
298
            maxDate: new Date("[% maxDate %]")
299
        });
300
        //Main datepicker
301
        $("#jcalendar-container").datepicker({
302
            onSelect: function(dateText, inst) {
303
                dateChanged(dateText, $(this).datepicker("getDate"));
304
            },
305
        });
306
        $('#from_copyToDatePicker').datepicker();
307
        $("#from_copyToDatePicker").change(function(){
308
            checkRange($(this).datepicker("getDate"));
309
            $('#from_copyTo').val(($(this).val()));
310
        });
311
        //Datepickers for copy dates feature
312
        $('#to_copyFromDatePicker').datepicker();
313
        $("#to_copyFromDatePicker").change(function(){
314
            $('#to_copyFrom').val(($(this).val()));
315
        });
316
        $('#to_copyToDatePicker').datepicker();
317
        $("#to_copyToDatePicker").change(function(){
318
            $('#to_copyTo').val(($(this).val()));
319
        });
320
        //Timepickers for open and close hours
321
        $('#openHour').timepicker({
322
            showOn : 'focus',
323
            timeFormat: 'HH:mm:ss',
324
            showSecond: false,
325
            stepMinute: 5,
326
        });
327
        $('#closeHour').timepicker({
328
            showOn : 'focus',
329
            timeFormat: 'HH:mm:ss',
330
            showSecond: false,
331
            stepMinute: 5,
332
        });
333
334
        $('.newHoliday input[type="radio"]').click(function () {
335
            if ($(this).attr("id") == "CopyRadioButton") {
336
                $(".CopyToBranchPanel").hide('fast');
337
                $(".CopyDatePanel").show('fast');
338
            } else if ($(this).attr("id") == "CopyToBranchRadioButton"){
339
                $(".CopyDatePanel").hide('fast');
340
                $(".CopyToBranchPanel").show('fast');
341
            } else{
342
                $(".CopyDatePanel").hide('fast');
343
                $(".CopyToBranchPanel").hide('fast');
344
            }
345
        });
346
        $(".hidePanel").on("click",function(){
347
            if( $(this).hasClass("showHoliday") ){
348
                hidePanel("showHoliday");
349
            }if ($(this).hasClass('newHoliday')) {
350
                hidePanel("newHoliday");
351
            }else {
352
                hidePanel("copyHoliday");
353
            }
354
        })
355
    });
356
//]]>
357
</script>
358
<!-- Datepicker colors -->
359
<style type="text/css"> .key { padding : 3px; white-space:nowrap; line-height:230%; }
360
.ui-datepicker { font-size : 150%; }
361
#jcalendar-container .ui-datepicker { font-size : 185%; }
362
.ui-datepicker th, .ui-datepicker .ui-datepicker-title select { font-size : 80%; }
363
.ui-datepicker td a { padding : .5em; }
364
.ui-datepicker td span { padding : .5em; border : 1px solid #BCBCBC;}
365
.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { font-size : 80%; }
366
.key { padding : 3px; white-space:nowrap; line-height:230%; }
367
.normalday { background-color :  #EDEDED; color :  Black; border : 1px solid #BCBCBC; }
368
.ui-datepicker-unselectable { padding :.5em; white-space:nowrap;}
369
.ui-state-disabled { padding :.5em; white-space:nowrap;}
370
.exception { background-color :  #b3d4ff; color :  Black; border : 1px solid #BCBCBC; }
371
.past-date { background-color :  #e6e6e6; color :  #555555; border : 1px solid #BCBCBC; }
372
td.past-date a.ui-state-default { background : #e6e6e6 ; color :  #555555; }
373
.float { background-color :  #66ff33; color :  Black; border : 1px solid #BCBCBC; }
374
.holiday {  background-color :  #ffaeae; color :  Black;  border : 1px solid #BCBCBC; }
375
.repeatableweekly {  background-color :  #FFFF99; color :  Black;  border : 1px solid #BCBCBC; }
376
.repeatableyearly {  background-color :  #FFCC66; color :  Black;  border : 1px solid #BCBCBC; }
377
td.exception a.ui-state-default { background:  #b3d4ff none; color :  Black; border : 1px solid #BCBCBC; }
378
td.float a.ui-state-default { background:  #66ff33 none; color :  Black; border : 1px solid #BCBCBC; }
379
td.holiday a.ui-state-default {  background:  #ffaeae none; color :  Black;  border : 1px solid #BCBCBC; }
380
td.repeatableweekly a.ui-state-default {  background:  #FFFF99 none; color :  Black;  border : 1px solid #BCBCBC; }
381
td.repeatableyearly a.ui-state-default {  background:  #FFCC66 none; color :  Black;  border : 1px solid #BCBCBC; }
382
.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; }
383
.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; }
384
#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; }
385
.copyHoliday form li{ display:table-row } .copyHoliday form li b, .copyHoliday form li input{ display:table-cell; margin-bottom: 2px; }
386
</style>
387
</head>
388
<body id="tools_holidays" class="tools">
389
[% INCLUDE 'header.inc' %]
390
[% INCLUDE 'cat-search.inc' %]
391
392
<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>
393
394
<div id="doc3" class="yui-t1">
395
396
   <div id="bd">
397
    <div id="yui-main">
398
    <div class="yui-b">
399
    <h2>[% Branches.GetName( branch ) %] calendar</h2>
400
    <div class="yui-g">
401
    <div class="yui-u first" style="width:60%">
402
        <label for="branch">Define the holidays for:</label>
403
        <form method="post" onsubmit="return validateForm('CopyCalendar')">
404
            <select id="branch" name="branch">
405
                [% PROCESS options_for_libraries libraries => Branches.all( selected => branch ) %]
406
            </select>
407
            Copy calendar to
408
            <select id='newBranch' name ='newBranch'>
409
                <option value=""></option>
410
                [% FOREACH l IN Branches.all() %]
411
                    [% UNLESS branch == l.branchcode %]
412
                    <option value="[% l.branchcode %]">[% l.branchname %]</option>
413
                    [% END %]
414
                [% END %]
415
            </select>
416
            <input type="hidden" name="action" value="copyBranch" />
417
            <input type="submit" value="Clone">
418
        </form>
419
            <h3>Calendar information</h3>
420
            <div id="jcalendar-container" style="float: left"></div>
421
    <!-- ***************************** Panel to deal with new holidays **********************  -->
422
    [% UNLESS  datesInfos %]
423
    <div class="alert alert-danger" style="float: left; margin-left:15px">
424
        <strong>Error!</strong> You have to run generate_discrete_calendar.pl in order to use Discrete Calendar.
425
    </div>
426
    [% END %]
427
    <div class="panel newHoliday" id="newHoliday" style="float: left; margin-left:15px">
428
        <form method="post" onsubmit="return validateForm('newHoliday')">
429
            <fieldset class="brief">
430
                <h3>Edit date details</h3>
431
                <span id="holtype"></span>
432
                <ol>
433
                    <li>
434
                        <strong>Library:</strong>
435
                        <span id="newBranchNameOutput"></span>
436
                        <input type="hidden" id="BranchName" name="BranchName" />
437
                    </li>
438
                    <li>
439
                        <strong>From date:</strong>
440
                        <span id="newDaynameOutput"></span>,
441
442
                        [% 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 %]
443
444
                        <input type="hidden" id="newDayname" name="showDayname" />
445
                        <input type="hidden" id="Weekday" name="Weekday" />
446
                        <input type="hidden" id="Day" name="Day" />
447
                        <input type="hidden" id="Month" name="Month" />
448
                        <input type="hidden" id="Year" name="Year" />
449
                    </li>
450
                    <li class="dateinsert">
451
                        <b>To date: </b>
452
                        <input type="text" id="from_copyToDatePicker" name="toDate" size="20" class="datepicker" />
453
                    </li>
454
                    <li>
455
                        <label for="title">Title: </label><input type="text" name="Title" id="title" size="35" />
456
                    </li>
457
                    <li id="holidayType">
458
                        <label for="holidayType">Date type</label>
459
                        <select name ='holidayType'>
460
                            <option value="empty"></option>
461
                            <option value="none">Working day</option>
462
                            <option value="E">Unique holiday</option>
463
                            <option value="W">Weekly holiday</option>
464
                            <option value="R">Repeatable holiday</option>
465
                            <option value="F">Floating holiday</option>
466
                            <option value="N" disabled>Need validation</option>
467
                        </select>
468
                    </li>
469
                    <li class="radio" id="deleteType" style="display : none;" >
470
                        <input type="checkbox" name="deleteType" id="deleteType_checkbox" value="1" ><label for="deleteType_checkbox"> Delete this type</label>
471
                        <a href="#" class="helptext">[?]</a>
472
                        <div class="hint">Remove all repeated or weekly holidays of the selected date or week day <br> if working day is selected.</div>
473
                    </li>
474
                    <li>
475
                        <label for="openHour">Open hours: </label><input type="text" name="openHour" id='openHour' style="display :flex"  >
476
                    </li>
477
                    <li>
478
                        <label for="closeHour">Close hours: </label><input type="text" name="closeHour" id='closeHour' style="display :flex" >
479
                    </li>
480
                    <li class="radio">
481
                        <input type="radio" name="action" id="EditRadioButton" value="edit" checked/>
482
                        <label for="EditRadioButton">Edit selected dates</label>
483
                    </li>
484
                    <li class="radio">
485
                        <input type="radio" name="action" id="CopyRadioButton" value="copyDates" />
486
                        <label for="CopyRadioButton">Copy to different dates</label>
487
                        <div class="CopyDatePanel" style="display:none; padding-left:15px">
488
489
                            <b>From : </b>
490
                            <input type="text" id="to_copyFromDatePicker" size="20" class="datepicker"/>
491
                            <b>To : </b>
492
                            <input type="text" id="to_copyToDatePicker" size="20" class="datepicker"/>
493
                        </div>
494
                        <input type="hidden" name="daysnumber" id='daysnumber'>
495
                        <!-- These  yyyy-mm-dd -->
496
                        <input type="hidden" name="from_copyFrom" id='from_copyFrom'>
497
                        <input type="hidden" name="from_copyTo" id='from_copyTo'>
498
                        <input type="hidden" name="to_copyFrom" id='to_copyFrom'>
499
                        <input type="hidden" name="to_copyTo" id='to_copyTo'>
500
                    </li>
501
                </ol>
502
                <fieldset class="action">
503
                    <input type="submit" name="submit" value="Save" />
504
                    <a href="#" class="cancel hidePanel newHoliday">Cancel</a>
505
                </fieldset>
506
            </fieldset>
507
        </form>
508
    </div>
509
510
<!-- ************************************************************************************** -->
511
<!-- ******                              MAIN SCREEN CODE                            ****** -->
512
<!-- ************************************************************************************** -->
513
514
</div>
515
<div class="yui-u" style="width : 40%">
516
    <div class="help">
517
        <h4>Hints</h4>
518
        <ul>
519
            <li>Search in the calendar the day you want to set as holiday.</li>
520
            <li>Click the date to add or edit a holiday.</li>
521
            <li>Specify how the holiday should repeat.</li>
522
            <li>Click Save to finish.</li>
523
            <li>PS:
524
                <ul>
525
                    <li>You can't edit passed dates</li>
526
                    <li>Weekly holidays change open/close hours for all the days affected unless inputs are empty</li>
527
                </ul>
528
            </li>
529
        </ul>
530
        <h4>Key</h4>
531
        <p>
532
            <span class="key normalday">Working day </span>
533
            <span class="key holiday">Unique holiday</span>
534
            <span class="key repeatableweekly">Holiday repeating weekly</span>
535
            <span class="key repeatableyearly">Holiday repeating yearly</span>
536
            <span class="key float">Floating holiday</span>
537
            <span class="key exception">Need validation</span>
538
        </p>
539
    </div>
540
<div id="holiday-list">
541
542
    [% IF ( NEED_VALIDATION_HOLIDAYS ) %]
543
    <h3>Need validation holidays</h3>
544
    <table id="holidaysunique">
545
        <thead>
546
            <tr>
547
                <th class="exception">Date</th>
548
                <th class="exception">Title</th>
549
            </tr>
550
        </thead>
551
        <tbody>
552
            [% FOREACH need_validation_holiday IN NEED_VALIDATION_HOLIDAYS %]
553
            <tr>
554
                <td><a href="#doc3" onclick="go_to_date('[% need_validation_holiday.date %]')"><span title="[% need_validation_holiday.DATE_SORT %]">[% need_validation_holiday.outputdate %]</span></a></td>
555
                <td>[% need_validation_holiday.note %]</td>
556
            </tr>
557
            [% END %]
558
        </tbody>
559
    </table>
560
    [% END %]
561
562
    [% IF ( WEEKLY_HOLIDAYS ) %]
563
    <h3>Weekly - Repeatable holidays</h3>
564
    <table id="holidayweeklyrepeatable">
565
        <thead>
566
            <tr>
567
                <th class="repeatableweekly">Day of week</th>
568
                <th class="repeatableweekly">Title</th>
569
            </tr>
570
        </thead>
571
        <tbody>
572
            [% FOREACH WEEK_DAYS_LOO IN WEEKLY_HOLIDAYS %]
573
            <tr>
574
                <td>[% WEEK_DAYS_LOO.weekday %]</td>
575
            </td>
576
            <td>[% WEEK_DAYS_LOO.note %]</td>
577
        </tr>
578
        [% END %]
579
    </tbody>
580
</table>
581
[% END %]
582
583
[% IF ( REPEATABLE_HOLIDAYS ) %]
584
<h3>Yearly - Repeatable holidays</h3>
585
<table id="holidaysyearlyrepeatable">
586
    <thead>
587
        <tr>
588
            [% IF ( dateformat == "metric" ) %]
589
            <th class="repeatableyearly">Day/month</th>
590
            [% ELSE %]
591
            <th class="repeatableyearly">Month/day</th>
592
            [% END %]
593
            <th class="repeatableyearly">Title</th>
594
        </tr>
595
    </thead>
596
    <tbody>
597
        [% FOREACH DAY_MONTH_HOLIDAYS_LOO IN REPEATABLE_HOLIDAYS %]
598
        <tr>
599
            <td><span title="[% DAY_MONTH_HOLIDAYS_LOO.DATE_SORT %]">[%DAY_MONTH_HOLIDAYS_LOO.month%]/[% DAY_MONTH_HOLIDAYS_LOO.day %]</span></td>
600
            <td>[% DAY_MONTH_HOLIDAYS_LOO.note %]</td>
601
        </tr>
602
        [% END %]
603
    </tbody>
604
</table>
605
[% END %]
606
607
[% IF ( UNIQUE_HOLIDAYS ) %]
608
<h3>Unique holidays</h3>
609
<table id="holidaysunique">
610
    <thead>
611
        <tr>
612
            <th class="holiday">Date</th>
613
            <th class="holiday">Title</th>
614
        </tr>
615
    </thead>
616
    <tbody>
617
        [% FOREACH HOLIDAYS_LOO IN UNIQUE_HOLIDAYS %]
618
        <tr>
619
            <td><a href="#doc3" onclick="go_to_date('[% HOLIDAYS_LOO.date %]')"><span title="[% HOLIDAYS_LOO.DATE_SORT %]">[% HOLIDAYS_LOO.outputdate %]</span></a></td>
620
            <td>[% HOLIDAYS_LOO.note %]</td>
621
        </tr>
622
        [% END %]
623
    </tbody>
624
</table>
625
[% END %]
626
627
[% IF ( FLOAT_HOLIDAYS ) %]
628
<h3>Floating holidays</h3>
629
<table id="holidaysunique">
630
    <thead>
631
        <tr>
632
            <th class="float">Date</th>
633
            <th class="float">Title</th>
634
        </tr>
635
    </thead>
636
    <tbody>
637
        [% FOREACH float_holiday IN FLOAT_HOLIDAYS %]
638
        <tr>
639
            <td><a href="#doc3" onclick="go_to_date('[% float_holiday.date %]')"><span title="[% float_holiday.DATE_SORT %]">[% float_holiday.outputdate %]</span></a></td>
640
            <td>[% float_holiday.note %]</td>
641
        </tr>
642
        [% END %]
643
    </tbody>
644
</table>
645
[% END %]
646
</div>
647
</div>
648
</div>
649
</div>
650
</div>
651
652
<div class="yui-b noprint">
653
[% INCLUDE 'tools-menu.inc' %]
654
</div>
655
</div>
656
[% INCLUDE 'intranet-bottom.inc' %]
(-)a/misc/cronjobs/add_days_discrete_calendar.pl (+125 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
my $debug = 0;
17
GetOptions (
18
    'help|?|h'  => \$help,
19
    'n=i'       => \$daysInFuture,
20
    'd|?|debug' => \$debug);
21
22
my $usage = << 'ENDUSAGE';
23
24
This script adds days into discrete_calendar table based on the same day from the week before.
25
26
Examples :
27
    The latest date on discrete_calendar is : 28-07-2017
28
    The current date : 01-08-2016
29
    The dates that will be added are : 29-07-2017, 30-07-2017, 31-07-2017, 01-08-2017
30
Open close exemples :
31
    Date added is : 29-07-2017
32
    Opening/closing hours will be base on : 22-07-2017 (- 7 days)
33
    Library open or closed will be based on : 29-07-2017 (- 1 year)
34
This script has the following parameters:
35
    -h --help: this message
36
    -n : number of days to add in the futre, default : 1
37
    -d --debug: displays all added days and errors if there is any
38
39
ENDUSAGE
40
41
my $dbh = C4::Context->dbh;
42
my $query = "SELECT distinct weekday(date), note FROM discrete_calendar where holidaytype='W'";
43
my $stmt = $dbh->prepare($query);
44
$stmt->execute();
45
my @week_days_discrete;
46
while (my ($weekday,$note) = $stmt->fetchrow_array){
47
    push @week_days_discrete, {weekday => $weekday, note => $note};
48
}
49
50
if ($help) {
51
    print $usage;
52
    exit;
53
}
54
55
#getting the all the branches
56
my $selectBranchesSt = 'SELECT branchcode FROM discrete_calendar GROUP BY branchcode';
57
my $selectBranchesSth = $dbh->prepare($selectBranchesSt);
58
$selectBranchesSth->execute();
59
my @branches = ();
60
while ( my $branchCode = $selectBranchesSth->fetchrow_array ) {
61
62
    push @branches,$branchCode;
63
}
64
65
#get the latest date in the table
66
$query = "SELECT MAX(date) FROM discrete_calendar";
67
$stmt = $dbh->prepare($query);
68
$stmt->execute();
69
my $latestedDate = $stmt->fetchrow_array;
70
my $parser = DateTime::Format::Strptime->new(
71
    pattern => '%Y-%m-%d %H:%M:%S',
72
    on_error => 'croak',
73
);
74
$latestedDate = $parser->parse_datetime($latestedDate);
75
76
my $newDay = $latestedDate->clone();
77
$latestedDate->add(days => $daysInFuture);
78
79
for ($newDay->add(days => 1);$newDay <= $latestedDate;$newDay->add(days => 1)){
80
    my $lastWeekDay = $newDay->clone();
81
    $lastWeekDay->add(days=> -8);
82
    my $dayOfWeek = $lastWeekDay->day_of_week;
83
    # Representation fix
84
    # DateTime object dow (1-7) where Monday is 1
85
    # Arrays are 0-based where 0 = Sunday, not 7.
86
    $dayOfWeek -= 1 unless $dayOfWeek == 7;
87
    $dayOfWeek = 0 if $dayOfWeek == 7;
88
89
    #checking if it was open on the same day from last year
90
    my $yearAgo = $newDay->clone();
91
    $yearAgo = $yearAgo->add(years => -1);
92
    my $last_year = 'SELECT isopened, holidaytype, note FROM discrete_calendar WHERE date=? AND branchcode=?';
93
    my $day_last_week = "SELECT openhour, closehour FROM discrete_calendar WHERE DAYOFWEEk(date)=DAYOFWEEK(?) and date < ? order by date desc limit 1";
94
    my $add_Day = 'INSERT INTO discrete_calendar (date,branchcode,isopened,openhour,closehour) VALUES (?,?,?,?,?)';
95
    my $note ='';
96
    #insert into discrete_calendar for each branch
97
    foreach my $branchCode(@branches){
98
        $stmt = $dbh->prepare($last_year);
99
        $stmt->execute($yearAgo,$branchCode);
100
        my ($isOpened, $holidaytype, $note) = $stmt->fetchrow_array;
101
        #weekly and unique holidays are not replicated in the future
102
        if ($holidaytype && $holidaytype ne "R"){
103
            $isOpened = 1;
104
            if ($holidaytype eq "W" || $holidaytype eq "E"){
105
                $holidaytype='';
106
                $note='';
107
            }elsif ($holidaytype eq "F"){
108
                $holidaytype = 'N';
109
            }
110
        }
111
        $holidaytype = '' if $isOpened;
112
        $stmt = $dbh->prepare($day_last_week);
113
        $stmt->execute($newDay, $newDay);
114
        my ($openhour,$closehour ) = $stmt->fetchrow_array;
115
        my $add_Day = 'INSERT INTO discrete_calendar (date,branchcode,isopened,holidaytype, note,openhour,closehour) VALUES (?,?,?,?,?,?,?)';
116
        $stmt = $dbh->prepare($add_Day);
117
        $stmt->execute($newDay,$branchCode,$isOpened,$holidaytype,$note, $openhour,$closehour);
118
119
        if($debug && !$@){
120
            warn "Added day $newDay to $branchCode is opened : $isOpened, holidaytype : $holidaytype, note: $note, openhour : $openhour, closehour : $closehour \n";
121
        }elsif($@){
122
            warn "Failed to add day $newDay to $branchCode : $_\n";
123
        }
124
    }
125
}
(-)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_repeatable_holidays();
126
127
#single hildays (exceptions)
128
my @unique_holidays =$calendar->get_unique_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
    UNIQUE_HOLIDAYS          => \@unique_holidays,
144
    FLOAT_HOLIDAYS           => \@float_holidays,
145
    NEED_VALIDATION_HOLIDAYS => \@need_validation_holidays,
146
    REPEATABLE_HOLIDAYS      => \@repeatable_holidays,
147
    WEEKLY_HOLIDAYS          => \@week_days,
148
    calendardate             => $calendardate,
149
    keydate                  => $keydate,
150
    branch                   => $branch,
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