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