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