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