Bug 13914 : Fix UNION in SQL request for reserves statistics
[koha.git] / reports / issues_stats.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 use warnings;
22
23 use CGI qw ( -utf8 );
24 use Date::Manip;
25
26 use C4::Auth;
27 use C4::Debug;
28 use C4::Context;
29 use C4::Koha;
30 use C4::Output;
31 use C4::Circulation;
32 use C4::Reports;
33 use C4::Members;
34 use Koha::DateUtils;
35
36 =head1 NAME
37
38 reports/issues_stats.pl
39
40 =head1 DESCRIPTION
41
42 Plugin that shows circulation stats
43
44 =cut
45
46 # my $debug = 1;        # override for now.
47 my $input = CGI->new;
48 my $fullreportname = "reports/issues_stats.tt";
49 my $do_it    = $input->param('do_it');
50 my $line     = $input->param("Line");
51 my $column   = $input->param("Column");
52 my @filters  = $input->multi_param("Filter");
53 $filters[0] = eval { output_pref( { dt => dt_from_string( $filters[0]), dateonly => 1, dateformat => 'iso' } ); }
54     if ( $filters[0] );
55 $filters[1] = eval { output_pref( { dt => dt_from_string( $filters[1]), dateonly => 1, dateformat => 'iso' } ); }
56     if ( $filters[1] );
57 my $podsp    = $input->param("DisplayBy");
58 my $type     = $input->param("PeriodTypeSel");
59 my $daysel   = $input->param("PeriodDaySel");
60 my $monthsel = $input->param("PeriodMonthSel");
61 my $calc     = $input->param("Cellvalue");
62 my $output   = $input->param("output");
63 my $basename = $input->param("basename");
64 my ($template, $borrowernumber, $cookie) = get_template_and_user({
65         template_name => $fullreportname,
66         query => $input,
67         type => "intranet",
68         authnotrequired => 0,
69         flagsrequired => {reports => '*'},
70         debug => 0,
71 });
72 our $sep     = $input->param("sep") // '';
73 $sep = "\t" if ($sep eq 'tabulation');
74 $template->param(do_it => $do_it,
75 );
76
77 our $itemtypes = GetItemTypes();
78 our @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
79
80 our $ccodes    = GetKohaAuthorisedValues("items.ccode");
81 our $locations = GetKohaAuthorisedValues("items.location");
82
83 our $Bsort1 = GetAuthorisedValues("Bsort1");
84 our $Bsort2 = GetAuthorisedValues("Bsort2");
85 my ($hassort1,$hassort2);
86 $hassort1=1 if $Bsort1;
87 $hassort2=1 if $Bsort2;
88
89
90 if ($do_it) {
91 # Displaying results
92         my $results = calculate($line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters);
93         if ($output eq "screen"){
94 # Printing results to screen
95                 $template->param(mainloop => $results);
96                 output_html_with_http_headers $input, $cookie, $template->output;
97         } else {
98 # Printing to a csv file
99         print $input->header(-type => 'application/vnd.sun.xml.calc',
100                             -encoding    => 'utf-8',
101                             -attachment=>"$basename.csv",
102                             -filename=>"$basename.csv" );
103                 my $cols  = @$results[0]->{loopcol};
104                 my $lines = @$results[0]->{looprow};
105 # header top-right
106                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
107 # Other header
108                 foreach my $col ( @$cols ) {
109                         print $col->{coltitle}.$sep;
110                 }
111                 print "Total\n";
112 # Table
113                 foreach my $line ( @$lines ) {
114                         my $x = $line->{loopcell};
115                         print $line->{rowtitle}.$sep;
116                         print map {$_->{value}.$sep} @$x;
117                         print $line->{totalrow}, "\n";
118                 }
119 # footer
120         print "TOTAL";
121         $cols = @$results[0]->{loopfooter};
122                 print map {$sep.$_->{totalcol}} @$cols;
123         print $sep.@$results[0]->{total};
124         }
125         exit; # exit either way after $do_it
126 }
127
128 my $dbh = C4::Context->dbh;
129 my @values;
130 my %labels;
131 my %select;
132
133 # create itemtype arrayref for <select>.
134 my @itemtypeloop;
135 for my $itype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description}} keys(%$itemtypes)) {
136     push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{translated_description} } ;
137 }
138
139     # location list
140 my @locations;
141 foreach (sort keys %$locations) {
142         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
143 }
144     
145 my @ccodes;
146 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
147         push @ccodes, { code => $_, description => $ccodes->{$_} };
148 }
149
150 my $CGIextChoice = ( 'CSV' ); # FIXME translation
151 my $CGIsepChoice=GetDelimiterChoices;
152  
153 $template->param(
154     categoryloop => \@patron_categories,
155         itemtypeloop => \@itemtypeloop,
156         locationloop => \@locations,
157            ccodeloop => \@ccodes,
158         hassort1=> $hassort1,
159         hassort2=> $hassort2,
160         Bsort1 => $Bsort1,
161         Bsort2 => $Bsort2,
162         CGIextChoice => $CGIextChoice,
163         CGIsepChoice => $CGIsepChoice,
164 );
165 output_html_with_http_headers $input, $cookie, $template->output;
166
167 sub calculate {
168         my ($line, $column, $dsp, $type,$daysel,$monthsel ,$process, $filters) = @_;
169         my @loopfooter;
170         my @loopcol;
171         my @loopline;
172         my @looprow;
173         my %globalline;
174         my $grantotal =0;
175 # extract parameters
176         my $dbh = C4::Context->dbh;
177
178 # Filters
179 # Checking filters
180 #
181         my @loopfilter;
182         for (my $i=0;$i<=12;$i++) {
183                 my %cell;
184                 (@$filters[$i]) or next;
185         if (($i==1) and (@$filters[$i-1])) {
186             $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
187         }
188             # format the dates filters, otherwise just fill as is
189         if ($i>=2) {
190                 $cell{filter} = @$filters[$i];
191         } else {
192                 $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
193                    if ( @$filters[$i] );
194                 }
195                 $cell{crit} = 
196             ( $i == 0 )  ? "Period From"
197           : ( $i == 1 )  ? "Period To"
198           : ( $i == 2 )  ? "Patron Category ="
199           : ( $i == 3 )  ? "Item Type ="
200           : ( $i == 4 )  ? "Library ="
201           : ( $i == 5 )  ? "Collection ="
202           : ( $i == 6 )  ? "Location ="
203           : ( $i == 7 )  ? "Item callnumber >="
204           : ( $i == 8 )  ? "Item callnumber <"
205           : ( $i == 9 )  ? "sort1 ="
206           : ( $i == 10 ) ? "sort2 ="
207           : ( $i == 11 ) ? "Home library ="
208           : ( $i == 12 )? "Holding library ="
209           :                "UNKNOWN FILTER ($i)";
210
211                 # FIXME - no translation mechanism !
212                 push @loopfilter, \%cell;
213     }
214         push @loopfilter,{crit=>"Event",       filter=>$type    };
215         push @loopfilter,{crit=>"Display by",  filter=>$dsp     } if ($dsp);
216         push @loopfilter,{crit=>"Select Day",  filter=>$daysel  } if ($daysel);
217         push @loopfilter,{crit=>"Select Month",filter=>$monthsel} if ($monthsel);
218
219         my @linefilter;
220         $debug and warn "filtres ". join "|", @$filters;
221         my ($colsource, $linesource) = ('', '');
222         $linefilter[1] = @$filters[1] if ($line =~ /datetime/);
223         $linefilter[0] = 
224             ( $line =~ /datetime/ ) ? @$filters[0]
225       : ( $line =~ /category/ ) ? @$filters[2]
226       : ( $line =~ /itemtype/ ) ? @$filters[3]
227       : ( $line =~ /^branch/ )   ? @$filters[4]
228       : ( $line =~ /ccode/ )    ? @$filters[5]
229       : ( $line =~ /location/ ) ? @$filters[6]
230       : ( $line =~ /sort1/ )    ? @$filters[9]
231       : ( $line =~ /sort2/ )    ? @$filters[10]
232       : ( $line =~ /homebranch/)    ? @$filters[11]
233       : ( $line =~ /holdingbranch/) ? @$filters[12]
234       :                           undef;
235
236     if ( $line =~ /ccode/ or $line =~ /location/ or $line =~ /homebranch/ or $line =~ /holdingbranch/ ) {
237                 $linesource = 'items';
238         }
239
240         my @colfilter;
241         $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
242         $colfilter[0] = 
243         ( $column =~ /datetime/ ) ? @$filters[0]
244       : ( $column =~ /category/ ) ? @$filters[2]
245       : ( $column =~ /itemtype/ ) ? @$filters[3]
246       : ( $column =~ /^branch/ )   ? @$filters[4]
247       : ( $column =~ /ccode/ )    ? @$filters[5]
248       : ( $column =~ /location/ ) ? @$filters[6]
249       : ( $column =~ /sort1/ )    ? @$filters[9]
250       : ( $column =~ /sort1/ )    ? @$filters[10]
251       : ( $column =~ /homebranch/)    ? @$filters[11]
252       : ( $column =~ /holdingbranch/) ? @$filters[12]
253       :                             undef;
254
255     if ( $column =~ /ccode/ or $column =~ /location/ or $column =~ /homebranch/ or $column =~ /holdingbranch/ ) {
256                 $colsource = 'items';
257         }
258 # 1st, loop rows.
259         my $linefield;
260         if ($line =~ /datetime/) {
261                 # by Day, Month or Year (1,2,3 respectively)
262                 $linefield = ($dsp == 1) ? "  dayname($line)" :
263                                          ($dsp == 2) ? "monthname($line)" :
264                                          ($dsp == 3) ? "     Year($line)" :
265                                          'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::DateUtils
266         } else {
267                 $linefield = $line;
268         }
269         my $lineorder = ($linefield =~ /dayname/) ? "weekday($line)" :
270                                         ($linefield =~ /^month/ ) ? "  month($line)" : $linefield;
271
272         my $strsth = "SELECT distinctrow $linefield FROM statistics, ";
273                 # get stats on items if ccode or location, otherwise borrowers.
274         $strsth .= ($linesource eq 'items' ) ?
275                         " items     WHERE (statistics.itemnumber=items.itemnumber) " :
276                         " borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
277         $strsth .= " AND $line is not null ";
278
279         if ($line =~ /datetime/) {
280                 if ($linefilter[1] and ($linefilter[0])) {
281                         $strsth .= " AND $line between ? AND ? ";
282                 } elsif ($linefilter[1]) {
283                         $strsth .= " AND $line < ? ";
284                 } elsif ($linefilter[0]) {
285                 $strsth .= " AND $line > ? ";
286                 }
287                 $strsth .= " AND type ='".$type."' " if $type;
288                 $strsth .= " AND   dayname(datetime) ='".   $daysel ."' " if $daysel;
289                 $strsth .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
290         } elsif ($linefilter[0]) {
291                 $linefilter[0] =~ s/\*/%/g;
292                 $strsth .= " AND $line LIKE ? ";
293         }
294         $strsth .=" group by $linefield order by $lineorder ";
295         $debug and warn $strsth;
296         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth};
297         my $sth = $dbh->prepare( $strsth );
298         if ((@linefilter) and ($linefilter[1])){
299                 $sth->execute($linefilter[0],$linefilter[1]);
300         } elsif ($linefilter[0]) {
301                 $sth->execute($linefilter[0]);
302         } else {
303                 $sth->execute;
304         }
305
306         while (my ($celvalue) = $sth->fetchrow) {
307                 my %cell = (rowtitle => $celvalue, totalrow => 0); # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display
308                 $cell{rowtitle_display} =
309                         ($line =~ /ccode/   ) ? $ccodes->{$celvalue}    :
310                         ($line =~ /location/) ? $locations->{$celvalue} :
311                         ($line =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
312                         $celvalue; # default fallback
313                 if ($line =~ /sort1/) {
314                         foreach (@$Bsort1) {
315                                 ($celvalue eq $_->{authorised_value}) or next;
316                                 $cell{rowtitle_display} = $_->{lib} and last;
317                         }
318                 } elsif ($line =~ /sort2/) {
319                         foreach (@$Bsort2) {
320                                 ($celvalue eq $_->{authorised_value}) or next;
321                                 $cell{rowtitle_display} = $_->{lib} and last;
322                         }
323         } elsif ($line =~ /category/) {
324             foreach my $patron_category ( @patron_categories ) {
325                 ($celvalue eq $patron_category->categorycode) or next;
326                 $cell{rowtitle_display} = $patron_category->description and last;
327             }
328         }
329                 push @loopline, \%cell;
330         }
331
332 # 2nd, loop cols.
333         my $colfield;
334         my $colorder;
335         if ($column =~ /datetime/) {
336                 #Display by Day, Month or Year (1,2,3 respectively)
337                 $colfield = ($dsp == 1) ? "  dayname($column)" :
338                                         ($dsp == 2) ? "monthname($column)" :
339                                         ($dsp == 3) ? "     Year($column)" :
340                                         'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::DateUtils
341         } else {
342                 $colfield = $column;
343         }
344         $colorder = ($colfield =~ /dayname/) ? "weekday($column)" :
345                                 ($colfield =~ /^month/ ) ? "  month($column)" : $colfield;
346         my $strsth2 = "SELECT distinctrow $colfield FROM statistics, ";
347         # get stats on items if ccode or location, otherwise borrowers.
348         $strsth2 .= ($colsource eq 'items' ) ?
349                                 "items     WHERE (statistics.itemnumber=items.itemnumber) " :
350                                 "borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
351         $strsth2 .= " AND $column IS NOT NULL ";
352
353         if ($column =~ /datetime/){
354         if (($colfilter[1]) and ($colfilter[0])){
355                         $strsth2 .= " AND $column BETWEEN ? AND ? " ;
356         } elsif ($colfilter[1]) {
357                         $strsth2 .= " AND $column < ? " ;
358         } elsif ($colfilter[0]) {
359                         $strsth2 .= " AND $column > ? " ;
360         }
361         $strsth2 .= " AND                type ='". $type     ."' " if $type;
362         $strsth2 .= " AND   dayname(datetime) ='". $daysel   ."' " if $daysel;
363         $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
364     } elsif ($colfilter[0]) {
365         $colfilter[0] =~ s/\*/%/g;
366         $strsth2 .= " AND $column LIKE ? " ;
367     }
368         $strsth2 .=" GROUP BY $colfield ORDER BY $colorder ";
369
370         my $sth2 = $dbh->prepare($strsth2);
371         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth2};
372         if ((@colfilter) and ($colfilter[1])){
373                 $sth2->execute($colfilter[0], $colfilter[1]);
374         } elsif ($colfilter[0]) {
375                 $sth2->execute($colfilter[0]);
376         } else {
377                 $sth2->execute;
378         }
379
380         while (my ($celvalue) = $sth2->fetchrow) {
381                 my %cell = (coltitle => $celvalue); # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display
382                 $cell{coltitle_display} =
383                         ($column =~ /ccode/   ) ?    $ccodes->{$celvalue} :
384                         ($column =~ /location/) ? $locations->{$celvalue} :
385                         ($column =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
386                         $celvalue; # default fallback
387                 if ($column =~ /sort1/) {
388                         foreach (@$Bsort1) {
389                                 ($celvalue eq $_->{authorised_value}) or next;
390                                 $cell{coltitle_display} = $_->{lib} and last;
391                         }
392                 } elsif ($column =~ /sort2/) {
393                         foreach (@$Bsort2) {
394                                 ($celvalue eq $_->{authorised_value}) or next;
395                                 $cell{coltitle_display} = $_->{lib} and last;
396                         }
397         } elsif ($column =~ /category/) {
398             foreach my $patron_category ( @patron_categories ) {
399                 ($celvalue eq $patron_category->categorycode) or next;
400                 $cell{coltitle_display} = $patron_category->description and last;
401             }
402         }
403                 push @loopcol, \%cell;
404         }
405
406         #Initialization of cell values.....
407         my %table;
408         foreach my $row (@loopline) {
409                 foreach my $col (@loopcol) {
410                         $debug and warn " init table : $row->{rowtitle} ( $row->{rowtitle_display} ) / $col->{coltitle} ( $col->{coltitle_display} )  ";
411                         $table{$row->{rowtitle}}->{$col->{coltitle}} = 0;
412                 }
413                 $table{$row->{rowtitle}}->{totalrow} = 0;
414         }
415
416 # preparing calculation
417     my $strcalc = "SELECT $linefield, $colfield, ";
418         $strcalc .= ($process == 1) ? " COUNT(*) "                                 :
419                                         ($process == 2) ? "(COUNT(DISTINCT borrowers.borrowernumber))" :
420                                 ($process == 3) ? "(COUNT(DISTINCT statistics.itemnumber))"        : '';
421         if ($process == 4) {
422                 my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
423                 $rqbookcount->execute;
424                 my ($bookcount) = $rqbookcount->fetchrow;
425                 $strcalc .= "100*(COUNT(DISTINCT statistics.itemnumber))/ $bookcount " ;
426         }
427         $strcalc .= "
428         FROM statistics
429         LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber
430         ";
431         $strcalc .= "LEFT JOIN items ON statistics.itemnumber=items.itemnumber "
432         if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or ($colsource eq 'items')
433             ||@$filters[5]||@$filters[6]||@$filters[7]||@$filters[8]);
434         
435         $strcalc .= "WHERE 1=1 ";
436         @$filters = map {defined($_) and s/\*/%/g; $_} @$filters;
437         $strcalc .= " AND statistics.datetime > '"       . @$filters[0] ."'" if (@$filters[0] );
438         $strcalc .= " AND statistics.datetime < '"       . @$filters[1] ."'" if (@$filters[1] );
439         $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] ."'" if (@$filters[2] );
440         $strcalc .= " AND statistics.itemtype LIKE '"    . @$filters[3] ."'" if (@$filters[3] );
441         $strcalc .= " AND statistics.branch LIKE '"      . @$filters[4] ."'" if (@$filters[4] );
442         $strcalc .= " AND items.ccode LIKE '"            . @$filters[5] ."'" if (@$filters[5] );
443         $strcalc .= " AND items.location LIKE '"         . @$filters[6] ."'" if (@$filters[6] );
444         $strcalc .= " AND items.itemcallnumber >='"      . @$filters[7] ."'" if (@$filters[7] );
445         $strcalc .= " AND items.itemcallnumber <'"       . @$filters[8] ."'" if (@$filters[8] );
446         $strcalc .= " AND borrowers.sort1 LIKE '"        . @$filters[9] ."'" if (@$filters[9] );
447         $strcalc .= " AND borrowers.sort2 LIKE '"        . @$filters[10]."'" if (@$filters[10]);
448         $strcalc .= " AND dayname(datetime) LIKE '"      . $daysel      ."'" if ($daysel  );
449         $strcalc .= " AND monthname(datetime) LIKE '"    . $monthsel    ."'" if ($monthsel);
450         $strcalc .= " AND statistics.type LIKE '"        . $type        ."'" if ($type    );
451
452         $strcalc .= " GROUP BY $linefield, $colfield order by $lineorder,$colorder";
453         ($debug) and warn $strcalc;
454         my $dbcalc = $dbh->prepare($strcalc);
455         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
456         $dbcalc->execute;
457         my ($emptycol,$emptyrow); 
458         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
459                 ($debug) and warn "filling table $row / $col / $value ";
460                 unless (defined $col) {
461                         $emptycol = 1; 
462                         $col = "zzEMPTY" ;
463                 }
464                 unless (defined $row) {
465                         $emptyrow = 1;
466                         $row = "zzEMPTY"; 
467                 }
468                 $table{$row}->{$col}     += $value;
469                 $table{$row}->{totalrow} += $value;
470                 $grantotal += $value;
471         }
472         push @loopcol, {coltitle => "NULL", coltitle_display => 'NULL'} if ($emptycol);
473         push @loopline,{rowtitle => "NULL", rowtitle_display => 'NULL'} if ($emptyrow);
474
475         foreach my $row (@loopline) {
476                 my @loopcell;
477                 #@loopcol ensures the order for columns is common with column titles
478                 # and the number matches the number of columns
479                 foreach my $col (@loopcol) {
480                         my $value = $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
481                         push @loopcell, {value => $value};
482                 }
483                 my $rowtitle = ($row->{rowtitle} eq "NULL") ? "zzEMPTY" : $row->{rowtitle};
484                 push @looprow, {
485                         'rowtitle_display' => $row->{rowtitle_display},
486                         'rowtitle' => $rowtitle,
487                         'loopcell' => \@loopcell,
488                         'totalrow' => $table{$rowtitle}->{totalrow}
489                 };
490         }
491         for my $col ( @loopcol ) {
492                 my $total = 0;
493                 foreach my $row (@looprow) {
494                         $total += $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
495                         $debug and warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
496                 }
497                 push @loopfooter, {'totalcol' => $total};
498         }
499
500         # the header of the table
501         $globalline{loopfilter}=\@loopfilter;
502         # the core of the table
503         $globalline{looprow} = \@looprow;
504         $globalline{loopcol} = \@loopcol;
505         #       # the foot (totals by borrower type)
506         $globalline{loopfooter} = \@loopfooter;
507         $globalline{total}  = $grantotal;
508         $globalline{line}   = $line;
509         $globalline{column} = $column;
510         return [(\%globalline)];
511 }
512
513 sub null_to_zzempty ($) {
514         my $string = shift;
515         defined($string)    or  return 'zzEMPTY';
516         ($string eq "NULL") and return 'zzEMPTY';
517         return $string;         # else return the valid value
518 }
519
520 1;