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