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