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