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