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