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