Bug 23389: Add 'All' option to report dropdowns
[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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21 use CGI qw ( -utf8 );
22 use List::MoreUtils qw/uniq/;
23
24 use C4::Auth;
25 use C4::Context;
26 use C4::Koha;
27 use C4::Acquisition;
28 use C4::Output;
29 use C4::Reports;
30 use C4::Circulation;
31 use C4::Members::AttributeTypes;
32
33 use Koha::AuthorisedValues;
34 use Koha::DateUtils;
35 use Koha::Libraries;
36 use Koha::Patron::Categories;
37
38 use Date::Calc qw(
39   Today
40   Add_Delta_YM
41   );
42
43 =head1 NAME
44
45 plugin that shows a stats on borrowers
46
47 =head1 DESCRIPTION
48
49 =cut
50
51 my $input = new CGI;
52 my $do_it=$input->param('do_it');
53 my $fullreportname = "reports/borrowers_stats.tt";
54 my $line = $input->param("Line");
55 my $column = $input->param("Column");
56 my @filters = $input->multi_param("Filter");
57 $filters[3] = eval { output_pref( { dt => dt_from_string( $filters[3]), dateonly => 1, dateformat => 'iso' } ); }
58     if ( $filters[3] );
59 $filters[4] = eval { output_pref ({ dt => dt_from_string( $filters[4]), dateonly => 1, dateformat => 'iso' } ); }
60     if ( $filters[4] );
61 my $digits = $input->param("digits");
62 our $period = $input->param("period");
63 my $borstat = $input->param("status");
64 my $borstat1 = $input->param("activity");
65 my $output = $input->param("output");
66 my $basename = $input->param("basename");
67 our $sep     = $input->param("sep");
68 $sep = "\t" if ($sep and $sep eq 'tabulation');
69
70 my ($template, $borrowernumber, $cookie)
71         = get_template_and_user({template_name => $fullreportname,
72                                 query => $input,
73                                 type => "intranet",
74                                 authnotrequired => 0,
75                                 flagsrequired => {reports => '*'},
76                                 debug => 1,
77                                 });
78 $template->param(do_it => $do_it);
79 if ($do_it) {
80         my $attributes;
81         if (C4::Context->preference('ExtendedPatronAttributes')) {
82             $attributes = parse_extended_patron_attributes($input);
83         }
84         my $results = calculate($line, $column, $digits, $borstat,$borstat1 ,\@filters, $attributes);
85         if ($output eq "screen"){
86                 $template->param(mainloop => $results);
87                 output_html_with_http_headers $input, $cookie, $template->output;
88         } else {
89                 print $input->header(-type => 'application/vnd.sun.xml.calc',
90                          -encoding => 'utf-8',
91                              -name => "$basename.csv",
92                        -attachment => "$basename.csv");
93                 my $cols = @$results[0]->{loopcol};
94                 my $lines = @$results[0]->{looprow};
95                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
96                 foreach my $col ( @$cols ) {
97                         print $col->{coltitle}.$sep;
98                 }
99                 print "Total\n";
100                 foreach my $line ( @$lines ) {
101                         my $x = $line->{loopcell};
102                         print $line->{rowtitle}.$sep;
103                         foreach my $cell (@$x) {
104                                 print $cell->{value}.$sep;
105                         }
106                         print $line->{totalrow};
107                         print "\n";
108                 }
109                 print "TOTAL";
110                 $cols = @$results[0]->{loopfooter};
111                 foreach my $col ( @$cols ) {
112                         print $sep.$col->{totalcol};
113                 }
114                 print $sep.@$results[0]->{total};
115         }
116         exit;   # exit after do_it, regardless
117 } else {
118         my $dbh = C4::Context->dbh;
119         my $req;
120     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']});
121     $template->param( patron_categories => $patron_categories );
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 destroy DB performance.
130         $req->execute;
131         $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
132         
133     my $CGIextChoice = ( 'CSV' ); # FIXME translation
134         my $CGIsepChoice=GetDelimiterChoices;
135         $template->param(
136                 CGIextChoice => $CGIextChoice,
137                 CGIsepChoice => $CGIsepChoice,
138     );
139     if (C4::Context->preference('ExtendedPatronAttributes')) {
140         patron_attributes_form($template);
141     }
142 }
143 output_html_with_http_headers $input, $cookie, $template->output;
144
145 sub calculate {
146         my ($line, $column, $digits, $status, $activity, $filters, $attr_filters) = @_;
147
148         my @mainloop;
149         my @loopfooter;
150         my @loopcol;
151         my @loopline;
152         my @looprow;
153         my %globalline;
154         my $grantotal =0;
155 # extract parameters
156         my $dbh = C4::Context->dbh;
157
158     # check parameters
159     my @valid_names = qw(categorycode zipcode branchcode sex sort1 sort2);
160     my @attribute_types = C4::Members::AttributeTypes::GetAttributeTypes;
161     if ($line =~ /^patron_attr\.(.*)/) {
162         my $attribute_type = $1;
163         return unless (grep {$attribute_type eq $_->{code}} @attribute_types);
164     } else {
165         return unless (grep /^$line$/, @valid_names);
166     }
167     if ($column =~ /^patron_attr\.(.*)/) {
168         my $attribute_type = $1;
169         return unless (grep {$attribute_type eq $_->{code}} @attribute_types);
170     } else {
171         return unless (grep /^$column$/, @valid_names);
172     }
173     return if ($digits and $digits !~ /^\d+$/);
174     return if ($status and (grep /^$status$/, qw(debarred gonenoaddress lost)) == 0);
175     return if ($activity and (grep /^$activity$/, qw(active nonactive)) == 0);
176
177     # Filters
178     my $linefilter;
179     if    ( $line =~ /categorycode/ ) { $linefilter = @$filters[0]; }
180     elsif ( $line =~ /zipcode/ )      { $linefilter = @$filters[1]; }
181     elsif ( $line =~ /branchcode/ )   { $linefilter = @$filters[2]; }
182     elsif ( $line =~ /sex/ )          { $linefilter = @$filters[5]; }
183     elsif ( $line =~ /sort1/ )        { $linefilter = @$filters[6]; }
184     elsif ( $line =~ /sort2/ )        { $linefilter = @$filters[7]; }
185     elsif ( $line =~ /^patron_attr\.(.*)$/ ) { $linefilter = $attr_filters->{$1}; }
186     else  { $linefilter = ''; }
187
188     my $colfilter;
189     if    ( $column =~ /categorycode/ ) { $colfilter = @$filters[0]; }
190     elsif ( $column =~ /zipcode/ )      { $colfilter = @$filters[1]; }
191     elsif ( $column =~ /branchcode/)    { $colfilter = @$filters[2]; }
192     elsif ( $column =~ /sex/)           { $colfilter = @$filters[5]; }
193     elsif ( $column =~ /sort1/)         { $colfilter = @$filters[6]; }
194     elsif ( $column =~ /sort2/)         { $colfilter = @$filters[7]; }
195     elsif ( $column =~ /^patron_attr\.(.*)$/) { $colfilter = $attr_filters->{$1}; }
196     else  { $colfilter = ''; }
197
198     my @loopfilter;
199     foreach my $i (0 .. scalar @$filters) {
200         my %cell;
201         if ( @$filters[$i] ) {
202             if ($i == 3 or $i == 4) {
203                 $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
204                     if ( @$filters[$i] );
205             } else {
206                 $cell{filter} = @$filters[$i];
207             }
208
209             if    ( $i == 0)  { $cell{crit} = "Cat code"; }
210             elsif ( $i == 1 ) { $cell{crit} = "ZIP/Postal code"; }
211             elsif ( $i == 2 ) { $cell{crit} = "Branch code"; }
212             elsif ( $i == 3 ||
213                     $i == 4 ) { $cell{crit} = "Date of birth"; }
214             elsif ( $i == 5 ) { $cell{crit} = "Sex"; }
215             elsif ( $i == 6 ) { $cell{crit} = "Sort1"; }
216             elsif ( $i == 7 ) { $cell{crit} = "Sort2"; }
217             else { $cell{crit} = "Unknown"; }
218
219             push @loopfilter, \%cell;
220         }
221     }
222     foreach my $type (keys %$attr_filters) {
223         if($attr_filters->{$type}) {
224             push @loopfilter, {
225                 crit => "Attribute $type",
226                 filter => $attr_filters->{$type}
227             }
228         }
229     }
230
231     my @branchcodes = map { $_->branchcode } Koha::Libraries->search;
232         ($status  ) and push @loopfilter,{crit=>"Status",  filter=>$status  };
233         ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
234 # year of activity
235         my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
236         my $newperioddate=$period_year."-".$period_month."-".$period_day;
237 # 1st, loop rows.
238         my $linefield;
239
240     my $line_attribute_type;
241     if ($line  =~/^patron_attr\.(.*)$/) {
242         $line_attribute_type = $1;
243         $line = 'borrower_attributes.attribute';
244     }
245
246     if (($line =~/zipcode/) and ($digits)) {
247         $linefield = "left($line,$digits)";
248     } else {
249         $linefield = $line;
250     }
251     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']});
252
253     my $strsth;
254     my @strparams; # bind parameters for the query
255     if ($line_attribute_type) {
256         $strsth = "SELECT distinct attribute FROM borrower_attributes
257             WHERE attribute IS NOT NULL AND code=?";
258         push @strparams, $line_attribute_type;
259     } else {
260         $strsth = "SELECT distinctrow $linefield FROM borrowers
261             WHERE $line IS NOT NULL ";
262     }
263
264         $linefilter =~ s/\*/%/g;
265         if ( $linefilter ) {
266                 $strsth .= " AND $linefield LIKE ? " ;
267                 push @strparams, $linefilter;
268         }
269         $strsth .= " AND $status='1' " if ($status);
270     $strsth .=" order by $linefield";
271         
272         my $sth = $dbh->prepare($strsth);
273     $sth->execute(@strparams);
274         while (my ($celvalue) = $sth->fetchrow) {
275                 my %cell;
276                 if ($celvalue) {
277                         $cell{rowtitle} = $celvalue;
278             $cell{rowtitle_display} = ($patron_categories->find($celvalue)->description || "$celvalue\*") if ($line eq 'categorycode');
279                 }
280                 $cell{totalrow} = 0;
281                 push @loopline, \%cell;
282         }
283
284 # 2nd, loop cols.
285         my $colfield;
286
287     my $column_attribute_type;
288     if ($column  =~/^patron_attr.(.*)$/) {
289         $column_attribute_type = $1;
290         $column = 'borrower_attributes.attribute';
291     }
292
293     if (($column =~/zipcode/) and ($digits)) {
294         $colfield = "left($column,$digits)";
295     } else {
296         $colfield = $column;
297     }
298
299     my $strsth2;
300     my @strparams2; # bind parameters for the query
301     if ($column_attribute_type) {
302         $strsth2 = "SELECT DISTINCT attribute FROM borrower_attributes
303             WHERE attribute IS NOT NULL AND code=?";
304         push @strparams2, $column_attribute_type;
305     } else {
306         $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
307             WHERE $column IS NOT NULL";
308     }
309
310         if ($colfilter) {
311                 $colfilter =~ s/\*/%/g;
312                 $strsth2 .= " AND $colfield LIKE ? ";
313         push @strparams2, $colfield;
314         }
315         $strsth2 .= " AND $status='1' " if ($status);
316
317     $strsth2 .= " order by $colfield";
318         my $sth2 = $dbh->prepare($strsth2);
319     $sth2->execute(@strparams2);
320         while (my ($celvalue) = $sth2->fetchrow) {
321                 my %cell;
322              if (defined $celvalue) {
323                         $cell{coltitle} = $celvalue;
324                         # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
325             $cell{coltitle_display} = $patron_categories->find($celvalue)->description if ($column eq 'categorycode');
326                 }
327                 push @loopcol, \%cell;
328         }
329
330         my $i=0;
331         #Initialization of cell values.....
332         my %table;
333 #       warn "init table";
334         foreach my $row (@loopline) {
335                 foreach my $col ( @loopcol ) {
336             my $rowtitle = $row->{rowtitle} // '';
337             my $coltitle = $row->{coltitle} // '';
338             $table{$rowtitle}->{$coltitle} = 0;
339                 }
340         $row->{rowtitle} ||= '';
341                 $table{$row->{rowtitle}}->{totalrow}=0;
342                 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
343         }
344
345     # preparing calculation
346     my $strcalc;
347     my @calcparams;
348     $strcalc = "SELECT ";
349     if ($line_attribute_type) {
350         $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
351     } else {
352         $strcalc .= " $linefield, ";
353     }
354     if ($column_attribute_type) {
355         $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
356     } else {
357         $strcalc .= " $colfield, ";
358     }
359
360     $strcalc .= " COUNT(*) FROM borrowers ";
361     foreach my $type (keys %$attr_filters) {
362         if (
363             ($line_attribute_type and $line_attribute_type eq $type)
364          or ($column_attribute_type and $column_attribute_type eq $type)
365          or ($attr_filters->{$type})
366         ) {
367             $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
368                 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
369                     AND attribute_$type.code = " . $dbh->quote($type) . ") ";
370         }
371     }
372     $strcalc .= " WHERE 1 ";
373
374         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
375         $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
376         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
377         $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
378         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
379         $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
380         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
381         $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
382         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
383         $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
384     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
385     $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] );
386     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
387         $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
388         @$filters[7]=~ s/\*/%/g if (@$filters[7]);
389         $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
390
391     foreach my $type (keys %$attr_filters) {
392         if($attr_filters->{$type}) {
393             my $filter = $attr_filters->{$type};
394             $filter =~ s/\*/%/g;
395             $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
396         }
397     }
398     $strcalc .= " AND borrowers.borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
399     $strcalc .= " AND borrowers.borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "' AND borrowernumber IS NOT NULL)" if ($activity eq 'nonactive');
400         $strcalc .= " AND $status='1' " if ($status);
401
402     $strcalc .= " GROUP BY ";
403     if ($line_attribute_type) {
404         $strcalc .= " line_attribute, ";
405     } else {
406         $strcalc .= " $linefield, ";
407     }
408     if ($column_attribute_type) {
409         $strcalc .= " column_attribute ";
410     } else {
411         $strcalc .= " $colfield ";
412     }
413
414         my $dbcalc = $dbh->prepare($strcalc);
415         (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
416         
417         my $emptycol; 
418         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
419 #               warn "filling table $row / $col / $value ";
420                 $emptycol = 1 if (!defined($col));
421                 $col = "zzEMPTY" if (!defined($col));
422                 $row = "zzEMPTY" if (!defined($row));
423                 
424                 $table{$row}->{$col}+=$value;
425                 $table{$row}->{totalrow}+=$value;
426                 $grantotal += $value;
427         }
428         
429         push @loopcol,{coltitle => "NULL"} if ($emptycol);
430         
431         foreach my $row (sort keys %table) {
432                 my @loopcell;
433                 #@loopcol ensures the order for columns is common with column titles
434                 # and the number matches the number of columns
435                 foreach my $col ( @loopcol ) {
436             my $coltitle = $col->{coltitle} // '';
437             $coltitle = $coltitle eq "NULL" ? "zzEMPTY" : $coltitle;
438                         my $value =$table{$row}->{$coltitle};
439                         push @loopcell, {value => $value};
440                 }
441                 push @looprow,{
442                         'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
443                         'rowtitle_display' => $table{$row}->{rowtitle_display} || ($row eq "zzEMPTY" ? "NULL" : $row),
444                         'loopcell' => \@loopcell,
445                         'totalrow' => $table{$row}->{totalrow}
446                 };
447         }
448         
449         foreach my $col ( @loopcol ) {
450                 my $total=0;
451                 foreach my $row ( @looprow ) {
452             my $rowtitle = $row->{rowtitle} // '';
453             $rowtitle = ($rowtitle eq "NULL") ? "zzEMPTY" : $rowtitle;
454             my $coltitle = $col->{coltitle} // '';
455             $coltitle = ($coltitle eq "NULL") ? "zzEMPTY" : $coltitle;
456
457             $total += $table{$rowtitle}->{$coltitle} || 0;
458 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
459                 }
460 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
461                 push @loopfooter, {'totalcol' => $total};
462         }
463                         
464
465         # the header of the table
466         $globalline{loopfilter}=\@loopfilter;
467         # the core of the table
468         $globalline{looprow} = \@looprow;
469         $globalline{loopcol} = \@loopcol;
470 #       # the foot (totals by borrower type)
471         $globalline{loopfooter} = \@loopfooter;
472         $globalline{total}= $grantotal;
473         $globalline{line} = ($line_attribute_type) ? $line_attribute_type : $line;
474         $globalline{column} = ($column_attribute_type) ? $column_attribute_type : $column;
475         push @mainloop,\%globalline;
476         return \@mainloop;
477 }
478
479 sub parse_extended_patron_attributes {
480     my ($input) = @_;
481
482     my @params_names = $input->param;
483     my %attr;
484     foreach my $name (@params_names) {
485         if ($name =~ /^Filter_patron_attr\.(.*)$/) {
486             my $code = $1;
487             my $value = $input->param($name);
488             $attr{$code} = $value;
489         }
490     }
491
492     return \%attr;
493 }
494
495
496 sub patron_attributes_form {
497     my $template = shift;
498
499     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
500
501     my %items_by_class;
502     foreach my $type (@types) {
503         my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
504         my $entry = {
505             class             => $attr_type->class(),
506             code              => $attr_type->code(),
507             description       => $attr_type->description(),
508             repeatable        => $attr_type->repeatable(),
509             category          => $attr_type->authorised_value_category(),
510             category_code     => $attr_type->category_code(),
511         };
512
513         my $newentry = { %$entry };
514         if ($attr_type->authorised_value_category()) {
515             $newentry->{use_dropdown} = 1;
516             $newentry->{auth_val_loop} = GetAuthorisedValues(
517                 $attr_type->authorised_value_category()
518             );
519         }
520         push @{ $items_by_class{ $attr_type->class() } }, $newentry;
521     }
522
523     my @attribute_loop;
524     foreach my $class ( sort keys %items_by_class ) {
525         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
526         my $lib = $av->count ? $av->next->lib : $class;
527         push @attribute_loop, {
528             class => $class,
529             items => $items_by_class{$class},
530             lib   => $lib,
531         };
532     }
533
534     $template->param(patron_attributes => \@attribute_loop);
535
536 }