Merge branch 'bug_9108' into 3.12-master
[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 our $sep     = $input->param("sep");
63 $sep = "\t" if ($sep eq 'tabulation');
64 my $selected_branch; # = $input->param("?");
65
66 our $branches = GetBranches;
67
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;
92                 }
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;
99                         }
100                         print $line->{totalrow};
101                         print "\n";
102                 }
103                 print "TOTAL";
104                 $cols = @$results[0]->{loopfooter};
105                 foreach my $col ( @$cols ) {
106                         print $sep.$col->{totalcol};
107                 }
108                 print $sep.@$results[0]->{total};
109         }
110         exit;   # 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;
120         }
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({}));
132         
133         my $CGIextChoice=CGI::scrolling_list(
134                                 -name => 'MIME',
135                                 -id => 'MIME',
136                                 -values   => ['CSV'], # FIXME translation
137                                 -size     => 1,
138                                 -multiple => 0 );
139         my $CGIsepChoice=GetDelimiterChoices;
140         $template->param(
141                 CGIextChoice => $CGIextChoice,
142                 CGIsepChoice => $CGIsepChoice,
143     );
144
145 }
146 output_html_with_http_headers $input, $cookie, $template->output;
147
148 sub catcode_aref() {
149         my $req = C4::Context->dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
150         $req->execute;
151         return $req->fetchall_arrayref({});
152 }
153 sub catcodes_hash() {
154         my %cathash;
155         my $catcodes = &catcode_aref;
156         foreach (@$catcodes) {
157                 $cathash{$_->{categorycode}} = ($_->{description} || 'NO_DESCRIPTION') . " ($_->{categorycode})";
158         }
159         return %cathash;
160 }
161
162 sub calculate {
163         my ($line, $column, $digits, $status, $activity, $filters) = @_;
164         my @mainloop;
165         my @loopfooter;
166         my @loopcol;
167         my @loopline;
168         my @looprow;
169         my %globalline;
170         my $grantotal =0;
171 # extract parameters
172         my $dbh = C4::Context->dbh;
173
174 # Filters
175         my $linefilter = "";
176 #       warn "filtres ".@filters[0];
177 #       warn "filtres ".@filters[4];
178 #       warn "filtres ".@filters[5];
179 #       warn "filtres ".@filters[6];
180
181         $linefilter = @$filters[0] if ($line =~ /categorycode/ )  ;
182         $linefilter = @$filters[1] if ($line =~ /zipcode/ )  ;
183         $linefilter = @$filters[2] if ($line =~ /branchcode/ ) ;
184         $linefilter = @$filters[5] if ($line =~ /sex/);
185         $linefilter = @$filters[6] if ($line =~ /sort1/ ) ;
186     $linefilter = @$filters[7] if ($line =~ /sort2/ ) ;
187
188         my $colfilter = "";
189         $colfilter = @$filters[0] if ($column =~ /categorycode/);
190         $colfilter = @$filters[1] if ($column =~ /zipcode/);
191         $colfilter = @$filters[2] if ($column =~ /branchcode/);
192     $colfilter = @$filters[5] if ($column =~ /sex/);
193     $colfilter = @$filters[6] if ($column =~ /sort1/);
194         $colfilter = @$filters[7] if ($column =~ /sort2/);
195
196         my @loopfilter;
197         for (my $i=0;$i<=7;$i++) {
198                 my %cell;
199                 if ( @$filters[$i] ) {
200                     if($i == 3 or $i == 4){
201                         $cell{filter} .= format_date(@$filters[$i]);
202                     }else{
203                         $cell{filter} .= @$filters[$i];
204                     }
205                         
206                         $cell{crit} .="Cat Code " if ($i==0);
207                         $cell{crit} .="Zip Code" if ($i==1);
208                         $cell{crit} .="Branchcode" if ($i==2);
209                         $cell{crit} .="Date of Birth" if ($i==3);
210                         $cell{crit} .="Date of Birth" if ($i==4);
211             $cell{crit} .="Sex" if ($i==5);
212                         $cell{crit} .="Sort1" if ($i==6);
213                         $cell{crit} .="Sort2" if ($i==7);
214                         push @loopfilter, \%cell;
215                 }
216         }
217         ($status  ) and push @loopfilter,{crit=>"Status",  filter=>$status  };
218         ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
219         push @loopfilter,{debug=>1, crit=>"Branches",filter=>join(" ", sort keys %$branches)};
220         push @loopfilter,{debug=>1, crit=>"(line, column)", filter=>"($line,$column)"};
221 # year of activity
222         my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
223         my $newperioddate=$period_year."-".$period_month."-".$period_day;
224 # 1st, loop rows.
225         my $linefield;
226         if (($line =~/zipcode/) and ($digits)) {
227                 $linefield .="left($line,$digits)";
228         } else{
229                 $linefield .= $line;
230         }
231
232         my %cathash = ($line eq 'categorycode' or $column eq 'categorycode') ? &catcodes_hash : ();
233         push @loopfilter, {debug=>1, crit=>"\%cathash", filter=>join(", ", map {$cathash{$_}} sort keys %cathash)};
234
235         my $strsth = "SELECT distinctrow $linefield FROM borrowers WHERE $line IS NOT NULL ";
236         $linefilter =~ s/\*/%/g;
237         if ( $linefilter ) {
238                 $strsth .= " AND $linefield LIKE ? " ;
239         }
240         $strsth .= " AND $status='1' " if ($status);
241         $strsth .=" order by $linefield";
242         
243         push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth};
244         my $sth = $dbh->prepare($strsth);
245         if ( $linefilter ) {
246                 $sth->execute($linefilter);
247         } else {
248                 $sth->execute;
249         }
250         while (my ($celvalue) = $sth->fetchrow) {
251                 my %cell;
252                 if ($celvalue) {
253                         $cell{rowtitle} = $celvalue;
254                         # $cell{rowtitle_display} = ($linefield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
255                         $cell{rowtitle_display} = ($cathash{$celvalue} || "$celvalue\*") if ($line eq 'categorycode');
256                 }
257                 $cell{totalrow} = 0;
258                 push @loopline, \%cell;
259         }
260
261 # 2nd, loop cols.
262         my $colfield;
263         if (($column =~/zipcode/) and ($digits)) {
264                 $colfield = "left($column,$digits)";
265         } else {
266                 $colfield = $column;
267         }
268         my $strsth2 = "select distinctrow $colfield from borrowers where $column is not null";
269         if ($colfilter) {
270                 $colfilter =~ s/\*/%/g;
271                 $strsth2 .= " AND $colfield LIKE ? ";
272         }
273         $strsth2 .= " AND $status='1' " if ($status);
274         $strsth2 .= " order by $colfield";
275         push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth2};
276         my $sth2 = $dbh->prepare($strsth2);
277         if ($colfilter) {
278                 $sth2->execute($colfilter);
279         } else {
280                 $sth2->execute;
281         }
282         while (my ($celvalue) = $sth2->fetchrow) {
283                 my %cell;
284                 if ($celvalue) {
285                         $cell{coltitle} = $celvalue;
286                         # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
287                         $cell{coltitle_display} = $cathash{$celvalue} if ($column eq 'categorycode');
288                 }
289                 push @loopcol, \%cell;
290         }
291
292         my $i=0;
293         #Initialization of cell values.....
294         my %table;
295 #       warn "init table";
296         foreach my $row (@loopline) {
297                 foreach my $col ( @loopcol ) {
298 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
299                         $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
300                 }
301                 $table{$row->{rowtitle}}->{totalrow}=0;
302                 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
303         }
304
305 # preparing calculation
306         my $strcalc .= "SELECT $linefield, $colfield, count( * ) FROM borrowers WHERE 1 ";
307         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
308         $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
309         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
310         $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
311         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
312         $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
313         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
314         $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
315         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
316         $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
317     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
318     $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] );
319     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
320         $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
321         @$filters[7]=~ s/\*/%/g if (@$filters[7]);
322         $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
323         $strcalc .= " AND borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
324         $strcalc .= " AND borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'nonactive');
325         $strcalc .= " AND $status='1' " if ($status);
326         $strcalc .= " group by $linefield, $colfield";
327         push @loopfilter, {sql=>1, crit=>"Query", filter=>$strcalc};
328         my $dbcalc = $dbh->prepare($strcalc);
329         $dbcalc->execute;
330         
331         my $emptycol; 
332         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
333 #               warn "filling table $row / $col / $value ";
334                 $emptycol = 1 if (!defined($col));
335                 $col = "zzEMPTY" if (!defined($col));
336                 $row = "zzEMPTY" if (!defined($row));
337                 
338                 $table{$row}->{$col}+=$value;
339                 $table{$row}->{totalrow}+=$value;
340                 $grantotal += $value;
341         }
342         
343         push @loopcol,{coltitle => "NULL"} if ($emptycol);
344         
345         foreach my $row (sort keys %table) {
346                 my @loopcell;
347                 #@loopcol ensures the order for columns is common with column titles
348                 # and the number matches the number of columns
349                 foreach my $col ( @loopcol ) {
350                         my $value =$table{$row}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
351                         push @loopcell, {value => $value};
352                 }
353                 push @looprow,{
354                         'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
355                         'rowtitle_display' => $table{$row}->{rowtitle_display} || $row,
356                         'loopcell' => \@loopcell,
357                         'totalrow' => $table{$row}->{totalrow}
358                 };
359         }
360         
361         foreach my $col ( @loopcol ) {
362                 my $total=0;
363                 foreach my $row ( @looprow ) {
364                         $total += $table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
365 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
366                 }
367 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
368                 push @loopfooter, {'totalcol' => $total};
369         }
370                         
371
372         # the header of the table
373         $globalline{loopfilter}=\@loopfilter;
374         # the core of the table
375         $globalline{looprow} = \@looprow;
376         $globalline{loopcol} = \@loopcol;
377 #       # the foot (totals by borrower type)
378         $globalline{loopfooter} = \@loopfooter;
379         $globalline{total}= $grantotal;
380         $globalline{line} = $line;
381         $globalline{column} = $column;
382         push @mainloop,\%globalline;
383         return \@mainloop;
384 }
385