Bug 3856: Tools Menu in Alpha Order - resubmission.
[koha.git] / reports / borrowers_stats.pl
blob437bd0939ea603f5bff4aa82129d4ced7c237b87
1 #!/usr/bin/perl
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
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.
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.
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
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::Reports;
30 use C4::Circulation;
31 use C4::Dates qw/format_date format_date_in_iso/;
32 use Date::Calc qw(
33 Today
34 Add_Delta_YM
37 =head1 NAME
39 plugin that shows a stats on borrowers
41 =head1 DESCRIPTION
43 =over 2
45 =cut
47 my $input = new CGI;
48 my $do_it=$input->param('do_it');
49 my $fullreportname = "reports/borrowers_stats.tmpl";
50 my $line = $input->param("Line");
51 my $column = $input->param("Column");
52 my @filters = $input->param("Filter");
53 $filters[3]=format_date_in_iso($filters[3]);
54 $filters[4]=format_date_in_iso($filters[4]);
55 my $digits = $input->param("digits");
56 my $period = $input->param("period");
57 my $borstat = $input->param("status");
58 my $borstat1 = $input->param("activity");
59 my $output = $input->param("output");
60 my $basename = $input->param("basename");
61 my $mime = $input->param("MIME");
62 our $sep = $input->param("sep");
63 $sep = "\t" if ($sep eq 'tabulation');
64 my $selected_branch; # = $input->param("?");
66 our $branches = GetBranches;
68 my ($template, $borrowernumber, $cookie)
69 = get_template_and_user({template_name => $fullreportname,
70 query => $input,
71 type => "intranet",
72 authnotrequired => 0,
73 flagsrequired => {reports => '*'},
74 debug => 1,
75 });
76 $template->param(do_it => $do_it);
77 if ($do_it) {
78 my $results = calculate($line, $column, $digits, $borstat,$borstat1 ,\@filters);
79 if ($output eq "screen"){
80 $template->param(mainloop => $results);
81 output_html_with_http_headers $input, $cookie, $template->output;
82 } else {
83 print $input->header(-type => 'application/vnd.sun.xml.calc',
84 -encoding => 'utf-8',
85 -name => "$basename.csv",
86 -attachment => "$basename.csv");
87 my $cols = @$results[0]->{loopcol};
88 my $lines = @$results[0]->{looprow};
89 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
90 foreach my $col ( @$cols ) {
91 print $col->{coltitle}.$sep;
93 print "Total\n";
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;
100 print $line->{totalrow};
101 print "\n";
103 print "TOTAL";
104 $cols = @$results[0]->{loopfooter};
105 foreach my $col ( @$cols ) {
106 print $sep.$col->{totalcol};
108 print $sep.@$results[0]->{total};
110 exit(1); # exit after do_it, regardless
111 } else {
112 my $dbh = C4::Context->dbh;
113 my $req;
114 $template->param( CAT_LOOP => &catcode_aref);
115 my @branchloop;
116 foreach (sort {$branches->{$a}->{branchname} cmp $branches->{$b}->{branchname}} keys %$branches) {
117 my $line = {branchcode => $_, branchname => $branches->{$_}->{branchname} || 'UNKNOWN'};
118 $line->{selected} = 'selected' if ($selected_branch and $selected_branch eq $_);
119 push @branchloop, $line;
121 $template->param(BRANCH_LOOP => \@branchloop);
122 $req = $dbh->prepare("SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode");
123 $req->execute;
124 $template->param( ZIP_LOOP => $req->fetchall_arrayref({}));
125 $req = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' ORDER BY lib");
126 $req->execute;
127 $template->param( SORT1_LOOP => $req->fetchall_arrayref({}));
128 $req = $dbh->prepare("SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort2 <> '' ORDER BY sort2 LIMIT 200");
129 # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destory DB performance.
130 $req->execute;
131 $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
133 my @mime = ( C4::Context->preference("MIME") );
134 # warn 'MIME(s): ' . join ' ', @mime;
135 my $CGIextChoice=CGI::scrolling_list(
136 -name => 'MIME',
137 -id => 'MIME',
138 -values => \@mime,
139 -size => 1,
140 -multiple => 0 );
141 my $CGIsepChoice=GetDelimiterChoices;
142 $template->param(
143 CGIextChoice => $CGIextChoice,
144 CGIsepChoice => $CGIsepChoice,
145 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
149 output_html_with_http_headers $input, $cookie, $template->output;
151 sub catcode_aref() {
152 my $req = C4::Context->dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
153 $req->execute;
154 return $req->fetchall_arrayref({});
156 sub catcodes_hash() {
157 my %cathash;
158 my $catcodes = &catcode_aref;
159 foreach (@$catcodes) {
160 $cathash{$_->{categorycode}} = ($_->{description} || 'NO_DESCRIPTION') . " ($_->{categorycode})";
162 return %cathash;
165 sub calculate {
166 my ($line, $column, $digits, $status, $activity, $filters) = @_;
167 my @mainloop;
168 my @loopfooter;
169 my @loopcol;
170 my @loopline;
171 my @looprow;
172 my %globalline;
173 my $grantotal =0;
174 # extract parameters
175 my $dbh = C4::Context->dbh;
177 # Filters
178 my $linefilter = "";
179 # warn "filtres ".@filters[0];
180 # warn "filtres ".@filters[4];
181 # warn "filtres ".@filters[5];
182 # warn "filtres ".@filters[6];
184 $linefilter = @$filters[0] if ($line =~ /categorycode/ ) ;
185 $linefilter = @$filters[1] if ($line =~ /zipcode/ ) ;
186 $linefilter = @$filters[2] if ($line =~ /branchcode/ ) ;
187 $linefilter = @$filters[5] if ($line =~ /sex/);
188 $linefilter = @$filters[6] if ($line =~ /sort1/ ) ;
189 $linefilter = @$filters[7] if ($line =~ /sort2/ ) ;
191 my $colfilter = "";
192 $colfilter = @$filters[0] if ($column =~ /categorycode/);
193 $colfilter = @$filters[1] if ($column =~ /zipcode/);
194 $colfilter = @$filters[2] if ($column =~ /branchcode/);
195 $colfilter = @$filters[5] if ($column =~ /sex/);
196 $colfilter = @$filters[6] if ($column =~ /sort1/);
197 $colfilter = @$filters[7] if ($column =~ /sort2/);
199 my @loopfilter;
200 for (my $i=0;$i<=7;$i++) {
201 my %cell;
202 if ( @$filters[$i] ) {
203 if($i == 3 or $i == 4){
204 $cell{filter} .= format_date(@$filters[$i]);
205 }else{
206 $cell{filter} .= @$filters[$i];
209 $cell{crit} .="Cat Code " if ($i==0);
210 $cell{crit} .="Zip Code" if ($i==1);
211 $cell{crit} .="Branchcode" if ($i==2);
212 $cell{crit} .="Date of Birth" if ($i==3);
213 $cell{crit} .="Date of Birth" if ($i==4);
214 $cell{crit} .="Sex" if ($i==5);
215 $cell{crit} .="Sort1" if ($i==6);
216 $cell{crit} .="Sort2" if ($i==7);
217 push @loopfilter, \%cell;
220 ($status ) and push @loopfilter,{crit=>"Status", filter=>$status };
221 ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
222 push @loopfilter,{debug=>1, crit=>"Branches",filter=>join(" ", sort keys %$branches)};
223 push @loopfilter,{debug=>1, crit=>"(line, column)", filter=>"($line,$column)"};
224 # year of activity
225 my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
226 my $newperioddate=$period_year."-".$period_month."-".$period_day;
227 # 1st, loop rows.
228 my $linefield;
229 if (($line =~/zipcode/) and ($digits)) {
230 $linefield .="left($line,$digits)";
231 } else{
232 $linefield .= $line;
235 my %cathash = ($line eq 'categorycode' or $column eq 'categorycode') ? &catcodes_hash : ();
236 push @loopfilter, {debug=>1, crit=>"\%cathash", filter=>join(", ", map {$cathash{$_}} sort keys %cathash)};
238 my $strsth = "SELECT distinctrow $linefield FROM borrowers WHERE $line IS NOT NULL ";
239 $linefilter =~ s/\*/%/g;
240 if ( $linefilter ) {
241 $strsth .= " AND $linefield LIKE ? " ;
243 $strsth .= " AND $status='1' " if ($status);
244 $strsth .=" order by $linefield";
246 push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth};
247 my $sth = $dbh->prepare($strsth);
248 if ( $linefilter ) {
249 $sth->execute($linefilter);
250 } else {
251 $sth->execute;
253 while (my ($celvalue) = $sth->fetchrow) {
254 my %cell;
255 if ($celvalue) {
256 $cell{rowtitle} = $celvalue;
257 # $cell{rowtitle_display} = ($linefield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
258 $cell{rowtitle_display} = ($cathash{$celvalue} || "$celvalue\*") if ($line eq 'categorycode');
260 $cell{totalrow} = 0;
261 push @loopline, \%cell;
264 # 2nd, loop cols.
265 my $colfield;
266 if (($column =~/zipcode/) and ($digits)) {
267 $colfield = "left($column,$digits)";
268 } else {
269 $colfield = $column;
271 my $strsth2 = "select distinctrow $colfield from borrowers where $column is not null";
272 if ($colfilter) {
273 $colfilter =~ s/\*/%/g;
274 $strsth2 .= " AND $colfield LIKE ? ";
276 $strsth2 .= " AND $status='1' " if ($status);
277 $strsth2 .= " order by $colfield";
278 push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth2};
279 my $sth2 = $dbh->prepare($strsth2);
280 if ($colfilter) {
281 $sth2->execute($colfilter);
282 } else {
283 $sth2->execute;
285 while (my ($celvalue) = $sth2->fetchrow) {
286 my %cell;
287 if ($celvalue) {
288 $cell{coltitle} = $celvalue;
289 # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
290 $cell{coltitle_display} = $cathash{$celvalue} if ($column eq 'categorycode');
292 push @loopcol, \%cell;
295 my $i=0;
296 #Initialization of cell values.....
297 my %table;
298 # warn "init table";
299 foreach my $row (@loopline) {
300 foreach my $col ( @loopcol ) {
301 # warn " init table : $row->{rowtitle} / $col->{coltitle} ";
302 $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
304 $table{$row->{rowtitle}}->{totalrow}=0;
305 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
308 # preparing calculation
309 my $strcalc .= "SELECT $linefield, $colfield, count( * ) FROM borrowers WHERE 1 ";
310 @$filters[0]=~ s/\*/%/g if (@$filters[0]);
311 $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
312 @$filters[1]=~ s/\*/%/g if (@$filters[1]);
313 $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
314 @$filters[2]=~ s/\*/%/g if (@$filters[2]);
315 $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
316 @$filters[3]=~ s/\*/%/g if (@$filters[3]);
317 $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
318 @$filters[4]=~ s/\*/%/g if (@$filters[4]);
319 $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
320 @$filters[5]=~ s/\*/%/g if (@$filters[5]);
321 $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] );
322 @$filters[6]=~ s/\*/%/g if (@$filters[6]);
323 $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
324 @$filters[7]=~ s/\*/%/g if (@$filters[7]);
325 $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
326 $strcalc .= " AND borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
327 $strcalc .= " AND borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'nonactive');
328 $strcalc .= " AND $status='1' " if ($status);
329 $strcalc .= " group by $linefield, $colfield";
330 push @loopfilter, {sql=>1, crit=>"Query", filter=>$strcalc};
331 my $dbcalc = $dbh->prepare($strcalc);
332 $dbcalc->execute;
334 my $emptycol;
335 while (my ($row, $col, $value) = $dbcalc->fetchrow) {
336 # warn "filling table $row / $col / $value ";
337 $emptycol = 1 if (!defined($col));
338 $col = "zzEMPTY" if (!defined($col));
339 $row = "zzEMPTY" if (!defined($row));
341 $table{$row}->{$col}+=$value;
342 $table{$row}->{totalrow}+=$value;
343 $grantotal += $value;
346 push @loopcol,{coltitle => "NULL"} if ($emptycol);
348 foreach my $row (sort keys %table) {
349 my @loopcell;
350 #@loopcol ensures the order for columns is common with column titles
351 # and the number matches the number of columns
352 foreach my $col ( @loopcol ) {
353 my $value =$table{$row}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
354 push @loopcell, {value => $value};
356 push @looprow,{
357 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
358 'rowtitle_display' => $table{$row}->{rowtitle_display} || $row,
359 'loopcell' => \@loopcell,
360 'totalrow' => $table{$row}->{totalrow}
364 foreach my $col ( @loopcol ) {
365 my $total=0;
366 foreach my $row ( @looprow ) {
367 $total += $table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
368 # warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
370 # warn "summ for column ".$col->{coltitle}." = ".$total;
371 push @loopfooter, {'totalcol' => $total};
375 # the header of the table
376 $globalline{loopfilter}=\@loopfilter;
377 # the core of the table
378 $globalline{looprow} = \@looprow;
379 $globalline{loopcol} = \@loopcol;
380 # # the foot (totals by borrower type)
381 $globalline{loopfooter} = \@loopfooter;
382 $globalline{total}= $grantotal;
383 $globalline{line} = $line;
384 $globalline{column} = $column;
385 push @mainloop,\%globalline;
386 return \@mainloop;