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