serials-home.tmpl
[koha.git] / reports / borrowers_stats.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::Context;
26 use C4::Branch; # GetBranches
27 use C4::Koha;
28 use C4::Acquisition;
29 use C4::Output;
30 use C4::Circulation;
31 use C4::Input;
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/borrowers_stats.tmpl";
47 my $line = $input->param("Line");
48 my $column = $input->param("Column");
49 my @filters = $input->param("Filter");
50 my $digits = $input->param("digits");
51 my $borstat = $input->param("status");
52 my $output = $input->param("output");
53 my $basename = $input->param("basename");
54 my $mime = $input->param("MIME");
55 my $del = $input->param("sep");
56
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=> 1},
63                                 debug => 1,
64                                 });
65 $template->param(do_it => $do_it);
66 if ($do_it) {
67         my $results = calculate($line, $column, $digits, $borstat, \@filters);
68         if ($output eq "screen"){
69                 $template->param(mainloop => $results);
70                 output_html_with_http_headers $input, $cookie, $template->output;
71                 exit(1);
72         } else {
73                 print $input->header(-type => 'application/vnd.sun.xml.calc',
74                                      -encoding    => 'utf-8',
75                                      -name=>"$basename.csv",
76                                      -attachment=>"$basename.csv");
77                 my $cols = @$results[0]->{loopcol};
78                 my $lines = @$results[0]->{looprow};
79                 my $sep;
80                 $sep =C4::Context->preference("delimiter");
81                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
82                 foreach my $col ( @$cols ) {
83                         print $col->{coltitle}.$sep;
84                 }
85                 print "Total\n";
86                 foreach my $line ( @$lines ) {
87                         my $x = $line->{loopcell};
88                         print $line->{rowtitle}.$sep;
89                         foreach my $cell (@$x) {
90                                 print $cell->{value}.$sep;
91                         }
92                         print $line->{totalrow};
93                         print "\n";
94                 }
95                 print "TOTAL";
96                 $cols = @$results[0]->{loopfooter};
97                 foreach my $col ( @$cols ) {
98                         print $sep.$col->{totalcol};
99                 }
100                 print $sep.@$results[0]->{total};
101                 exit(1);
102         }
103 } else {
104         my $dbh = C4::Context->dbh;
105         my @values;
106         my %labels;
107         my $req;
108         $req = $dbh->prepare( "select categorycode, description from categories order by description");
109         $req->execute;
110         my %select_catcode;
111         my @select_catcode;
112         push @select_catcode,"";
113         $select_catcode{""} ="";
114         while (my ($catcode, $description) =$req->fetchrow) {
115                 push @select_catcode, $catcode;
116                 $select_catcode{$catcode} = $description;
117         }
118         my $CGICatCode=CGI::scrolling_list( -name     => 'Filter',
119                                 -id => 'Filter',
120                                 -values   => \@select_catcode,
121                                 -labels   => \%select_catcode,
122                                 -size     => 1,
123                                 -multiple => 0 );
124
125         
126 my $branches = GetBranches;
127 my @branchloop;
128 foreach my $thisbranch (keys %$branches) {
129    # my $selected = 1 if $thisbranch eq $branch;
130     my %row =(value => $thisbranch,
131 #                selected => $selected,
132                 branchname => $branches->{$thisbranch}->{'branchname'},
133             );
134     push @branchloop, \%row;
135 }
136         $req = $dbh->prepare( "select distinctrow zipcode from borrowers order by zipcode");
137         $req->execute;
138         my @select_zipcode;
139         push @select_zipcode,"";
140         while (my ($value) =$req->fetchrow) {
141                 if ($value) {
142                         push @select_zipcode, $value;
143                 }
144         }
145
146         my $CGIZipCode=CGI::scrolling_list( -name     => 'Filter',
147                                 -id => 'Filter',
148                                 -values   => \@select_zipcode,
149                                 -size     => 1,
150                                 -multiple => 0 );
151
152         $req = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' order by lib");
153         $req->execute;
154         my @select_sort1;
155         my %select_sort1;
156         push @select_sort1,"";
157         $select_sort1{""}="";
158         my $hassort1;
159         while (my ($auth_value,$lib) =$req->fetchrow) {
160                 if ($auth_value) {
161                         $hassort1=1;
162                         push @select_sort1, $auth_value;
163                         $select_sort1{$auth_value}=$lib
164                 }
165         }
166
167         my $CGIsort1=CGI::scrolling_list( -name     => 'Filter',
168                                 -id => 'Filter',
169                                 -values   => \@select_sort1,
170                                 -labels =>\%select_sort1,
171                                 -size     => 1,
172                                 -multiple => 0 );
173         
174         $req = $dbh->prepare( "select distinctrow sort2 from borrowers order by sort2");
175         $req->execute;
176         my @select_sort2;
177         push @select_sort2,"";
178         my $hassort2;
179         while (my ($value) =$req->fetchrow) {
180                 if ($value) {
181                         $hassort2 = 1;
182                         push @select_sort2, $value;
183                 }
184         }
185         my $CGIsort2=CGI::scrolling_list( -name     => 'Filter',
186                                 -id => 'Filter',
187                                 -values   => \@select_sort2,
188                                 -size     => 1,
189                                 -multiple => 0 );
190         
191         my @mime = ( C4::Context->preference("MIME") );
192         foreach my $mime (@mime){
193                 warn "".$mime;
194         }
195         
196         my $CGIextChoice=CGI::scrolling_list(
197                                 -name => 'MIME',
198                                 -id => 'MIME',
199                                 -values   => \@mime,
200                                 -size     => 1,
201                                 -multiple => 0 );
202         
203         my @dels = ( C4::Context->preference("delimiter") );
204         my $CGIsepChoice=CGI::scrolling_list(
205                                 -name => 'sep',
206                                 -id => 'sep',
207                                 -values   => \@dels,
208                                 -size     => 1,
209                                 -multiple => 0 );
210
211         $template->param(               CGICatCode => $CGICatCode,
212                                         CGIZipCode => $CGIZipCode,
213                                         CGISort1 => $CGIsort1,
214                                         hassort1 => $hassort1,
215                                         CGISort2 => $CGIsort2,
216                                         hassort2 => $hassort2,
217                                         CGIextChoice => $CGIextChoice,
218                                         CGIsepChoice => $CGIsepChoice,
219                                         CGIBranch => @branchloop
220                                         );
221
222 }
223 output_html_with_http_headers $input, $cookie, $template->output;
224
225
226
227 sub calculate {
228         my ($line, $column, $digits, $status, $filters) = @_;
229         my @mainloop;
230         my @loopfooter;
231         my @loopcol;
232         my @loopline;
233         my @looprow;
234         my %globalline;
235         my $grantotal =0;
236 # extract parameters
237         my $dbh = C4::Context->dbh;
238
239 # Filters
240         my $linefilter = "";
241 #       warn "filtres ".@filters[0];
242 #       warn "filtres ".@filters[1];
243 #       warn "filtres ".@filters[2];
244 #       warn "filtres ".@filters[3];
245         
246         $linefilter = @$filters[0] if ($line =~ /categorycode/ )  ;
247         $linefilter = @$filters[1] if ($line =~ /zipcode/ )  ;
248         $linefilter = @$filters[2] if ($line =~ /branccode/ ) ;
249         $linefilter = @$filters[3] if ($line =~ /sort1/ ) ;
250         $linefilter = @$filters[4] if ($line =~ /sort2/ ) ;
251
252         my $colfilter = "";
253         $colfilter = @$filters[0] if ($column =~ /categorycode/);
254         $colfilter = @$filters[1] if ($column =~ /zipcode/);
255         $colfilter = @$filters[2] if ($column =~ /branchcode/);
256         $colfilter = @$filters[3] if ($column =~ /sort1/);
257         $colfilter = @$filters[4] if ($column =~ /sort2/);
258
259         my @loopfilter;
260         for (my $i=0;$i<=3;$i++) {
261                 my %cell;
262                 if ( @$filters[$i] ) {
263                         $cell{filter} .= @$filters[$i];
264                         $cell{crit} .="Cat Code " if ($i==0);
265                         $cell{crit} .="Zip Code" if ($i==1);
266                         $cell{crit} .="Branchcode" if ($i==2);
267                         $cell{crit} .="Sort1" if ($i==3);
268                         $cell{crit} .="Sort2" if ($i==4);
269                         push @loopfilter, \%cell;
270                 }
271         }
272         if ($status) {
273                 push @loopfilter,{crit=>"Status",filter=>$status}
274         }
275 # 1st, loop rows.
276         my $linefield;
277         if (($line =~/zipcode/) and ($digits)) {
278                 $linefield .="left($line,$digits)";
279         } else{
280                 $linefield .= $line;
281         }
282         
283         my $strsth;
284         $strsth .= "select distinctrow $linefield from borrowers where $line is not null ";
285         $linefilter =~ s/\*/%/g;
286         if ( $linefilter ) {
287                 $strsth .= " and $linefield LIKE ? " ;
288         }
289         $strsth .= " and $status='1' " if ($status);
290         $strsth .=" order by $linefield";
291 #       warn "". $strsth;
292         
293         my $sth = $dbh->prepare( $strsth );
294         if ( $linefilter ) {
295                 $sth->execute($linefilter);
296         } else {
297                 $sth->execute;
298         }
299         while ( my ($celvalue) = $sth->fetchrow) {
300                 my %cell;
301                 if ($celvalue) {
302                         $cell{rowtitle} = $celvalue;
303 #               } else {
304 #                       $cell{rowtitle} = "";
305                 }
306                 $cell{totalrow} = 0;
307                 push @loopline, \%cell;
308         }
309
310 # 2nd, loop cols.
311         my $colfield;
312         if (($column =~/zipcode/) and ($digits)) {
313                 $colfield .= "left($column,$digits)";
314         } else{
315                 $colfield .= $column;
316         }
317         my $strsth2;
318         $colfilter =~ s/\*/%/g;
319         $strsth2 .= "select distinctrow $colfield from borrowers where $column is not null";
320         if ( $colfilter ) {
321                 $strsth2 .= " and $colfield LIKE ? ";
322         }
323         $strsth2 .= " and $status='1' " if ($status);
324         $strsth2 .= " order by $colfield";
325 #       warn "". $strsth2;
326         my $sth2 = $dbh->prepare( $strsth2 );
327         if ($colfilter) {
328                 $sth2->execute($colfilter);
329         } else {
330                 $sth2->execute;
331         }
332         while (my ($celvalue) = $sth2->fetchrow) {
333                 my %cell;
334                 my %ft;
335                 if ($celvalue) {
336                         $cell{coltitle} = $celvalue;
337                 }
338                 push @loopcol, \%cell;
339         }
340         
341
342         my $i=0;
343         my @totalcol;
344         my $hilighted=-1;
345         
346         #Initialization of cell values.....
347         my %table;
348 #       warn "init table";
349         foreach my $row ( @loopline ) {
350                 foreach my $col ( @loopcol ) {
351 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
352                         $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
353                 }
354                 $table{$row->{rowtitle}}->{totalrow}=0;
355         }
356
357 # preparing calculation
358         my $strcalc .= "SELECT $linefield, $colfield, count( * ) FROM borrowers WHERE 1 ";
359         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
360         $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
361         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
362         $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
363         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
364         $strcalc .= " AND sort1 like '" . @$filters[2] ."'" if ( @$filters[2] );
365         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
366         $strcalc .= " AND sort2 like '" . @$filters[3] ."'" if ( @$filters[3] );
367         $strcalc .= " AND $status='1' " if ($status);
368         $strcalc .= " group by $linefield, $colfield";
369 #       warn "". $strcalc;
370         my $dbcalc = $dbh->prepare($strcalc);
371         $dbcalc->execute;
372 #       warn "filling table";
373         
374         my $emptycol; 
375         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
376 #               warn "filling table $row / $col / $value ";
377                 $emptycol = 1 if ($col eq undef);
378                 $col = "zzEMPTY" if ($col eq undef);
379                 $row = "zzEMPTY" if ($row eq undef);
380                 
381                 $table{$row}->{$col}+=$value;
382                 $table{$row}->{totalrow}+=$value;
383                 $grantotal += $value;
384         }
385         
386         push @loopcol,{coltitle => "NULL"} if ($emptycol);
387         
388         foreach my $row ( sort keys %table ) {
389                 my @loopcell;
390                 #@loopcol ensures the order for columns is common with column titles
391                 # and the number matches the number of columns
392                 foreach my $col ( @loopcol ) {
393                         my $value =$table{$row}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
394                         push @loopcell, {value => $value  } ;
395                 }
396                 push @looprow,{ 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
397                                                 'loopcell' => \@loopcell,
398                                                 'hilighted' => ($hilighted >0),
399                                                 'totalrow' => $table{$row}->{totalrow}
400                                         };
401                 $hilighted = -$hilighted;
402         }
403         
404         foreach my $col ( @loopcol ) {
405                 my $total=0;
406                 foreach my $row ( @looprow ) {
407                         $total += $table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
408 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
409                 }
410 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
411                 push @loopfooter, {'totalcol' => $total};
412         }
413                         
414
415         # the header of the table
416         $globalline{loopfilter}=\@loopfilter;
417         # the core of the table
418         $globalline{looprow} = \@looprow;
419         $globalline{loopcol} = \@loopcol;
420 #       # the foot (totals by borrower type)
421         $globalline{loopfooter} = \@loopfooter;
422         $globalline{total}= $grantotal;
423         $globalline{line} = $line;
424         $globalline{column} = $column;
425         push @mainloop,\%globalline;
426         return \@mainloop;
427 }
428