minor code rewritte
[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 CGI;
24 use C4::Auth;
25 use C4::Output;
26 use C4::Context;
27 use C4::Branch; # GetBranches
28 use C4::Koha;
29 use C4::Circulation;
30 use C4::Members;
31 use Date::Manip;
32
33 =head1 NAME
34
35 plugin that shows a stats on borrowers
36
37 =head1 DESCRIPTION
38
39
40 =over2
41
42 =cut
43
44 my $input = new CGI;
45 my $do_it=$input->param('do_it');
46 my $fullreportname = "reports/bor_issues_top.tmpl";
47 my $limit = $input->param("Limit");
48 my $column = $input->param("Criteria");
49 my @filters = $input->param("Filter");
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                 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
65                 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
66                 IntranetNav => C4::Context->preference("IntranetNav"),
67                 );
68 if ($do_it) {
69 # Displaying results
70         my $results = calculate($limit, $column, \@filters);
71         if ($output eq "screen"){
72 # Printing results to screen
73                 $template->param(mainloop => $results, 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                 my $sep;
85                 $sep =C4::Context->preference("delimiter");
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(1);
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 @mime = ( C4::Context->preference("MIME") );
121 #       foreach my $mime (@mime){
122 #               warn "".$mime;
123 #       }
124         
125         my $CGIextChoice=CGI::scrolling_list(
126                                 -name     => 'MIME',
127                                 -id       => 'MIME',
128                                 -values   => \@mime,
129                                 -size     => 1,
130                                 -multiple => 0 );
131         
132         my @dels = ( C4::Context->preference("delimiter") );
133         my $CGIsepChoice=CGI::scrolling_list(
134                                 -name     => 'sep',
135                                 -id       => 'sep',
136                                 -values   => \@dels,
137                                 -size     => 1,
138                                 -multiple => 0 );
139         #branch
140         my $branches = GetBranches;
141         my @branchloop;
142         foreach my $thisbranch (keys %$branches) {
143 #                       my $selected = 1 if $thisbranch eq $branch;
144                         my %row =(value => $thisbranch,
145 #                                                                       selected => $selected,
146                                                                         branchname => $branches->{$thisbranch}->{'branchname'},
147                                                         );
148                         push @branchloop, \%row;
149         }
150
151         #doctype
152         my $itemtypes = GetItemTypes;
153         my @itemtypeloop;
154         foreach my $thisitemtype (keys %$itemtypes) {
155 #                       my $selected = 1 if $thisbranch eq $branch;
156                         my %row =(value => $thisitemtype,
157 #                                                                       selected => $selected,
158                                                                         description => $itemtypes->{$thisitemtype}->{'description'},
159                                                         );
160                         push @itemtypeloop, \%row;
161         }
162         
163         #borcat
164         my ($codes,$labels) = GetborCatFromCatType(undef,undef);
165         my @borcatloop;
166         foreach my $thisborcat (sort keys %$labels) {
167  #                      my $selected = 1 if $thisbranch eq $branch;
168                         my %row =(value => $thisborcat,
169  #                                                                      selected => $selected,
170                                                                         description => $labels->{$thisborcat},
171                                                         );
172                         push @borcatloop, \%row;
173         }
174         
175         #Day
176         #Month
177         $template->param(
178                                         CGIextChoice => $CGIextChoice,
179                                         CGIsepChoice => $CGIsepChoice,
180                                         branchloop =>\@branchloop,
181                                         itemtypeloop =>\@itemtypeloop,
182                                         borcatloop =>\@borcatloop,
183                                         );
184 output_html_with_http_headers $input, $cookie, $template->output;
185 }
186
187
188
189
190 sub calculate {
191         my ($line, $column, $filters) = @_;
192         my @mainloop;
193         my @loopfooter;
194         my @loopcol;
195         my @loopline;
196         my @looprow;
197         my %globalline;
198         my $grantotal =0;
199 # extract parameters
200         my $dbh = C4::Context->dbh;
201
202 # Filters
203 # Checking filters
204 #
205         my @loopfilter;
206         for (my $i=0;$i<=6;$i++) {
207                 my %cell;
208                 if ( @$filters[$i] ) {
209                         if (($i==1) and (@$filters[$i-1])) {
210                                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
211                         }
212                         $cell{filter} .= @$filters[$i];
213                         $cell{crit} .="Issue From" if ($i==0);
214                         $cell{crit} .="Issue To" if ($i==1);
215                         $cell{crit} .="Return From" if ($i==2);
216                         $cell{crit} .="Return To" if ($i==3);
217                         $cell{crit} .="Branch" if ($i==4);
218                         $cell{crit} .="Doc Type" if ($i==5);
219                         $cell{crit} .="Bor Cat" if ($i==6);
220                         $cell{crit} .="Day" if ($i==7);
221                         $cell{crit} .="Month" if ($i==8);
222                         $cell{crit} .="Year" if ($i==9);
223                         push @loopfilter, \%cell;
224                 }
225         }
226         my $colfield;
227         my $colorder;
228         if ($column){
229                 $column = "issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/));
230                 $column = "biblioitems.".$column if $column=~/itemtype/;
231                 $column = "borrowers.".$column if $column=~/categorycode/;
232                 my @colfilter ;
233                 $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ )  ;
234                 $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ )  ;
235                 $colfilter[0] = @$filters[2] if ($column =~ /returndate/ )  ;
236                 $colfilter[1] = @$filters[3] if ($column =~ /returndate/ )  ;
237                 $colfilter[0] = @$filters[4] if ($column =~ /branch/ )  ;
238                 $colfilter[0] = @$filters[5] if ($column =~ /itemtype/ )  ;
239                 $colfilter[0] = @$filters[6] if ($column =~ /category/ )  ;
240         #       $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
241                 $colfilter[0] = @$filters[7] if ($column =~ /timestamp/ ) ;
242                 $colfilter[0] = @$filters[8] if ($column =~ /timestamp/ ) ;
243                 $colfilter[0] = @$filters[9] if ($column =~ /timestamp/ ) ;
244         #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
245                                                                                                 
246         # loop cols.
247                 if ($column eq "Day") {
248                         #Display by day
249                         $column = "issues.timestamp";
250                         $colfield .="dayname($column)";  
251                         $colorder .="weekday($column)";
252                 } elsif ($column eq "Month") {
253                         #Display by Month
254                         $column = "issues.timestamp";
255                         $colfield .="monthname($column)";  
256                         $colorder .="month($column)";  
257                 } elsif ($column eq "Year") {
258                         #Display by Year
259                         $column = "issues.timestamp";
260                         $colfield .="Year($column)";
261                         $colorder .= $column;
262                 } else {
263                         $colfield .= $column;
264                         $colorder .= $column;
265                 }  
266                 
267                 my $strsth2;
268                 $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";
269                 if (($column=~/timestamp/) or ($column=~/returndate/)){
270                         if ($colfilter[1] and ($colfilter[0])){
271                                 $strsth2 .= " and $column between '$colfilter[0]' and '$colfilter[1]' " ;
272                         } elsif ($colfilter[1]) {
273                                         $strsth2 .= " and $column < '$colfilter[1]' " ;
274                         } elsif ($colfilter[0]) {
275                                 $strsth2 .= " and $column > '$colfilter[0]' " ;
276                         }
277                 } elsif ($colfilter[0]) {
278                         $colfilter[0] =~ s/\*/%/g;
279                         $strsth2 .= " and $column LIKE '$colfilter[0]' " ;
280                 }
281                 $strsth2 .=" group by $colfield";
282                 $strsth2 .=" order by $colorder";
283                 warn "". $strsth2;
284                 
285                 my $sth2 = $dbh->prepare( $strsth2 );
286                 $sth2->execute;
287         
288                 while (my ($celvalue) = $sth2->fetchrow) {
289                         my %cell;
290                         $cell{'coltitle'} = ($celvalue?$celvalue:"NULL");
291                         push @loopcol, \%cell;
292                 }
293         #       warn "fin des titres colonnes";
294         }
295         
296         my $i=0;
297 #       my @totalcol;
298         my $hilighted=-1;
299         
300         #Initialization of cell values.....
301         my @table;
302         
303 #       warn "init table";
304         for (my $i=1;$i<=$line;$i++) {
305                 foreach my $col ( @loopcol ) {
306 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
307                         $table[$i]->{($col->{coltitle})?$col->{coltitle}:"total"}->{'name'}=0;
308                 }
309         }
310
311
312 # preparing calculation
313         my $strcalc ;
314         
315 # Processing average loanperiods
316         $strcalc .= "SELECT  CONCAT(borrowers.surname , \"\\t\",borrowers.firstname),  COUNT(*) AS RANK, borrowers.borrowernumber AS ID";
317         $strcalc .= " , $colfield " if ($colfield);
318         $strcalc .= " 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";
319
320         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
321         $strcalc .= " AND issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
322         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
323         $strcalc .= " AND issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] );
324         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
325         $strcalc .= " AND issues.returndate > '" . @$filters[2] ."'" if ( @$filters[2] );
326         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
327         $strcalc .= " AND issues.returndate < '" . @$filters[3] ."'" if ( @$filters[3] );
328         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
329         $strcalc .= " AND issues.branchcode like '" . @$filters[4] ."'" if ( @$filters[4] );
330         @$filters[5]=~ s/\*/%/g if (@$filters[5]);
331         $strcalc .= " AND biblioitems.itemtype like '" . @$filters[5] ."'" if ( @$filters[5] );
332         @$filters[6]=~ s/\*/%/g if (@$filters[6]);
333         $strcalc .= " AND borrowers.categorycode like '" . @$filters[6] ."'" if ( @$filters[6] );
334         @$filters[7]=~ s/\*/%/g if (@$filters[7]);
335         $strcalc .= " AND dayname(issues.timestamp) like '" . @$filters[7]."'" if (@$filters[7]);
336         @$filters[8]=~ s/\*/%/g if (@$filters[8]);
337         $strcalc .= " AND monthname(issues.timestamp) like '" . @$filters[8]."'" if (@$filters[8]);
338         @$filters[9]=~ s/\*/%/g if (@$filters[9]);
339         $strcalc .= " AND year(issues.timestamp) like '" . @$filters[9] ."'" if ( @$filters[9] );
340         
341         $strcalc .= " group by borrowers.borrowernumber";
342         $strcalc .= ", $colfield" if ($column);
343         $strcalc .= " order by RANK DESC";
344         $strcalc .= ",$colfield " if ($colfield);
345 #       my $max;
346 #       if (@loopcol) {
347 #               $max = $line*@loopcol;
348 #       } else { $max=$line;}
349 #       $strcalc .= " LIMIT 0,$max";
350         warn "SQL :". $strcalc;
351         
352         my $dbcalc = $dbh->prepare($strcalc);
353         $dbcalc->execute;
354 #       warn "filling table";
355         my $previous_col;
356         my %indice;
357         while (my  @data = $dbcalc->fetchrow) {
358                 my ($row, $rank, $id, $col )=@data;
359                 $col = "zzEMPTY" if ($col eq undef);
360                 $indice{$col}=1 if (not($indice{$col}));
361                 $table[$indice{$col}]->{$col}->{'name'}=$row;
362                 $table[$indice{$col}]->{$col}->{'count'}=$rank;
363                 $table[$indice{$col}]->{$col}->{'link'}=$id;
364 #               warn " ".$i." ".$col. " ".$row;
365                 $indice{$col}++;
366         }
367         
368         push @loopcol,{coltitle => "Global"} if not($column);
369         
370         for ($i=1; $i<=$line;$i++) {
371                 my @loopcell;
372                 warn " $i";
373                 #@loborrowersopcol ensures the order for columns is common with column titles
374                 # and the number matches the number of columns
375                 my $colcount=0;
376                 foreach my $col ( @loopcol ) {
377 #                       warn " colonne :$col->{coltitle}";
378                         my $value;
379                         my $count=0;
380                         my $link;
381                         if (@loopcol){
382                                 $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'name'};
383                                 $count =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'count'};
384                                 $link =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'link'};
385                         } else {
386                                 $value =$table[$i]->{"zzEMPTY"}->{'name'};
387                                 $count =$table[$i]->{"zzEMPTY"}->{'count'};
388                                 $link =$table[$i]->{"zzEMPTY"}->{'link'};
389                         }
390 #                       warn " ".$i ." value:$value count:$count reference:$link";
391                         push @loopcell, {value => $value, count =>$count, reference => $link} ;
392                 }
393                 push @looprow,{ 'rowtitle' => $i ,
394                                                 'loopcell' => \@loopcell,
395                                                 'hilighted' => ($hilighted >0),
396                                         };
397                 $hilighted = -$hilighted;
398         }
399 #       
400                         
401
402         # the header of the table
403         $globalline{loopfilter}=\@loopfilter;
404         # the core of the table
405         $globalline{looprow} = \@looprow;
406         $globalline{loopcol} = \@loopcol;
407 #       # the foot (totals by borrower type)
408         $globalline{loopfooter} = \@loopfooter;
409         $globalline{total}= $grantotal;
410         $globalline{line} = $line;
411         $globalline{column} = $column;
412         push @mainloop,\%globalline;
413         return \@mainloop;
414 }
415
416 1;