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