kohabug 2345: bad comparisons pervade reports
[koha.git] / reports / borrowers_stats.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 use CGI;
22 use C4::Auth;
23 use C4::Context;
24 use C4::Branch; # GetBranches
25 use C4::Koha;
26 use C4::Dates;
27 use C4::Acquisition;
28 use C4::Output;
29 use C4::Circulation;
30 use Date::Calc qw(
31   Today
32   Add_Delta_YM
33   );
34
35 =head1 NAME
36
37 plugin that shows a stats on borrowers
38
39 =head1 DESCRIPTION
40
41 =over 2
42
43 =cut
44
45 my $input = new CGI;
46 my $do_it=$input->param('do_it');
47 my $fullreportname = "reports/borrowers_stats.tmpl";
48 my $line = $input->param("Line");
49 my $column = $input->param("Column");
50 my @filters = $input->param("Filter");
51 my $digits = $input->param("digits");
52 my $period = $input->param("period");
53 my $borstat = $input->param("status");
54 my $borstat1 = $input->param("activity");
55 my $output = $input->param("output");
56 my $basename = $input->param("basename");
57 my $mime = $input->param("MIME");
58 my $del = $input->param("sep");
59 my $selected_branch; # = $input->param("?");
60
61 our $branches = GetBranches;
62
63 my ($template, $borrowernumber, $cookie)
64         = get_template_and_user({template_name => $fullreportname,
65                                 query => $input,
66                                 type => "intranet",
67                                 authnotrequired => 0,
68                                 flagsrequired => {reports=> 1},
69                                 debug => 1,
70                                 });
71 $template->param(do_it => $do_it);
72 if ($do_it) {
73         my $results = calculate($line, $column, $digits, $borstat,$borstat1 ,\@filters);
74         if ($output eq "screen"){
75                 $template->param(mainloop => $results);
76                 output_html_with_http_headers $input, $cookie, $template->output;
77         } else {
78                 print $input->header(-type => 'application/vnd.sun.xml.calc',
79                          -encoding => 'utf-8',
80                              -name => "$basename.csv",
81                        -attachment => "$basename.csv");
82                 my $cols = @$results[0]->{loopcol};
83                 my $lines = @$results[0]->{looprow};
84                 my $sep;
85                 $sep =C4::Context->preference("delimiter");
86                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
87                 foreach my $col ( @$cols ) {
88                         print $col->{coltitle}.$sep;
89                 }
90                 print "Total\n";
91                 foreach my $line ( @$lines ) {
92                         my $x = $line->{loopcell};
93                         print $line->{rowtitle}.$sep;
94                         foreach my $cell (@$x) {
95                                 print $cell->{value}.$sep;
96                         }
97                         print $line->{totalrow};
98                         print "\n";
99                 }
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         }
107         exit(1);        # exit after do_it, regardless
108 } else {
109         my $dbh = C4::Context->dbh;
110         my $req;
111         $template->param(  CAT_LOOP => &catcode_aref);
112         my @branchloop;
113         foreach (sort {$branches->{$a}->{branchname} cmp $branches->{$b}->{branchname}} keys %$branches) {
114                 my $line = {branchcode => $_, branchname => $branches->{$_}->{branchname} || 'UNKNOWN'};
115                 $line->{selected} = 'selected' if ($selected_branch and $selected_branch eq $_);
116                 push @branchloop, $line;
117         }
118         $template->param(BRANCH_LOOP => \@branchloop);
119         $req = $dbh->prepare("SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode");
120         $req->execute;
121         $template->param(   ZIP_LOOP => $req->fetchall_arrayref({}));
122         $req = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' ORDER BY lib");
123         $req->execute;
124         $template->param( SORT1_LOOP => $req->fetchall_arrayref({}));
125         $req = $dbh->prepare("SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort <> '' ORDER BY sort2 LIMIT 200");
126                 # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destory DB performance.
127         $req->execute;
128         $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
129         
130         my @mime = ( C4::Context->preference("MIME") );
131         # warn 'MIME(s): ' . join ' ', @mime;
132         my $CGIextChoice=CGI::scrolling_list(
133                                 -name => 'MIME',
134                                 -id => 'MIME',
135                                 -values   => \@mime,
136                                 -size     => 1,
137                                 -multiple => 0 );
138         my @dels = ( C4::Context->preference("delimiter") );
139         my $CGIsepChoice=CGI::scrolling_list(
140                                 -name => 'sep',
141                                 -id => 'sep',
142                                 -values   => \@dels,
143                                 -size     => 1,
144                                 -multiple => 0 );
145         $template->param(
146                 CGIextChoice => $CGIextChoice,
147                 CGIsepChoice => $CGIsepChoice,
148                 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
149     );
150
151 }
152 output_html_with_http_headers $input, $cookie, $template->output;
153
154 sub catcode_aref() {
155         my $req = C4::Context->dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
156         $req->execute;
157         return $req->fetchall_arrayref({});
158 }
159 sub catcodes_hash() {
160         my %cathash;
161         my $catcodes = &catcode_aref;
162         foreach (@$catcodes) {
163                 $cathash{$_->{categorycode}} = ($_->{description} || 'NO_DESCRIPTION') . " ($_->{categorycode})";
164         }
165         return %cathash;
166 }
167
168 sub calculate {
169         my ($line, $column, $digits, $status, $activity, $filters) = @_;
170         my @mainloop;
171         my @loopfooter;
172         my @loopcol;
173         my @loopline;
174         my @looprow;
175         my %globalline;
176         my $grantotal =0;
177 # extract parameters
178         my $dbh = C4::Context->dbh;
179
180 # Filters
181         my $linefilter = "";
182 #       warn "filtres ".@filters[0];
183 #       warn "filtres ".@filters[4];
184 #       warn "filtres ".@filters[5];
185 #       warn "filtres ".@filters[6];
186
187         $linefilter = @$filters[0] if ($line =~ /categorycode/ )  ;
188         $linefilter = @$filters[1] if ($line =~ /zipcode/ )  ;
189         $linefilter = @$filters[2] if ($line =~ /branchcode/ ) ;
190         $linefilter = @$filters[5] if ($line =~ /sort1/ ) ;
191         $linefilter = @$filters[6] if ($line =~ /sort2/ ) ;
192
193         my $colfilter = "";
194         $colfilter = @$filters[0] if ($column =~ /categorycode/);
195         $colfilter = @$filters[1] if ($column =~ /zipcode/);
196         $colfilter = @$filters[2] if ($column =~ /branchcode/);
197         $colfilter = @$filters[5] if ($column =~ /sort1/);
198         $colfilter = @$filters[6] if ($column =~ /sort2/);
199
200         my @loopfilter;
201         for (my $i=0;$i<=6;$i++) {
202                 my %cell;
203                 if ( @$filters[$i] ) {
204                         $cell{filter} .= @$filters[$i];
205                         $cell{crit} .="Cat Code " if ($i==0);
206                         $cell{crit} .="Zip Code" if ($i==1);
207                         $cell{crit} .="Branchcode" if ($i==2);
208                         $cell{crit} .="Date of Birth" if ($i==3);
209                         $cell{crit} .="Date of Birth" if ($i==4);
210                         $cell{crit} .="Sort1" if ($i==5);
211                         $cell{crit} .="Sort2" if ($i==6);
212                         push @loopfilter, \%cell;
213                 }
214         }
215         ($status  ) and push @loopfilter,{crit=>"Status",  filter=>$status  };
216         ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
217         push @loopfilter,{debug=>1, crit=>"Branches",filter=>join(" ", sort keys %$branches)};
218         push @loopfilter,{debug=>1, crit=>"(line, column)", filter=>"($line,$column)"};
219 # year of activity
220         my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
221         my $newperioddate=$period_year."-".$period_month."-".$period_day;
222 # 1st, loop rows.
223         my $linefield;
224         if (($line =~/zipcode/) and ($digits)) {
225                 $linefield .="left($line,$digits)";
226         } else{
227                 $linefield .= $line;
228         }
229
230         my %cathash = ($line eq 'categorycode' or $column eq 'categorycode') ? &catcodes_hash : ();
231         push @loopfilter, {debug=>1, crit=>"\%cathash", filter=>join(", ", map {$cathash{$_}} sort keys %cathash)};
232
233         my $strsth = "SELECT distinctrow $linefield FROM borrowers WHERE $line IS NOT NULL ";
234         $linefilter =~ s/\*/%/g;
235         if ( $linefilter ) {
236                 $strsth .= " AND $linefield LIKE ? " ;
237         }
238         $strsth .= " AND $status='1' " if ($status);
239         $strsth .=" order by $linefield";
240         
241         push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth};
242         my $sth = $dbh->prepare($strsth);
243         if ( $linefilter ) {
244                 $sth->execute($linefilter);
245         } else {
246                 $sth->execute;
247         }
248         while (my ($celvalue) = $sth->fetchrow) {
249                 my %cell;
250                 if ($celvalue) {
251                         $cell{rowtitle} = $celvalue;
252                         # $cell{rowtitle_display} = ($linefield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
253                         $cell{rowtitle_display} = ($cathash{$celvalue} || "$celvalue\*") if ($line eq 'categorycode');
254                 }
255                 $cell{totalrow} = 0;
256                 push @loopline, \%cell;
257         }
258
259 # 2nd, loop cols.
260         my $colfield;
261         if (($column =~/zipcode/) and ($digits)) {
262                 $colfield = "left($column,$digits)";
263         } else {
264                 $colfield = $column;
265         }
266         my $strsth2 = "select distinctrow $colfield from borrowers where $column is not null";
267         if ($colfilter) {
268                 $colfilter =~ s/\*/%/g;
269                 $strsth2 .= " AND $colfield LIKE ? ";
270         }
271         $strsth2 .= " AND $status='1' " if ($status);
272         $strsth2 .= " order by $colfield";
273         push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth2};
274         my $sth2 = $dbh->prepare($strsth2);
275         if ($colfilter) {
276                 $sth2->execute($colfilter);
277         } else {
278                 $sth2->execute;
279         }
280         while (my ($celvalue) = $sth2->fetchrow) {
281                 my %cell;
282                 if ($celvalue) {
283                         $cell{coltitle} = $celvalue;
284                         # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
285                         $cell{coltitle_display} = $cathash{$celvalue} if ($column eq 'categorycode');
286                 }
287                 push @loopcol, \%cell;
288         }
289
290         my $i=0;
291         #Initialization of cell values.....
292         my %table;
293 #       warn "init table";
294         foreach my $row (@loopline) {
295                 foreach my $col ( @loopcol ) {
296 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
297                         $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
298                 }
299                 $table{$row->{rowtitle}}->{totalrow}=0;
300                 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
301         }
302
303 # preparing calculation
304         my $strcalc .= "SELECT $linefield, $colfield, count( * ) FROM borrowers WHERE 1 ";
305         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
306         $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
307         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
308         $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
309         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
310         $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
311         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
312         $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
313         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
314         $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
315         @$filters[5]=~ s/\*/%/g if (@$filters[5]);
316         $strcalc .= " AND sort1 like '" . @$filters[5] ."'" if ( @$filters[5] );
317         @$filters[6]=~ s/\*/%/g if (@$filters[6]);
318         $strcalc .= " AND sort2 like '" . @$filters[6] ."'" if ( @$filters[6] );
319         $strcalc .= " AND borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
320         $strcalc .= " AND borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'nonactive');
321         $strcalc .= " AND $status='1' " if ($status);
322         $strcalc .= " group by $linefield, $colfield";
323         push @loopfilter, {sql=>1, crit=>"Query", filter=>$strcalc};
324         my $dbcalc = $dbh->prepare($strcalc);
325         $dbcalc->execute;
326         
327         my $emptycol; 
328         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
329 #               warn "filling table $row / $col / $value ";
330                 $emptycol = 1 if (!defined($col));
331                 $col = "zzEMPTY" if (!defined($col));
332                 $row = "zzEMPTY" if (!defined($row));
333                 
334                 $table{$row}->{$col}+=$value;
335                 $table{$row}->{totalrow}+=$value;
336                 $grantotal += $value;
337         }
338         
339         push @loopcol,{coltitle => "NULL"} if ($emptycol);
340         
341         foreach my $row (sort keys %table) {
342                 my @loopcell;
343                 #@loopcol ensures the order for columns is common with column titles
344                 # and the number matches the number of columns
345                 foreach my $col ( @loopcol ) {
346                         my $value =$table{$row}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
347                         push @loopcell, {value => $value};
348                 }
349                 push @looprow,{
350                         'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
351                         'rowtitle_display' => $table{$row}->{rowtitle_display} || $row,
352                         'loopcell' => \@loopcell,
353                         'totalrow' => $table{$row}->{totalrow}
354                 };
355         }
356         
357         foreach my $col ( @loopcol ) {
358                 my $total=0;
359                 foreach my $row ( @looprow ) {
360                         $total += $table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
361 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
362                 }
363 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
364                 push @loopfooter, {'totalcol' => $total};
365         }
366                         
367
368         # the header of the table
369         $globalline{loopfilter}=\@loopfilter;
370         # the core of the table
371         $globalline{looprow} = \@looprow;
372         $globalline{loopcol} = \@loopcol;
373 #       # the foot (totals by borrower type)
374         $globalline{loopfooter} = \@loopfooter;
375         $globalline{total}= $grantotal;
376         $globalline{line} = $line;
377         $globalline{column} = $column;
378         push @mainloop,\%globalline;
379         return \@mainloop;
380 }
381