Fixing : Including packages calls
[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 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                         -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         
203         my @mime = ( C4::Context->preference("MIME") );
204 #       foreach my $mime (@mime){
205 #               warn "".$mime;
206 #       }
207         
208         my $CGIextChoice=CGI::scrolling_list(
209                                 -name     => 'MIME',
210                                 -id       => 'MIME',
211                                 -values   => \@mime,
212                                 -size     => 1,
213                                 -multiple => 0 );
214         
215         my @dels = ( C4::Context->preference("delimiter") );
216         my $CGIsepChoice=CGI::scrolling_list(
217                                 -name     => 'sep',
218                                 -id       => 'sep',
219                                 -values   => \@dels,
220                                 -size     => 1,
221                                 -multiple => 0 );
222         
223         $template->param(
224                                         CGIBorCat => $CGIBorCat,
225                                         CGIItemType => $CGIItemTypes,
226                                         CGIBranch => $CGIBranch,
227                                         hassort1=> $hassort1,
228                                         hassort2=> $hassort2,
229                                         HlghtSort2 => $hglghtsort2,
230                                         CGISort1 => $CGISort1,
231                                         CGISort2 => $CGISort2,
232                                         CGIextChoice => $CGIextChoice,
233                                         CGIsepChoice => $CGIsepChoice
234                                         );
235 output_html_with_http_headers $input, $cookie, $template->output;
236 }
237
238
239
240
241 sub calculate {
242         my ($line, $column, $dsp, $type,$daysel,$monthsel ,$process, $filters) = @_;
243         my @mainloop;
244         my @loopfooter;
245         my @loopcol;
246         my @loopline;
247         my @looprow;
248         my %globalline;
249         my $grantotal =0;
250 # extract parameters
251         my $dbh = C4::Context->dbh;
252
253 # Filters
254 # Checking filters
255 #
256         my @loopfilter;
257         for (my $i=0;$i<=6;$i++) {
258                 my %cell;
259                 if ( @$filters[$i] ) {
260                         if (($i==1) and (@$filters[$i-1])) {
261                                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
262                         }
263                         $cell{filter} .= @$filters[$i];
264                         $cell{crit} .="Period From" if ($i==0);
265                         $cell{crit} .="Period To" if ($i==1);
266                         $cell{crit} .="Borrower Cat" if ($i==2);
267                         $cell{crit} .="Doc Type" if ($i==3);
268                         $cell{crit} .="Branch" if ($i==4);
269                         $cell{crit} .="Sort1" if ($i==5);
270                         $cell{crit} .="Sort2" if ($i==6);
271                         push @loopfilter, \%cell;
272                 }
273         }
274         push @loopfilter,{crit=>"Issue|Return ",filter=>$type};
275         push @loopfilter,{crit=>"Display by ",filter=>$dsp} if ($dsp);
276         push @loopfilter,{crit=>"Select Day ",filter=>$daysel} if ($daysel);
277         push @loopfilter,{crit=>"Select Month ",filter=>$daysel} if ($monthsel);
278         
279         
280         my @linefilter;
281 #       warn "filtres ".@filters[0];
282 #       warn "filtres ".@filters[1];
283 #       warn "filtres ".@filters[2];
284 #       warn "filtres ".@filters[3];
285         
286         $linefilter[0] = @$filters[0] if ($line =~ /datetime/ )  ;
287         $linefilter[1] = @$filters[1] if ($line =~ /datetime/ )  ;
288         $linefilter[0] = @$filters[2] if ($line =~ /category/ )  ;
289         $linefilter[0] = @$filters[3] if ($line =~ /itemtype/ )  ;
290         $linefilter[0] = @$filters[4] if ($line =~ /branch/ )  ;
291 #       $linefilter[0] = @$filters[11] if ($line =~ /sort2/ ) ;
292         $linefilter[0] = @$filters[5] if ($line =~ /sort1/ ) ;
293         $linefilter[0] = @$filters[6] if ($line =~ /sort2/ ) ;
294 #warn "filtre lignes".$linefilter[0]." ".$linefilter[1];
295
296         my @colfilter ;
297         $colfilter[0] = @$filters[0] if ($column =~ /datetime/) ;
298         $colfilter[1] = @$filters[1] if ($column =~ /datetime/) ;
299         $colfilter[0] = @$filters[2] if ($column =~ /category/) ;
300         $colfilter[0] = @$filters[3] if ($column =~ /itemtype/) ;
301         $colfilter[0] = @$filters[4] if ($column =~ /branch/ )  ;
302         $colfilter[0] = @$filters[5] if ($column =~ /sort1/  )  ;
303         $colfilter[0] = @$filters[6] if ($column =~ /sort2/  )  ;
304 #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
305                                               
306 # 1st, loop rows.                             
307         my $linefield;                               
308         if (($line =~/datetime/) and ($dsp == 1)) {
309                 #Display by day
310                 $linefield .="dayname($line)";  
311         } elsif (($line=~/datetime/) and ($dsp == 2)) {
312                 #Display by Month
313                 $linefield .="monthname($line)";  
314         } elsif (($line=~/datetime/) and ($dsp == 3)) {
315                 #Display by Year
316                 $linefield .="Year($line)";
317         } elsif ($line=~/datetime/) {
318                 $linefield .= 'date_format(`datetime`,"%Y-%m-%d")';
319         } else {
320                 $linefield .= $line;
321         }  
322         
323         my $strsth;
324         $strsth .= "select distinctrow $linefield from statistics, borrowers where (statistics.borrowernumber=borrowers.borrowernumber) and $line is not null ";
325         
326         if ($line=~/datetime/) {
327                 if ($linefilter[1] and ($linefilter[0])){
328                         $strsth .= " and $line between ? and ? " ;
329                 } elsif ($linefilter[1]) {
330                                 $strsth .= " and $line < ? " ;
331                 } elsif ($linefilter[0]) {
332                         $strsth .= " and $line > ? " ;
333                 }
334                 $strsth .= " and type ='".$type."' " if $type;
335                 $strsth .= " and dayname(datetime) ='". $daysel ."' " if $daysel;
336                 $strsth .= " and monthname(datetime) ='". $monthsel ."' " if $monthsel;
337         } elsif ($linefilter[0]) {
338                 $linefilter[0] =~ s/\*/%/g;
339                 $strsth .= " and $line LIKE ? " ;
340         }
341         $strsth .=" group by $linefield";
342         $strsth .=" order by $linefield";
343 #       warn "". $strsth;
344         
345         my $sth = $dbh->prepare( $strsth );
346         if (( @linefilter ) and ($linefilter[1])){
347                 $sth->execute("'".$linefilter[0]."'","'".$linefilter[1]."'");
348         } elsif ($linefilter[0]) {
349                 $sth->execute($linefilter[0]);
350         } else {
351                 $sth->execute;
352         }
353         
354         while ( my ($celvalue) = $sth->fetchrow) {
355                 my %cell;
356                 if ($celvalue) {
357                         $cell{rowtitle} = $celvalue;
358                 } else {
359                         $cell{rowtitle} = "";
360                 }
361                 $cell{totalrow} = 0;
362                 push @loopline, \%cell;
363         }
364
365 # 2nd, loop cols.
366         my $colfield;                               
367         if (($column =~/datetime/) and ($dsp == 1)) {
368                 #Display by day
369                 $colfield .="dayname($column)";  
370         } elsif (($column=~/datetime/) and ($dsp == 2)) {
371                 #Display by Month
372                 $colfield .="monthname($column)";  
373         } elsif (($column=~/datetime/) and ($dsp == 3)) {
374                 #Display by Year
375                 $colfield .="Year($column)";
376         } elsif ($column=~/datetime/) {
377                 $colfield .='date_format(`datetime`,"%Y-%m-%d")';       
378         } else {
379                 $colfield .= $column;
380         }  
381         
382         my $strsth2;
383         $strsth2 .= "select distinctrow $colfield from statistics, borrowers where (statistics.borrowernumber=borrowers.borrowernumber) and $column is not null ";
384         
385         if ($column=~/datetime/){
386                 if (($colfilter[1]) and ($colfilter[0])){
387                         $strsth2 .= " and $column between ? and ? " ;
388                 } elsif ($colfilter[1]) {
389                         $strsth2 .= " and $column < ? " ;
390                 } elsif ($colfilter[0]) {
391                         $strsth2 .= " and $column > ? " ;
392                 }
393                 $strsth2 .= " and type ='".$type."' " if $type;
394                 $strsth2 .= " and dayname(datetime) ='". $daysel ."' " if $daysel;
395                 $strsth2 .= " and monthname(datetime) ='". $monthsel ."' " if $monthsel;
396         } elsif ($colfilter[0]) {
397                 $colfilter[0] =~ s/\*/%/g;
398                 $strsth2 .= " and $column LIKE ? " ;
399         }
400         $strsth2 .=" group by $colfield";
401         $strsth2 .=" order by $colfield";
402 #       warn "". $strsth2;
403         
404         my $sth2 = $dbh->prepare( $strsth2 );
405         if (( @colfilter ) and ($colfilter[1])){
406                 $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'");
407         } elsif ($colfilter[0]) {
408                 $sth2->execute($colfilter[0]);
409         } else {
410                 $sth2->execute;
411         }
412         
413
414         while (my ($celvalue) = $sth2->fetchrow) {
415                 my %cell;
416                 my %ft;
417 #               warn "coltitle :".$celvalue;
418                 $cell{coltitle} = $celvalue;
419                 $ft{totalcol} = 0;
420                 push @loopcol, \%cell;
421         }
422 #       warn "fin des titres colonnes";
423
424         my $i=0;
425         my @totalcol;
426         my $hilighted=-1;
427         
428         #Initialization of cell values.....
429         my %table;
430 #       warn "init table";
431         foreach my $row ( @loopline ) {
432                 foreach my $col ( @loopcol ) {
433 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
434                         $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
435                 }
436                 $table{$row->{rowtitle}}->{totalrow}=0;
437         }
438
439 # preparing calculation
440         my $strcalc ;
441
442         $strcalc .= "SELECT $linefield, $colfield, ";
443         $strcalc .= "COUNT( * ) " if ($process ==1);
444         if ($process ==3){
445                 my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
446                 $rqbookcount->execute;
447                 my ($bookcount) = $rqbookcount->fetchrow;
448                 $strcalc .= "100*(COUNT(itemnumber))/ $bookcount " ;
449         }
450         $strcalc .= "FROM statistics,borrowers where (statistics.borrowernumber=borrowers.borrowernumber) ";
451
452         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
453         $strcalc .= " AND statistics.datetime > '" . @$filters[0] ."'" if ( @$filters[0] );
454         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
455         $strcalc .= " AND statistics.datetime < '" . @$filters[1] ."'" if ( @$filters[1] );
456         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
457         $strcalc .= " AND borrowers.categorycode like '" . @$filters[2] ."'" if ( @$filters[2] );
458         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
459         $strcalc .= " AND statistics.itemtype like '" . @$filters[3] ."'" if ( @$filters[3] );
460         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
461         $strcalc .= " AND statistics.branch like '" . @$filters[4] ."'" if ( @$filters[4] );
462         @$filters[5]=~ s/\*/%/g if (@$filters[5]);
463         $strcalc .= " AND borrowers.sort1 like '" . @$filters[5] ."'" if ( @$filters[5] );
464         @$filters[6]=~ s/\*/%/g if (@$filters[6]);
465         $strcalc .= " AND borrowers.sort2 like '" . @$filters[6] ."'" if ( @$filters[6] );
466         $strcalc .= " AND dayname(datetime) like '" . $daysel ."'" if ( $daysel );
467         $strcalc .= " AND monthname(datetime) like '" . $monthsel ."'" if ( $monthsel );
468         $strcalc .= " AND statistics.type like '" . $type ."'" if ( $type );
469         
470         $strcalc .= " group by $linefield, $colfield order by $linefield,$colfield";
471 #       warn "". $strcalc;
472         my $dbcalc = $dbh->prepare($strcalc);
473         $dbcalc->execute;
474 #       warn "filling table";
475         my $emptycol; 
476         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
477 #               warn "filling table $row / $col / $value ";
478                 $emptycol = 1 if ($col eq undef);
479                 $col = "zzEMPTY" if ($col eq undef);
480                 $row = "zzEMPTY" if ($row eq undef);
481                 
482                 $table{$row}->{$col}+=$value;
483                 $table{$row}->{totalrow}+=$value;
484                 $grantotal += $value;
485         }
486         push @loopcol,{coltitle => "NULL"} if ($emptycol);
487
488         foreach my $row ( sort keys %table ) {
489                 my @loopcell;
490                 #@loopcol ensures the order for columns is common with column titles
491                 # and the number matches the number of columns
492                 foreach my $col ( @loopcol ) {
493                         my $value =$table{$row}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
494                         push @loopcell, {value => $value  } ;
495                 }
496                 push @looprow,{ 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
497                                                         'loopcell' => \@loopcell,
498                                                         'hilighted' => ($hilighted >0),
499                                                         'totalrow' => $table{$row}->{totalrow}
500                                                 };
501                 $hilighted = -$hilighted;
502         }
503         
504 #       warn "footer processing";
505         foreach my $col ( @loopcol ) {
506                 my $total=0;
507                 foreach my $row ( @looprow ) {
508                         $total += $table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
509 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
510                 }
511 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
512                 push @loopfooter, {'totalcol' => $total};
513         }
514                         
515
516         # the header of the table
517         $globalline{loopfilter}=\@loopfilter;
518         # the core of the table
519         $globalline{looprow} = \@looprow;
520         $globalline{loopcol} = \@loopcol;
521 #       # the foot (totals by borrower type)
522         $globalline{loopfooter} = \@loopfooter;
523         $globalline{total}= $grantotal;
524         $globalline{line} = $line;
525         $globalline{column} = $column;
526         push @mainloop,\%globalline;
527         return \@mainloop;
528 }
529
530 1;