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