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