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