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

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