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