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