Report cleanup - fix highlight, add debugging feedback
[koha.git] / reports / issues_stats.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA  02111-1307 USA
20
21 use strict;
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::Dates qw/format_date format_date_in_iso/;
34 use C4::Members;
35
36 =head1 NAME
37
38 plugin that shows circulation stats
39
40 =head1 DESCRIPTION
41
42 =over 2
43
44 =cut
45
46 # my $debug = 1;        # override for now.
47 my $input = new CGI;
48 my $fullreportname = "reports/issues_stats.tmpl";
49 my $do_it    = $input->param('do_it');
50 my $line     = $input->param("Line");
51 my $column   = $input->param("Column");
52 my @filters  = $input->param("Filter");
53 $filters[0]=format_date_in_iso($filters[0]);
54 $filters[1]=format_date_in_iso($filters[1]);
55 my $podsp    = $input->param("DisplayBy");
56 my $type     = $input->param("PeriodTypeSel");
57 my $daysel   = $input->param("PeriodDaySel");
58 my $monthsel = $input->param("PeriodMonthSel");
59 my $calc     = $input->param("Cellvalue");
60 my $output   = $input->param("output");
61 my $basename = $input->param("basename");
62 my $mime     = $input->param("MIME");
63 my $del      = $input->param("sep");
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 => 1},
70         debug => 0,
71 });
72 $template->param(do_it => $do_it,
73         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
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                 my $sep = C4::Context->preference("delimiter");
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(1); # 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 ( keys(%$itemtypes)) {
136         push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{description} } ;
137 }
138
139 my $branches=GetBranches();
140 my @branchloop;
141 foreach (keys %$branches) {
142         my $thisbranch = ''; # FIXME 
143         my %row = (
144                 branchcode => $_,
145                 selected => ($thisbranch eq $_ ? 1 : 0),
146                 code => $branches->{$_}->{'branchcode'},
147                 description => $branches->{$_}->{'branchname'},
148         );
149         push @branchloop, \%row;
150 }
151
152     # location list
153 my @locations;
154 foreach (sort keys %$locations) {
155         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
156 }
157     
158 my @ccodes;
159 foreach (keys %$ccodes) {
160         push @ccodes, { code => $_, description => $ccodes->{$_} };
161 }
162
163 # various
164 my @mime = (C4::Context->preference("MIME"));
165
166 my $CGIextChoice=CGI::scrolling_list(
167         -name     => 'MIME',
168         -id       => 'MIME',
169         -values   => \@mime,
170         -size     => 1,
171         -multiple => 0 );
172     
173 my @dels = ( C4::Context->preference("delimiter") );
174 my $CGIsepChoice=CGI::scrolling_list(
175         -name     => 'sep',
176         -id       => 'sep',
177         -values   => \@dels,
178         -size     => 1,
179         -multiple => 0 );
180  
181 $template->param(
182         categoryloop => $categoryloop,
183         itemtypeloop => \@itemtypeloop,
184         locationloop => \@locations,
185            ccodeloop => \@ccodes,
186           branchloop => \@branchloop,
187         hassort1=> $hassort1,
188         hassort2=> $hassort2,
189         Bsort1 => $Bsort1,
190         Bsort2 => $Bsort2,
191         CGIextChoice => $CGIextChoice,
192         CGIsepChoice => $CGIsepChoice,
193 );
194 output_html_with_http_headers $input, $cookie, $template->output;
195
196 sub calculate {
197         my ($line, $column, $dsp, $type,$daysel,$monthsel ,$process, $filters) = @_;
198         my @loopfooter;
199         my @loopcol;
200         my @loopline;
201         my @looprow;
202         my %globalline;
203         my $grantotal =0;
204 # extract parameters
205         my $dbh = C4::Context->dbh;
206
207 # Filters
208 # Checking filters
209 #
210         my @loopfilter;
211         for (my $i=0;$i<=10;$i++) {
212                 my %cell;
213                 (@$filters[$i]) or next;
214         if (($i==1) and (@$filters[$i-1])) {
215             $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
216         }
217             # format the dates filters, otherwise just fill as is
218         if ($i>=2) {
219                 $cell{filter} = @$filters[$i];
220         } else {
221                 $cell{filter} = format_date(@$filters[$i]);
222                 }
223                 $cell{crit} = 
224                 ($i==0) ? "Period From"        :
225                 ($i==1) ? "Period To"          :
226                 ($i==2) ? "Patron Category ="  :
227                 ($i==3) ? "Item Type ="        :
228                 ($i==4) ? "Library ="          :
229                 ($i==5) ? "Collection ="       :
230                 ($i==6) ? "Location ="         :
231                 ($i==7) ? "Item callnumber >=" :
232                 ($i==8) ? "Item callnumber <"  :
233                 ($i==9) ? "sort1 ="            :
234                 ($i==10)? "sort2 ="            : "UNKNOWN FILTER ($i)";
235                 # FIXME - no translation mechanism !
236                 push @loopfilter, \%cell;
237     }
238         push @loopfilter,{crit=>"Event",       filter=>$type    };
239         push @loopfilter,{crit=>"Display by",  filter=>$dsp     } if ($dsp);
240         push @loopfilter,{crit=>"Select Day",  filter=>$daysel  } if ($daysel);
241         push @loopfilter,{crit=>"Select Month",filter=>$monthsel} if ($monthsel);
242
243         my @linefilter;
244         $debug and warn "filtres ". join "|", @filters;
245         my ($colsource, $linesource);
246         $linefilter[1] = @$filters[1] if ($line =~ /datetime/);
247         $linefilter[0] = ($line =~ /datetime/) ? @$filters[0]  :
248                                          ($line =~ /category/) ? @$filters[2]  :
249                                          ($line =~ /itemtype/) ? @$filters[3]  :
250                                          ($line =~ /branch/  ) ? @$filters[4]  :
251                                          ($line =~ /ccode/   ) ? @$filters[5]  :
252                                          ($line =~ /location/) ? @$filters[6]  :
253                                          ($line =~ /sort1/   ) ? @$filters[9]  :
254                                          ($line =~ /sort2/   ) ? @$filters[10] : undef ;
255         if ($line =~ /ccode/ or $line =~ /location/) {
256                 $linesource = 'items';
257         }
258
259         my @colfilter;
260         $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
261         $colfilter[0] = ($column =~ /datetime/) ? @$filters[0]  :
262                                         ($column =~ /category/) ? @$filters[2]  :
263                                         ($column =~ /itemtype/) ? @$filters[3]  :
264                                         ($column =~ /branch/  ) ? @$filters[4]  :
265                                         ($column =~ /ccode/   ) ? @$filters[5]  :
266                                         ($column =~ /location/) ? @$filters[6]  :
267                                         ($column =~ /sort1/   ) ? @$filters[9]  :
268                                         ($column =~ /sort1/   ) ? @$filters[10] : undef ;
269         if ($column =~ /ccode/ or $column =~ /location/) {
270                 $colsource = 'items';
271         }
272 # 1st, loop rows.
273         my $linefield;
274         if ($line =~ /datetime/) {
275                 # by Day, Month or Year (1,2,3 respectively)
276                 $linefield = ($dsp == 1) ? "  dayname($line)" :
277                                          ($dsp == 2) ? "monthname($line)" :
278                                          ($dsp == 3) ? "     Year($line)" :
279                                         'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
280         } else {
281                 $linefield = $line;
282         }
283         my $lineorder = ($linefield =~ /dayname/) ? "weekday($line)" :
284                                         ($linefield =~ /^month/ ) ? "  month($line)" : $linefield;
285
286         my $strsth = "SELECT distinctrow $linefield FROM statistics, ";
287                 # get stats on items if ccode or location, otherwise borrowers.
288         $strsth .= ($linesource eq 'items' ) ?
289                         " items     WHERE (statistics.itemnumber=items.itemnumber) " :
290                         " borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
291         $strsth .= " AND $line is not null ";
292
293         if ($line =~ /datetime/) {
294                 if ($linefilter[1] and ($linefilter[0])) {
295                         $strsth .= " AND $line between ? AND ? ";
296                 } elsif ($linefilter[1]) {
297                         $strsth .= " AND $line < ? ";
298                 } elsif ($linefilter[0]) {
299                 $strsth .= " AND $line > ? ";
300                 }
301                 $strsth .= " AND type ='".$type."' " if $type;
302                 $strsth .= " AND   dayname(datetime) ='".   $daysel ."' " if $daysel;
303                 $strsth .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
304         } elsif ($linefilter[0]) {
305                 $linefilter[0] =~ s/\*/%/g;
306                 $strsth .= " AND $line LIKE ? ";
307         }
308         $strsth .=" group by $linefield order by $lineorder ";
309         $debug and warn $strsth;
310         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth};
311         my $sth = $dbh->prepare( $strsth );
312         if ((@linefilter) and ($linefilter[1])){
313                 $sth->execute($linefilter[0],$linefilter[1]);
314         } elsif ($linefilter[0]) {
315                 $sth->execute($linefilter[0]);
316         } else {
317                 $sth->execute;
318         }
319
320         while (my ($celvalue) = $sth->fetchrow) {
321                 my %cell = (rowtitle => $celvalue, totalrow => 0); # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display
322                 $cell{rowtitle_display} =
323                         ($line =~ /ccode/   ) ? $ccodes->{$celvalue}    :
324                         ($line =~ /location/) ? $locations->{$celvalue} :
325                         ($line =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
326                         $celvalue; # default fallback
327                 if ($line =~ /sort1/) {
328                         foreach (@$Bsort1) {
329                                 ($celvalue eq $_->{authorised_value}) or next;
330                                 $cell{rowtitle_display} = $_->{lib} and last;
331                         }
332                 } elsif ($line =~ /sort2/) {
333                         foreach (@$Bsort2) {
334                                 ($celvalue eq $_->{authorised_value}) or next;
335                                 $cell{rowtitle_display} = $_->{lib} and last;
336                         }
337                 } elsif ($line =~ /category/) {
338                         foreach (@$categoryloop) {
339                                 ($celvalue eq $_->{categorycode}) or next;
340                                 $cell{rowtitle_display} = $_->{description} and last;
341                         }
342                 }
343                 push @loopline, \%cell;
344         }
345
346 # 2nd, loop cols.
347         my $colfield;
348         my $colorder;
349         if ($column =~ /datetime/) {
350                 #Display by Day, Month or Year (1,2,3 respectively)
351                 $colfield = ($dsp == 1) ? "  dayname($column)" :
352                                         ($dsp == 2) ? "monthname($column)" :
353                                         ($dsp == 3) ? "     Year($column)" :
354                                         'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
355         } else {
356                 $colfield = $column;
357         }
358         $colorder = ($colfield =~ /dayname/) ? "weekday($line)" :
359                                 ($colfield =~ /^month/ ) ? "  month($line)" : $colfield;
360         my $strsth2 = "SELECT distinctrow $colfield FROM statistics, ";
361         # get stats on items if ccode or location, otherwise borrowers.
362         $strsth2 .= ($colsource eq 'items' ) ?
363                                 "items     WHERE (statistics.itemnumber=items.itemnumber) " :
364                                 "borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
365         $strsth2 .= " AND $column IS NOT NULL ";
366
367         if ($column =~ /datetime/){
368         if (($colfilter[1]) and ($colfilter[0])){
369                         $strsth2 .= " AND $column BETWEEN ? AND ? " ;
370         } elsif ($colfilter[1]) {
371                         $strsth2 .= " AND $column < ? " ;
372         } elsif ($colfilter[0]) {
373                         $strsth2 .= " AND $column > ? " ;
374         }
375         $strsth2 .= " AND                type ='". $type     ."' " if $type;
376         $strsth2 .= " AND   dayname(datetime) ='". $daysel   ."' " if $daysel;
377         $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
378     } elsif ($colfilter[0]) {
379         $colfilter[0] =~ s/\*/%/g;
380         $strsth2 .= " AND $column LIKE ? " ;
381     }
382         $strsth2 .=" GROUP BY $colfield ORDER BY $colorder ";
383
384         my $sth2 = $dbh->prepare($strsth2);
385         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth2};
386         if ((@colfilter) and ($colfilter[1])){
387                 $sth2->execute($colfilter[0], $colfilter[1]);
388         } elsif ($colfilter[0]) {
389                 $sth2->execute($colfilter[0]);
390         } else {
391                 $sth2->execute;
392         }
393
394         while (my ($celvalue) = $sth2->fetchrow) {
395                 my %cell = (coltitle => $celvalue); # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display
396                 $cell{coltitle_display} =
397                         ($column =~ /ccode/   ) ?    $ccodes->{$celvalue} :
398                         ($column =~ /location/) ? $locations->{$celvalue} :
399                         ($column =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
400                         $celvalue; # default fallback
401                 if ($column =~ /sort1/) {
402                         foreach (@$Bsort1) {
403                                 ($celvalue eq $_->{authorised_value}) or next;
404                                 $cell{coltitle_display} = $_->{lib} and last;
405                         }
406                 } elsif ($column =~ /sort2/) {
407                         foreach (@$Bsort2) {
408                                 ($celvalue eq $_->{authorised_value}) or next;
409                                 $cell{coltitle_display} = $_->{lib} and last;
410                         }
411                 } elsif ($column =~ /category/) {
412                         foreach (@$categoryloop) {
413                                 ($celvalue eq $_->{categorycode}) or next;
414                                 $cell{coltitle_display} = $_->{description} and last;
415                         }
416                 }
417                 push @loopcol, \%cell;
418         }
419
420         #Initialization of cell values.....
421         my %table;
422         foreach my $row (@loopline) {
423                 foreach my $col (@loopcol) {
424                         $debug and warn " init table : $row->{rowtitle} ( $row->{rowtitle_display} ) / $col->{coltitle} ( $col->{coltitle_display} )  ";
425                         $table{$row->{rowtitle}}->{$col->{coltitle}} = 0;
426                 }
427                 $table{$row->{rowtitle}}->{totalrow} = 0;
428         }
429
430 # preparing calculation
431     my $strcalc = "SELECT $linefield, $colfield, ";
432         $strcalc .= ($process == 1) ? " COUNT(*) "                                 :
433                                         ($process == 2) ? "(COUNT(DISTINCT borrowers.borrowernumber))" :
434                                 ($process == 3) ? "(COUNT(DISTINCT issues.itemnumber))"        : '';
435         if ($process == 4) {
436                 my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
437                 $rqbookcount->execute;
438                 my ($bookcount) = $rqbookcount->fetchrow;
439                 $strcalc .= "100*(COUNT(DISTINCT issues.itemnumber))/ $bookcount " ;
440         }
441         $strcalc .= "
442         FROM statistics
443         LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber
444         ";
445         $strcalc .= "LEFT JOIN items ON statistics.itemnumber=items.itemnumber " if (($colsource eq 'items')||@$filters[5]||@$filters[6]||@$filters[7]||@$filters[8]);
446         
447         $strcalc .= "WHERE 1=1 ";
448         @$filters = map {defined($_) and s/\*/%/g; $_} @$filters;
449         $strcalc .= " AND statistics.datetime > '"       . @$filters[0] ."'" if (@$filters[0] );
450         $strcalc .= " AND statistics.datetime < '"       . @$filters[1] ."'" if (@$filters[1] );
451         $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] ."'" if (@$filters[2] );
452         $strcalc .= " AND statistics.itemtype LIKE '"    . @$filters[3] ."'" if (@$filters[3] );
453         $strcalc .= " AND statistics.branch LIKE '"      . @$filters[4] ."'" if (@$filters[4] );
454         $strcalc .= " AND items.ccode LIKE '"            . @$filters[5] ."'" if (@$filters[5] );
455         $strcalc .= " AND items.location LIKE '"         . @$filters[6] ."'" if (@$filters[6] );
456         $strcalc .= " AND items.itemcallnumber >='"      . @$filters[7] ."'" if (@$filters[7] );
457         $strcalc .= " AND items.itemcallnumber <'"       . @$filters[8] ."'" if (@$filters[8] );
458         $strcalc .= " AND borrowers.sort1 LIKE '"        . @$filters[9] ."'" if (@$filters[9] );
459         $strcalc .= " AND borrowers.sort2 LIKE '"        . @$filters[10]."'" if (@$filters[10]);
460         $strcalc .= " AND dayname(datetime) LIKE '"      . $daysel      ."'" if ($daysel  );
461         $strcalc .= " AND monthname(datetime) LIKE '"    . $monthsel    ."'" if ($monthsel);
462         $strcalc .= " AND statistics.type LIKE '"        . $type        ."'" if ($type    );
463
464         $strcalc .= " GROUP BY $linefield, $colfield order by $lineorder,$colorder";
465         ($debug) and warn $strcalc;
466         my $dbcalc = $dbh->prepare($strcalc);
467         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
468         $dbcalc->execute;
469         my ($emptycol,$emptyrow); 
470         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
471                 ($debug) and warn "filling table $row / $col / $value ";
472                 unless (defined $col) {
473                         $emptycol = 1; 
474                         $col = "zzEMPTY" ;
475                 }
476                 unless (defined $row) {
477                         $emptyrow = 1;
478                         $row = "zzEMPTY"; 
479                 }
480                 $table{$row}->{$col}     += $value;
481                 $table{$row}->{totalrow} += $value;
482                 $grantotal += $value;
483         }
484         push @loopcol, {coltitle => "NULL", coltitle_display => 'NULL'} if ($emptycol);
485         push @loopline,{rowtitle => "NULL", rowtitle_display => 'NULL'} if ($emptyrow);
486
487         foreach my $row (@loopline) {
488                 my @loopcell;
489                 #@loopcol ensures the order for columns is common with column titles
490                 # and the number matches the number of columns
491                 foreach my $col (@loopcol) {
492                         my $value = $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
493                         push @loopcell, {value => $value};
494                 }
495                 my $rowtitle = ($row->{rowtitle} eq "NULL") ? "zzEMPTY" : $row->{rowtitle};
496                 push @looprow, {
497                         'rowtitle_display' => $row->{rowtitle_display},
498                         'rowtitle' => $rowtitle,
499                         'loopcell' => \@loopcell,
500                         'totalrow' => $table{$rowtitle}->{totalrow}
501                 };
502         }
503         for my $col ( @loopcol ) {
504                 my $total = 0;
505                 foreach my $row (@looprow) {
506                         $total += $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
507                         $debug and warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
508                 }
509                 push @loopfooter, {'totalcol' => $total};
510         }
511
512         # the header of the table
513         $globalline{loopfilter}=\@loopfilter;
514         # the core of the table
515         $globalline{looprow} = \@looprow;
516         $globalline{loopcol} = \@loopcol;
517         #       # the foot (totals by borrower type)
518         $globalline{loopfooter} = \@loopfooter;
519         $globalline{total}  = $grantotal;
520         $globalline{line}   = $line;
521         $globalline{column} = $column;
522         return [(\%globalline)];
523 }
524
525 sub null_to_zzempty ($) {
526         my $string = shift;
527         defined($string)    or  return 'zzEMPTY';
528         ($string eq "NULL") and return 'zzEMPTY';
529         return $string;         # else return the valid value
530 }
531
532 1;