Adding Reports on issues Stats
[koha.git] / reports / issues_stats.pl
1 #!/usr/bin/perl
2
3 # $Id$
4
5 # Copyright 2000-2002 Katipo Communications
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 USA
21
22 use strict;
23 use C4::Auth;
24 use CGI;
25 use C4::Context;
26 use HTML::Template;
27 use C4::Search;
28 use C4::Output;
29 use C4::Koha;
30 use C4::Interface::CGI::Output;
31 use C4::Circulation::Circ2;
32
33 =head1 NAME
34
35 plugin that shows a stats on borrowers
36
37 =head1 DESCRIPTION
38
39
40 =over2
41
42 =cut
43
44 my $input = new CGI;
45 my $do_it=$input->param('do_it');
46 my $fullreportname = "reports/issues_stats.tmpl";
47 my $line = $input->param("Line");
48 my $column = $input->param("Column");
49 my @filters = $input->param("Filter");
50 my $podsp = $input->param("DisplayBy");
51 my $type = $input->param("PeriodTypeSel");
52 my $daysel = $input->param("PeriodDaySel");
53 my $monthsel = $input->param("PeriodMonthSel");
54 my $calc = $input->param("Cellvalue");
55 my $output = $input->param("output");
56 my $basename = $input->param("basename");
57 my $mime = $input->param("MIME");
58 my $del = $input->param("sep");
59 #warn "calcul : ".$calc;
60 my ($template, $borrowernumber, $cookie)
61         = get_template_and_user({template_name => $fullreportname,
62                                 query => $input,
63                                 type => "intranet",
64                                 authnotrequired => 0,
65                                 flagsrequired => {editcatalogue => 1},
66                                 debug => 1,
67                                 });
68 $template->param(do_it => $do_it);
69 if ($do_it) {
70 # Displaying results
71         my $results = calculate($line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters);
72         if ($output eq "screen"){
73 # Printing results to screen
74                 $template->param(mainloop => $results);
75                 output_html_with_http_headers $input, $cookie, $template->output;
76                 exit(1);
77         } else {
78 # Printing to a csv file
79                 print $input->header(-type => 'application/vnd.ms-excel',
80                 -disposition=>'inline',
81 #               -title=>"$basename.csv",
82 #               -file=>"$basename.csv",
83                 -filename=>"$basename.csv" );
84                 my $cols = @$results[0]->{loopcol};
85                 my $lines = @$results[0]->{looprow};
86                 my $sep;
87                 $sep =C4::Context->preference("delimiter");
88 # header top-right
89                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
90 # Other header
91                 foreach my $col ( @$cols ) {
92                         print $col->{coltitle}.$sep;
93                 }
94                 print "\n";
95 # Table
96                 foreach my $line ( @$lines ) {
97                         my $x = $line->{loopcell};
98                         print $line->{rowtitle}.$sep;
99                         foreach my $cell (@$x) {
100                                 print $cell->{value}.$sep;
101                         }
102                         print $line->{totalrow};
103                         print "\n";
104                 }
105 # footer
106                 print "TOTAL";
107                 $cols = @$results[0]->{loopfooter};
108                 foreach my $col ( @$cols ) {
109                         print $sep.$col->{totalcol};
110                 }
111                 print $sep.@$results[0]->{total};
112                 exit(1);
113         }
114 # Displaying choices
115 } else {
116         my $dbh = C4::Context->dbh;
117         my @values;
118         my %labels;
119         my %select;
120         my $req;
121         $req = $dbh->prepare("select distinctrow categorycode,description from categories order by description");
122         $req->execute;
123         my @select;
124         push @select,"";
125         $select{""}="";
126         while (my ($value, $desc) =$req->fetchrow) {
127                 push @select, $value;
128                 $select{$value}=$desc;
129         }
130         my $CGIBorCat=CGI::scrolling_list( -name     => 'Filter',
131                                 -id => 'Filter',
132                                 -values   => \@select,
133                                 -labels   => \%select,
134                                 -size     => 1,
135                                 -multiple => 0 );
136         
137         $req = $dbh->prepare( "select distinctrow itemtype,description from itemtypes order by description");
138         $req->execute;
139         undef @select;
140         undef %select;
141         push @select,"";
142         $select{""}="";
143         while (my ($value,$desc) =$req->fetchrow) {
144                 push @select, $value;
145                 $select{$value}=$desc;
146         }
147         my $CGIItemTypes=CGI::scrolling_list( -name     => 'Filter',
148                                 -id => 'Filter',
149                                 -values   => \@select,
150                                 -labels    => \%select,
151                                 -size     => 1,
152                                 -multiple => 0 );
153         
154         $req = $dbh->prepare("select distinctrow sort1 from borrowers where sort1 is not null order by sort1");
155         $req->execute;
156         undef @select;
157         push @select,"";
158         my $hassort1;
159         while (my ($value) =$req->fetchrow) {
160                 $hassort1 =1 if ($value);
161                 push @select, $value;
162         }
163         my $branches=getbranches();
164         my @select_branch;
165         my %select_branches;
166         push @select_branch,"";
167         $select_branches{""} = "";
168         foreach my $branch (keys %$branches) {
169                 push @select_branch, $branch;
170                 $select_branches{$branch} = $branches->{$branch}->{'branchname'};
171         }
172         my $CGIBranch=CGI::scrolling_list( -name     => 'Filter',
173                                 -id => 'Filter',
174                                 -values   => \@select_branch,
175                                 -labels   => \%select_branches,
176                                 -size     => 1,
177                                 -multiple => 0 );
178         
179         my $CGISort1=CGI::scrolling_list( -name     => 'Filter',
180                                 -id => 'Filter',
181                                 -values   => \@select,
182                                 -size     => 1,
183                                 -multiple => 0 );
184         
185         $req = $dbh->prepare("select distinctrow sort2 from borrowers where sort2 is not null order by sort2");
186         $req->execute;
187         undef @select;
188         push @select,"";
189         my $hassort2;
190         my $hglghtsort2;
191         while (my ($value) =$req->fetchrow) {
192                 $hassort2 =1 if ($value);
193                 $hglghtsort2= !($hassort1);
194                 push @select, $value;
195         }
196         my $CGISort2=CGI::scrolling_list( -name     => 'Filter',
197                                 -id => 'Filter',
198                                 -values   => \@select,
199                                 -size     => 1,
200                                 -multiple => 0 );
201         
202         my @mime = ( C4::Context->preference("MIME") );
203 #       foreach my $mime (@mime){
204 #               warn "".$mime;
205 #       }
206         
207         my $CGIextChoice=CGI::scrolling_list(
208                                 -name     => 'MIME',
209                                 -id       => 'MIME',
210                                 -values   => \@mime,
211                                 -size     => 1,
212                                 -multiple => 0 );
213         
214         my @dels = ( C4::Context->preference("delimiter") );
215         my $CGIsepChoice=CGI::scrolling_list(
216                                 -name     => 'sep',
217                                 -id       => 'sep',
218                                 -values   => \@dels,
219                                 -size     => 1,
220                                 -multiple => 0 );
221         
222         $template->param(
223                                         CGIBorCat => $CGIBorCat,
224                                         CGIItemType => $CGIItemTypes,
225                                         CGIBranch => $CGIBranch,
226                                         hassort1=> $hassort1,
227                                         hassort2=> $hassort2,
228                                         HlghtSort2 => $hglghtsort2,
229                                         CGISort1 => $CGISort1,
230                                         CGISort2 => $CGISort2,
231                                         CGIextChoice => $CGIextChoice,
232                                         CGIsepChoice => $CGIsepChoice
233                                         );
234 output_html_with_http_headers $input, $cookie, $template->output;
235 }
236
237
238
239
240 sub calculate {
241         my ($line, $column, $dsp, $type,$daysel,$monthsel ,$process, $filters) = @_;
242         my @mainloop;
243         my @loopfooter;
244         my @loopcol;
245         my @loopline;
246         my @looprow;
247         my %globalline;
248         my $grantotal =0;
249 # extract parameters
250         my $dbh = C4::Context->dbh;
251
252 # Filters
253 # Checking filters
254 #
255         my @loopfilter;
256         for (my $i=0;$i<=6;$i++) {
257                 my %cell;
258                 if ( @$filters[$i] ) {
259                         if (($i==1) and (@$filters[$i-1])) {
260                                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
261                         }
262                         $cell{filter} .= @$filters[$i];
263                         $cell{crit} .="Period From" if ($i==0);
264                         $cell{crit} .="Period To" if ($i==1);
265                         $cell{crit} .="Borrower Cat" if ($i==2);
266                         $cell{crit} .="Doc Type" if ($i==3);
267                         $cell{crit} .="Branch" if ($i==4);
268                         $cell{crit} .="Sort1" if ($i==5);
269                         $cell{crit} .="Sort2" if ($i==6);
270                         push @loopfilter, \%cell;
271                 }
272         }
273         push @loopfilter,{crit=>"Issue|Return : ",filter=>$type};
274         push @loopfilter,{crit=>"Display by :",filter=>$dsp} if ($dsp);
275         push @loopfilter,{crit=>"Select Day :",filter=>$daysel} if ($daysel);
276         push @loopfilter,{crit=>"Select Month :",filter=>$daysel} if ($monthsel);
277         
278         
279         my @linefilter;
280 #       warn "filtres ".@filters[0];
281 #       warn "filtres ".@filters[1];
282 #       warn "filtres ".@filters[2];
283 #       warn "filtres ".@filters[3];
284         
285         $linefilter[0] = @$filters[0] if ($line =~ /datetime/ )  ;
286         $linefilter[1] = @$filters[1] if ($line =~ /datetime/ )  ;
287         $linefilter[0] = @$filters[2] if ($line =~ /category/ )  ;
288         $linefilter[0] = @$filters[3] if ($line =~ /itemtype/ )  ;
289         $linefilter[0] = @$filters[4] if ($line =~ /branch/ )  ;
290 #       $linefilter[0] = @$filters[11] if ($line =~ /sort2/ ) ;
291         $linefilter[0] = @$filters[5] if ($line =~ /sort1/ ) ;
292         $linefilter[0] = @$filters[6] if ($line =~ /sort2/ ) ;
293 #warn "filtre lignes".$linefilter[0]." ".$linefilter[1];
294
295         my @colfilter ;
296         $colfilter[0] = @$filters[0] if ($column =~ /datetime/) ;
297         $colfilter[1] = @$filters[1] if ($column =~ /datetime/) ;
298         $colfilter[0] = @$filters[2] if ($column =~ /category/) ;
299         $colfilter[0] = @$filters[3] if ($column =~ /itemtype/) ;
300         $colfilter[0] = @$filters[4] if ($column =~ /branch/ )  ;
301         $colfilter[0] = @$filters[5] if ($column =~ /sort1/  )  ;
302         $colfilter[0] = @$filters[6] if ($column =~ /sort2/  )  ;
303 #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
304                                               
305 # 1st, loop rows.                             
306         my $linefield;                               
307         if (($line =~/datetime/) and ($dsp == 1)) {
308                 #Display by day
309                 $linefield .="dayname($line)";  
310         } elsif (($line=~/datetime/) and ($dsp == 2)) {
311                 #Display by Month
312                 $linefield .="monthname($line)";  
313         } elsif (($line=~/datetime/) and ($dsp == 3)) {
314                 #Display by Year
315                 $linefield .="Year($line)";
316         } elsif ($line=~/datetime/) {
317                 $linefield .= 'date_format(`datetime`,"%Y-%m-%d")';
318         } else {
319                 $linefield .= $line;
320         }  
321         
322         my $strsth;
323         $strsth .= "select distinctrow $linefield from statistics, borrowers where (statistics.borrowernumber=borrowers.borrowernumber) and $line is not null ";
324         
325         if ($line=~/datetime/) {
326                 if ($linefilter[1] and ($linefilter[0])){
327                         $strsth .= " and $line between ? and ? " ;
328                 } elsif ($linefilter[1]) {
329                                 $strsth .= " and $line < ? " ;
330                 } elsif ($linefilter[0]) {
331                         $strsth .= " and $line > ? " ;
332                 }
333                 $strsth .= " and type ='".$type."' " if $type;
334                 $strsth .= " and dayname(datetime) ='". $daysel ."' " if $daysel;
335                 $strsth .= " and monthname(datetime) ='". $monthsel ."' " if $monthsel;
336         } elsif ($linefilter[0]) {
337                 $linefilter[0] =~ s/\*/%/g;
338                 $strsth .= " and $line LIKE ? " ;
339         }
340         $strsth .=" group by $linefield";
341         $strsth .=" order by $linefield";
342 #       warn "". $strsth;
343         
344         my $sth = $dbh->prepare( $strsth );
345         if (( @linefilter ) and ($linefilter[1])){
346                 $sth->execute("'".$linefilter[0]."'","'".$linefilter[1]."'");
347         } elsif ($linefilter[0]) {
348                 $sth->execute($linefilter[0]);
349         } else {
350                 $sth->execute;
351         }
352         
353         while ( my ($celvalue) = $sth->fetchrow) {
354                 my %cell;
355                 if ($celvalue) {
356                         $cell{rowtitle} = $celvalue;
357                 } else {
358                         $cell{rowtitle} = "";
359                 }
360                 $cell{totalrow} = 0;
361                 push @loopline, \%cell;
362         }
363
364 # 2nd, loop cols.
365         my $colfield;                               
366         if (($column =~/datetime/) and ($dsp == 1)) {
367                 #Display by day
368                 $colfield .="dayname($column)";  
369         } elsif (($column=~/datetime/) and ($dsp == 2)) {
370                 #Display by Month
371                 $colfield .="monthname($column)";  
372         } elsif (($column=~/datetime/) and ($dsp == 3)) {
373                 #Display by Year
374                 $colfield .="Year($column)";
375         } elsif ($column=~/datetime/) {
376                 $colfield .='date_format(`datetime`,"%Y-%m-%d")';       
377         } else {
378                 $colfield .= $column;
379         }  
380         
381         my $strsth2;
382         $strsth2 .= "select distinctrow $colfield from statistics, borrowers where (statistics.borrowernumber=borrowers.borrowernumber) and $column is not null ";
383         
384         if ($column=~/datetime/){
385                 if (($colfilter[1]) and ($colfilter[0])){
386                         $strsth2 .= " and $column between ? and ? " ;
387                 } elsif ($colfilter[1]) {
388                         $strsth2 .= " and $column < ? " ;
389                 } elsif ($colfilter[0]) {
390                         $strsth2 .= " and $column > ? " ;
391                 }
392                 $strsth2 .= " and type ='".$type."' " if $type;
393                 $strsth2 .= " and dayname(datetime) ='". $daysel ."' " if $daysel;
394                 $strsth2 .= " and monthname(datetime) ='". $monthsel ."' " if $monthsel;
395         } elsif ($colfilter[0]) {
396                 $colfilter[0] =~ s/\*/%/g;
397                 $strsth2 .= " and $column LIKE ? " ;
398         }
399         $strsth2 .=" group by $colfield";
400         $strsth2 .=" order by $colfield";
401 #       warn "". $strsth2;
402         
403         my $sth2 = $dbh->prepare( $strsth2 );
404         if (( @colfilter ) and ($colfilter[1])){
405                 $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'");
406         } elsif ($colfilter[0]) {
407                 $sth2->execute($colfilter[0]);
408         } else {
409                 $sth2->execute;
410         }
411         
412
413         while (my ($celvalue) = $sth2->fetchrow) {
414                 my %cell;
415                 my %ft;
416 #               warn "coltitle :".$celvalue;
417                 $cell{coltitle} = $celvalue;
418                 $ft{totalcol} = 0;
419                 push @loopcol, \%cell;
420         }
421 #       warn "fin des titres colonnes";
422
423         my $i=0;
424         my @totalcol;
425         my $hilighted=-1;
426         
427         #Initialization of cell values.....
428         my %table;
429 #       warn "init table";
430         foreach my $row ( @loopline ) {
431                 foreach my $col ( @loopcol ) {
432 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
433                         $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
434                 }
435                 $table{$row->{rowtitle}}->{totalrow}=0;
436         }
437
438 # preparing calculation
439         my $strcalc ;
440         $strcalc .= "SELECT $linefield, $colfield, ";
441         $strcalc .= "COUNT( * ) " if ($process ==1);
442         if ($process ==3){
443         my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
444         $rqbookcount->execute;
445         my ($bookcount) = $rqbookcount->fetchrow;
446         $strcalc .= "100*(COUNT(itemnumber))/ $bookcount " ;
447         }
448         $strcalc .= "FROM statistics,borrowers where (statistics.borrowernumber=borrowers.borrowernumber) and $column is not null and $line is not null ";
449
450         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
451         $strcalc .= " AND statistics.datetime > '" . @$filters[0] ."'" if ( @$filters[0] );
452         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
453         $strcalc .= " AND statistics.datetime < '" . @$filters[1] ."'" if ( @$filters[1] );
454         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
455         $strcalc .= " AND borrowers.categorycode like '" . @$filters[2] ."'" if ( @$filters[2] );
456         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
457         $strcalc .= " AND statistics.itemtype like '" . @$filters[3] ."'" if ( @$filters[3] );
458         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
459         $strcalc .= " AND statistics.branch like '" . @$filters[4] ."'" if ( @$filters[4] );
460         @$filters[5]=~ s/\*/%/g if (@$filters[5]);
461         $strcalc .= " AND borrowers.sort1 like '" . @$filters[5] ."'" if ( @$filters[5] );
462         @$filters[6]=~ s/\*/%/g if (@$filters[6]);
463         $strcalc .= " AND borrowers.sort2 like '" . @$filters[6] ."'" if ( @$filters[6] );
464         $strcalc .= " AND dayname(datetime) like '" . $daysel ."'" if ( $daysel );
465         $strcalc .= " AND monthname(datetime) like '" . $monthsel ."'" if ( $monthsel );
466         $strcalc .= " AND statistics.type like '" . $type ."'" if ( $type );
467         
468         $strcalc .= " group by $linefield, $colfield order by $linefield,$colfield";
469 #       warn "". $strcalc;
470         my $dbcalc = $dbh->prepare($strcalc);
471         $dbcalc->execute;
472 #       warn "filling table";
473         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
474 #               warn "filling table $row / $col / $value ";
475                 $table{$row}->{$col}=$value;
476                 $table{$row}->{totalrow}+=$value;
477                 $grantotal += $value;
478         }
479         
480         foreach my $row ( sort keys %table ) {
481                 my @loopcell;
482                 #@loopcol ensures the order for columns is common with column titles
483                 foreach my $col ( @loopcol ) {
484                         push @loopcell, {value => $table{$row}->{$col->{coltitle}}} ;
485                 }
486                 push @looprow,{ 'rowtitle' => $row,
487                                                 'loopcell' => \@loopcell,
488                                                 'hilighted' => 1 ,
489                                                 'totalrow' => $table{$row}->{totalrow}
490                                         };
491                 $hilighted = -$hilighted;
492         }
493         
494 #       warn "footer processing";
495         foreach my $col ( @loopcol ) {
496                 my $total=0;
497                 foreach my $row ( @looprow ) {
498                         $total += $table{$row->{rowtitle}}->{$col->{coltitle}};
499 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
500                 }
501 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
502                 push @loopfooter, {'totalcol' => $total};
503         }
504                         
505
506         # the header of the table
507         $globalline{loopfilter}=\@loopfilter;
508         # the core of the table
509         $globalline{looprow} = \@looprow;
510         $globalline{loopcol} = \@loopcol;
511 #       # the foot (totals by borrower type)
512         $globalline{loopfooter} = \@loopfooter;
513         $globalline{total}= $grantotal;
514         $globalline{line} = $line;
515         $globalline{column} = $column;
516         push @mainloop,\%globalline;
517         return \@mainloop;
518 }
519
520 1;