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