kohabug 2345: bad comparisons pervade reports
[koha.git] / reports / cat_issues_top.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::Output;
27 use C4::Koha;
28 use C4::Circulation;
29 use C4::Dates qw/format_date format_date_in_iso/;
30 use C4::Members;
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 $input = new CGI;
43 my $do_it=$input->param('do_it');
44 my $fullreportname = "reports/cat_issues_top.tmpl";
45 my $limit = $input->param("Limit");
46 my $column = $input->param("Criteria");
47 my @filters = $input->param("Filter");
48 $filters[0]=format_date_in_iso($filters[0]);
49 $filters[1]=format_date_in_iso($filters[1]);
50 my $output = $input->param("output");
51 my $basename = $input->param("basename");
52 my $mime = $input->param("MIME");
53 my $del = $input->param("sep");
54 #warn "calcul : ".$calc;
55 my ($template, $borrowernumber, $cookie)
56     = get_template_and_user({template_name => $fullreportname,
57                 query => $input,
58                 type => "intranet",
59                 authnotrequired => 0,
60                 flagsrequired => { reports => 1},
61                 debug => 1,
62                 });
63 $template->param(do_it => $do_it,
64         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
65         );
66 if ($do_it) {
67 # Displaying results
68     my $results = calculate($limit, $column, \@filters);
69     if ($output eq "screen"){
70 # Printing results to screen
71         $template->param(mainloop => $results,
72                         limit => $limit);
73         output_html_with_http_headers $input, $cookie, $template->output;
74         exit(1);
75     } else {
76 # Printing to a csv file
77         print $input->header(-type => 'application/vnd.sun.xml.calc',
78                             -encoding    => 'utf-8',
79                             -attachment=>"$basename.csv",
80                             -filename=>"$basename.csv" );
81         my $cols = @$results[0]->{loopcol};
82         my $lines = @$results[0]->{looprow};
83         my $sep;
84         $sep =C4::Context->preference("delimiter");
85 # header top-right
86         print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
87 # Other header
88         foreach my $col ( @$cols ) {
89             print $col->{coltitle}.$sep;
90         }
91         print "Total\n";
92 # Table
93         foreach my $line ( @$lines ) {
94             my $x = $line->{loopcell};
95             print $line->{rowtitle}.$sep;
96             foreach my $cell (@$x) {
97                 print $cell->{value}.$sep;
98             }
99             print $line->{totalrow};
100             print "\n";
101         }
102 # footer
103         print "TOTAL";
104         $cols = @$results[0]->{loopfooter};
105         foreach my $col ( @$cols ) {
106             print $sep.$col->{totalcol};
107         }
108         print $sep.@$results[0]->{total};
109         exit(1);
110     }
111 # Displaying choices
112 } else {
113     my $dbh = C4::Context->dbh;
114     my @values;
115     my %labels;
116     my %select;
117     my $req;
118     
119     my @mime = ( C4::Context->preference("MIME") );
120 #       foreach my $mime (@mime){
121 #               warn "".$mime;
122 #       }
123     
124     my $CGIextChoice=CGI::scrolling_list(
125                 -name     => 'MIME',
126                 -id       => 'MIME',
127                 -values   => \@mime,
128                 -size     => 1,
129                 -multiple => 0 );
130     
131     my @dels = ( C4::Context->preference("delimiter") );
132     my $CGIsepChoice=CGI::scrolling_list(
133                 -name     => 'sep',
134                 -id       => 'sep',
135                 -values   => \@dels,
136                 -size     => 1,
137                 -multiple => 0 );
138     #branch
139     my $branches = GetBranches;
140     my @branchloop;
141     foreach my $thisbranch (keys %$branches) {
142 #                       my $selected = 1 if $thisbranch eq $branch;
143             my %row =(value => $thisbranch,
144 #                                                                       selected => $selected,
145                                     branchname => $branches->{$thisbranch}->{'branchname'},
146                             );
147             push @branchloop, \%row;
148     }
149
150     #doctype
151     my $itemtypes = GetItemTypes;
152     my @itemtypeloop;
153     foreach my $thisitemtype (keys %$itemtypes) {
154 #                       my $selected = 1 if $thisbranch eq $branch;
155             my %row =(value => $thisitemtype,
156 #                                                                       selected => $selected,
157                                     description => $itemtypes->{$thisitemtype}->{'description'},
158                             );
159             push @itemtypeloop, \%row;
160     }
161     
162     #borcat
163     my ($codes,$labels) = GetborCatFromCatType(undef,undef);
164     my @borcatloop;
165     foreach my $thisborcat (sort keys %$labels) {
166 #                       my $selected = 1 if $thisbranch eq $branch;
167             my %row =(value => $thisborcat,
168 #                                                                       selected => $selected,
169                                     description => $labels->{$thisborcat},
170                             );
171             push @borcatloop, \%row;
172     }
173     
174     #Day
175     #Month
176     $template->param(
177                     CGIextChoice => $CGIextChoice,
178                     CGIsepChoice => $CGIsepChoice,
179                     branchloop =>\@branchloop,
180                     itemtypeloop =>\@itemtypeloop,
181                     borcatloop =>\@borcatloop,
182                     );
183 output_html_with_http_headers $input, $cookie, $template->output;
184 }
185
186
187
188
189 sub calculate {
190     my ($line, $column, $filters) = @_;
191     my @mainloop;
192     my @loopfooter;
193     my @loopcol;
194     my @loopline;
195     my @looprow;
196     my %globalline;
197     my $grantotal =0;
198 # extract parameters
199     my $dbh = C4::Context->dbh;
200
201 # Filters
202 # Checking filters
203 #
204     my @loopfilter;
205     for (my $i=0;$i<=6;$i++) {
206         my %cell;
207         if ( @$filters[$i] ) {
208             if (($i==1) and (@$filters[$i-1])) {
209                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
210             }
211             # format the dates filters, otherwise just fill as is
212             if ($i>=2) {
213                 $cell{filter} .= @$filters[$i];
214             } else {
215                 $cell{filter} .= format_date(@$filters[$i]);
216             }            $cell{crit} .="Issue From" if ($i==0);
217             $cell{crit} .="Issue To" if ($i==1);
218             $cell{crit} .="Return From" if ($i==2);
219             $cell{crit} .="Return To" if ($i==3);
220             $cell{crit} .="Branch" if ($i==4);
221             $cell{crit} .="Doc Type" if ($i==5);
222             $cell{crit} .="Bor Cat" if ($i==6);
223             $cell{crit} .="Day" if ($i==7);
224             $cell{crit} .="Month" if ($i==8);
225             $cell{crit} .="Year" if ($i==9);
226             push @loopfilter, \%cell;
227         }
228     }
229     my $colfield;
230     my $colorder;
231     if ($column){
232         $column = "old_issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/));
233         $column = "biblioitems.".$column if $column=~/itemtype/;
234         $column = "borrowers.".$column if $column=~/categorycode/;
235         my @colfilter ;
236         $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ )  ;
237         $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ )  ;
238         $colfilter[0] = @$filters[2] if ($column =~ /returndate/ )  ;
239         $colfilter[1] = @$filters[3] if ($column =~ /returndate/ )  ;
240         $colfilter[0] = @$filters[4] if ($column =~ /branch/ )  ;
241         $colfilter[0] = @$filters[5] if ($column =~ /itemtype/ )  ;
242         $colfilter[0] = @$filters[6] if ($column =~ /category/ )  ;
243     #   $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
244         $colfilter[0] = @$filters[7] if ($column =~ /timestamp/ ) ;
245         $colfilter[0] = @$filters[8] if ($column =~ /timestamp/ ) ;
246         $colfilter[0] = @$filters[9] if ($column =~ /timestamp/ ) ;
247     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
248                                                 
249     # loop cols.
250         if ($column eq "Day") {
251             #Display by day
252             $column = "old_issues.timestamp";
253             $colfield .="dayname($column)";  
254             $colorder .="weekday($column)";
255         } elsif ($column eq "Month") {
256             #Display by Month
257             $column = "old_issues.timestamp";
258             $colfield .="monthname($column)";  
259             $colorder .="month($column)";  
260         } elsif ($column eq "Year") {
261             #Display by Year
262             $column = "old_issues.timestamp";
263             $colfield .="Year($column)";
264             $colorder .= $column;
265         } else {
266             $colfield .= $column;
267             $colorder .= $column;
268         }  
269         
270         my $strsth2;
271         $strsth2 .= "SELECT distinctrow $colfield 
272                      FROM `old_issues` 
273                      LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber 
274                      LEFT JOIN items ON old_issues.itemnumber=items.itemnumber 
275                      LEFT JOIN biblioitems  ON biblioitems.biblioitemnumber=items.biblioitemnumber 
276                      WHERE 1";
277         if (($column=~/timestamp/) or ($column=~/returndate/)){
278             if ($colfilter[1] and ($colfilter[0])){
279                 $strsth2 .= " and $column between '$colfilter[0]' and '$colfilter[1]' " ;
280             } elsif ($colfilter[1]) {
281                     $strsth2 .= " and $column < '$colfilter[1]' " ;
282             } elsif ($colfilter[0]) {
283                 $strsth2 .= " and $column > '$colfilter[0]' " ;
284             }
285         } elsif ($colfilter[0]) {
286             $colfilter[0] =~ s/\*/%/g;
287             $strsth2 .= " and $column LIKE '$colfilter[0]' " ;
288         }
289         $strsth2 .=" group by $colfield";
290         $strsth2 .=" order by $colorder";
291         warn "". $strsth2;
292         
293         my $sth2 = $dbh->prepare( $strsth2 );
294         if (( @colfilter ) and ($colfilter[1])){
295             $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'");
296         } elsif ($colfilter[0]) {
297             $sth2->execute($colfilter[0]);
298         } else {
299             $sth2->execute;
300         }
301         
302     
303         while (my ($celvalue) = $sth2->fetchrow) {
304             my %cell;
305             $cell{coltitle} = ($celvalue?$celvalue:"NULL");
306             push @loopcol, \%cell;
307         }
308     #   warn "fin des titres colonnes";
309     }
310     
311     my $i=0;
312 #       my @totalcol;
313     my $hilighted=-1;
314     
315     #Initialization of cell values.....
316     my @table;
317     
318 #       warn "init table";
319     for (my $i=1;$i<=$line;$i++) {
320         foreach my $col ( @loopcol ) {
321 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
322             $table[$i]->{($col->{coltitle})?$col->{coltitle}:"total"}->{'name'}=0;
323         }
324     }
325
326
327 # preparing calculation
328     my $strcalc ;
329     
330 # Processing average loanperiods
331     $strcalc .= "SELECT DISTINCT biblio.title, COUNT(biblio.biblionumber) AS RANK, biblio.biblionumber AS ID";
332     $strcalc .= " , $colfield " if ($colfield);
333     $strcalc .= " FROM `old_issues` 
334                   LEFT JOIN borrowers ON old_issues.borrowernumber=borrowers.borrowernumber 
335                   LEFT JOIN (items 
336                          LEFT JOIN biblioitems ON biblioitems.biblioitemnumber=items.biblioitemnumber) 
337                     ON items.itemnumber=old_issues.itemnumber 
338                   LEFT JOIN biblio ON (biblio.biblionumber=items.biblionumber) 
339                   WHERE 1";
340
341     @$filters[0]=~ s/\*/%/g if (@$filters[0]);
342     $strcalc .= " AND old_issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
343     @$filters[1]=~ s/\*/%/g if (@$filters[1]);
344     $strcalc .= " AND old_issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] );
345     @$filters[2]=~ s/\*/%/g if (@$filters[2]);
346     $strcalc .= " AND old_issues.returndate > '" . @$filters[2] ."'" if ( @$filters[2] );
347     @$filters[3]=~ s/\*/%/g if (@$filters[3]);
348     $strcalc .= " AND old_issues.returndate < '" . @$filters[3] ."'" if ( @$filters[3] );
349     @$filters[4]=~ s/\*/%/g if (@$filters[4]);
350     $strcalc .= " AND old_issues.branchcode like '" . @$filters[4] ."'" if ( @$filters[4] );
351     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
352     $strcalc .= " AND biblioitems.itemtype like '" . @$filters[5] ."'" if ( @$filters[5] );
353     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
354     $strcalc .= " AND borrowers.categorycode like '" . @$filters[6] ."'" if ( @$filters[6] );
355     @$filters[7]=~ s/\*/%/g if (@$filters[7]);
356     $strcalc .= " AND dayname(old_issues.timestamp) like '" . @$filters[7]."'" if (@$filters[7]);
357     @$filters[8]=~ s/\*/%/g if (@$filters[8]);
358     $strcalc .= " AND monthname(old_issues.timestamp) like '" . @$filters[8]."'" if (@$filters[8]);
359     @$filters[9]=~ s/\*/%/g if (@$filters[9]);
360     $strcalc .= " AND year(old_issues.timestamp) like '" . @$filters[9] ."'" if ( @$filters[9] );
361     
362     $strcalc .= " group by biblio.biblionumber";
363     $strcalc .= ", $colfield" if ($column);
364     $strcalc .= " order by RANK DESC";
365     $strcalc .= ", $colfield " if ($colfield);
366
367 #       my $max;
368 #       if (@loopcol) {
369 #               $max = $line*@loopcol;
370 #       } else { $max=$line;}
371 #       $strcalc .= " LIMIT 0,$max";
372     warn "SQL :". $strcalc;
373     
374     my $dbcalc = $dbh->prepare($strcalc);
375     $dbcalc->execute;
376 #       warn "filling table";
377     my $previous_col;
378     my %indice;
379     while (my  @data = $dbcalc->fetchrow) {
380         my ($row, $rank, $id, $col )=@data;
381         $col = "zzEMPTY" if (!defined($col));
382         $indice{$col}=1 if (not($indice{$col}));
383         $table[$indice{$col}]->{$col}->{'name'}=$row;
384         $table[$indice{$col}]->{$col}->{'count'}=$rank;
385         $table[$indice{$col}]->{$col}->{'link'}=$id;
386 #               warn " ".$i." ".$col. " ".$row;
387         $indice{$col}++;
388     }
389     
390     push @loopcol,{coltitle => "Global"} if not($column);
391     
392     for ($i=1; $i<=$line;$i++) {
393         my @loopcell;
394         warn " $i";
395         #@loopcol ensures the order for columns is common with column titles
396         # and the number matches the number of columns
397         my $colcount=0;
398         foreach my $col ( @loopcol ) {
399 #                       warn " colonne :$col->{coltitle}";
400             my $value;
401             my $count=0;
402             my $link;
403             if (@loopcol){
404                 $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'name'};
405                 $count =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'count'};
406                 $link =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'link'};
407             } else {
408                 $value =$table[$i]->{"zzEMPTY"}->{'name'};
409                 $count =$table[$i]->{"zzEMPTY"}->{'count'};
410                 $link =$table[$i]->{"zzEMPTY"}->{'link'};
411             }
412 #                       warn " ".$i ." value:$value count:$count reference:$link";
413             push @loopcell, {value => $value, count =>$count, reference => $link} ;
414         }
415         #warn "row : $row colcount:$colcount";
416         #my $total = $table[$i]->{totalrow}/$colcount if ($colcount>0);
417         push @looprow,{ 'rowtitle' => $i ,
418                         'loopcell' => \@loopcell,
419                         'hilighted' => ($hilighted >0),
420                         #'totalrow' => ($total)?sprintf("%.2f",$total):0
421                     };
422         $hilighted = -$hilighted;
423     }
424 #       
425             
426
427     # the header of the table
428     $globalline{loopfilter}=\@loopfilter;
429     # the core of the table
430     $globalline{looprow} = \@looprow;
431     $globalline{loopcol} = \@loopcol;
432 #       # the foot (totals by borrower type)
433     $globalline{loopfooter} = \@loopfooter;
434     $globalline{total}= $grantotal;
435     $globalline{line} = $line;
436     $globalline{column} = $column;
437     push @mainloop,\%globalline;
438     return \@mainloop;
439 }
440
441 1;