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