Bug 13914 : Fix UNION in SQL request for reserves statistics
[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 Koha::DateUtils;
28 use C4::Acquisition;
29 use C4::Output;
30 use C4::Reports;
31 use C4::Circulation;
32 use C4::Members::AttributeTypes;
33
34 use Koha::Libraries;
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
69 my ($template, $borrowernumber, $cookie)
70         = get_template_and_user({template_name => $fullreportname,
71                                 query => $input,
72                                 type => "intranet",
73                                 authnotrequired => 0,
74                                 flagsrequired => {reports => '*'},
75                                 debug => 1,
76                                 });
77 $template->param(do_it => $do_it);
78 if ($do_it) {
79         my $attributes;
80         if (C4::Context->preference('ExtendedPatronAttributes')) {
81             $attributes = parse_extended_patron_attributes($input);
82         }
83         my $results = calculate($line, $column, $digits, $borstat,$borstat1 ,\@filters, $attributes);
84         if ($output eq "screen"){
85                 $template->param(mainloop => $results);
86                 output_html_with_http_headers $input, $cookie, $template->output;
87         } else {
88                 print $input->header(-type => 'application/vnd.sun.xml.calc',
89                          -encoding => 'utf-8',
90                              -name => "$basename.csv",
91                        -attachment => "$basename.csv");
92                 my $cols = @$results[0]->{loopcol};
93                 my $lines = @$results[0]->{looprow};
94                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
95                 foreach my $col ( @$cols ) {
96                         print $col->{coltitle}.$sep;
97                 }
98                 print "Total\n";
99                 foreach my $line ( @$lines ) {
100                         my $x = $line->{loopcell};
101                         print $line->{rowtitle}.$sep;
102                         foreach my $cell (@$x) {
103                                 print $cell->{value}.$sep;
104                         }
105                         print $line->{totalrow};
106                         print "\n";
107                 }
108                 print "TOTAL";
109                 $cols = @$results[0]->{loopfooter};
110                 foreach my $col ( @$cols ) {
111                         print $sep.$col->{totalcol};
112                 }
113                 print $sep.@$results[0]->{total};
114         }
115         exit;   # exit after do_it, regardless
116 } else {
117         my $dbh = C4::Context->dbh;
118         my $req;
119     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']});
120     $template->param( patron_categories => $patron_categories );
121         $req = $dbh->prepare("SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode");
122         $req->execute;
123         $template->param(   ZIP_LOOP => $req->fetchall_arrayref({}));
124         $req = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' ORDER BY lib");
125         $req->execute;
126         $template->param( SORT1_LOOP => $req->fetchall_arrayref({}));
127         $req = $dbh->prepare("SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort2 <> '' ORDER BY sort2 LIMIT 200");
128                 # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destory DB performance.
129         $req->execute;
130         $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
131         
132     my $CGIextChoice = ( 'CSV' ); # FIXME translation
133         my $CGIsepChoice=GetDelimiterChoices;
134         $template->param(
135                 CGIextChoice => $CGIextChoice,
136                 CGIsepChoice => $CGIsepChoice,
137     );
138     if (C4::Context->preference('ExtendedPatronAttributes')) {
139         $template->param(ExtendedPatronAttributes => 1);
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     push @loopfilter,{debug=>1, crit=>"Branches",filter=>join(" ", sort @branchcodes)};
235         push @loopfilter,{debug=>1, crit=>"(line, column)", filter=>"($line,$column)"};
236 # year of activity
237         my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
238         my $newperioddate=$period_year."-".$period_month."-".$period_day;
239 # 1st, loop rows.
240         my $linefield;
241
242     my $line_attribute_type;
243     if ($line  =~/^patron_attr\.(.*)$/) {
244         $line_attribute_type = $1;
245         $line = 'borrower_attributes.attribute';
246     }
247
248     if (($line =~/zipcode/) and ($digits)) {
249         $linefield = "left($line,$digits)";
250     } else {
251         $linefield = $line;
252     }
253     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']});
254     push @loopfilter,
255         {
256             debug  => 1,
257             crit   => "Patron category",
258             filter => join( ", ", map { $_->categorycode . ' (' . ( $_->description || 'NO_DESCRIPTION' ) . ')' } $patron_categories->as_list ),
259         };
260
261     my $strsth;
262     my @strparams; # bind parameters for the query
263     if ($line_attribute_type) {
264         $strsth = "SELECT distinct attribute FROM borrower_attributes
265             WHERE attribute IS NOT NULL AND code=?";
266         push @strparams, $line_attribute_type;
267     } else {
268         $strsth = "SELECT distinctrow $linefield FROM borrowers
269             WHERE $line IS NOT NULL ";
270     }
271
272         $linefilter =~ s/\*/%/g;
273         if ( $linefilter ) {
274                 $strsth .= " AND $linefield LIKE ? " ;
275                 push @strparams, $linefilter;
276         }
277         $strsth .= " AND $status='1' " if ($status);
278     $strsth .=" order by $linefield";
279         
280         push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth};
281         my $sth = $dbh->prepare($strsth);
282     $sth->execute(@strparams);
283         while (my ($celvalue) = $sth->fetchrow) {
284                 my %cell;
285                 if ($celvalue) {
286                         $cell{rowtitle} = $celvalue;
287             $cell{rowtitle_display} = ($patron_categories->find($celvalue)->description || "$celvalue\*") if ($line eq 'categorycode');
288                 }
289                 $cell{totalrow} = 0;
290                 push @loopline, \%cell;
291         }
292
293 # 2nd, loop cols.
294         my $colfield;
295
296     my $column_attribute_type;
297     if ($column  =~/^patron_attr.(.*)$/) {
298         $column_attribute_type = $1;
299         $column = 'borrower_attributes.attribute';
300     }
301
302     if (($column =~/zipcode/) and ($digits)) {
303         $colfield = "left($column,$digits)";
304     } else {
305         $colfield = $column;
306     }
307
308     my $strsth2;
309     my @strparams2; # bind parameters for the query
310     if ($column_attribute_type) {
311         $strsth2 = "SELECT DISTINCT attribute FROM borrower_attributes
312             WHERE attribute IS NOT NULL AND code=?";
313         push @strparams2, $column_attribute_type;
314     } else {
315         $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
316             WHERE $column IS NOT NULL";
317     }
318
319         if ($colfilter) {
320                 $colfilter =~ s/\*/%/g;
321                 $strsth2 .= " AND $colfield LIKE ? ";
322         push @strparams2, $colfield;
323         }
324         $strsth2 .= " AND $status='1' " if ($status);
325
326     $strsth2 .= " order by $colfield";
327         push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth2};
328         my $sth2 = $dbh->prepare($strsth2);
329     $sth2->execute(@strparams2);
330         while (my ($celvalue) = $sth2->fetchrow) {
331                 my %cell;
332              if (defined $celvalue) {
333                         $cell{coltitle} = $celvalue;
334                         # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
335             $cell{coltitle_display} = $patron_categories->find($celvalue)->description if ($column eq 'categorycode');
336                 }
337                 push @loopcol, \%cell;
338         }
339
340         my $i=0;
341         #Initialization of cell values.....
342         my %table;
343 #       warn "init table";
344         foreach my $row (@loopline) {
345                 foreach my $col ( @loopcol ) {
346             my $rowtitle = $row->{rowtitle} // '';
347             my $coltitle = $row->{coltitle} // '';
348             $table{$rowtitle}->{$coltitle} = 0;
349                 }
350         $row->{rowtitle} ||= '';
351                 $table{$row->{rowtitle}}->{totalrow}=0;
352                 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
353         }
354
355     # preparing calculation
356     my $strcalc;
357     my @calcparams;
358     $strcalc = "SELECT ";
359     if ($line_attribute_type) {
360         $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
361     } else {
362         $strcalc .= " $linefield, ";
363     }
364     if ($column_attribute_type) {
365         $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
366     } else {
367         $strcalc .= " $colfield, ";
368     }
369
370     $strcalc .= " COUNT(*) FROM borrowers ";
371     foreach my $type (keys %$attr_filters) {
372         if (
373             ($line_attribute_type and $line_attribute_type eq $type)
374          or ($column_attribute_type and $column_attribute_type eq $type)
375          or ($attr_filters->{$type})
376         ) {
377             $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
378                 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
379                     AND attribute_$type.code = " . $dbh->quote($type) . ") ";
380         }
381     }
382     $strcalc .= " WHERE 1 ";
383
384         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
385         $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
386         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
387         $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
388         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
389         $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
390         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
391         $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
392         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
393         $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
394     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
395     $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] );
396     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
397         $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
398         @$filters[7]=~ s/\*/%/g if (@$filters[7]);
399         $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
400
401     foreach my $type (keys %$attr_filters) {
402         if($attr_filters->{$type}) {
403             my $filter = $attr_filters->{$type};
404             $filter =~ s/\*/%/g;
405             $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
406         }
407     }
408         $strcalc .= " AND borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
409         $strcalc .= " AND borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'nonactive');
410         $strcalc .= " AND $status='1' " if ($status);
411
412     $strcalc .= " GROUP BY ";
413     if ($line_attribute_type) {
414         $strcalc .= " line_attribute, ";
415     } else {
416         $strcalc .= " $linefield, ";
417     }
418     if ($column_attribute_type) {
419         $strcalc .= " column_attribute ";
420     } else {
421         $strcalc .= " $colfield ";
422     }
423
424         push @loopfilter, {sql=>1, crit=>"Query", filter=>$strcalc};
425         my $dbcalc = $dbh->prepare($strcalc);
426         (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
427         
428         my $emptycol; 
429         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
430 #               warn "filling table $row / $col / $value ";
431                 $emptycol = 1 if (!defined($col));
432                 $col = "zzEMPTY" if (!defined($col));
433                 $row = "zzEMPTY" if (!defined($row));
434                 
435                 $table{$row}->{$col}+=$value;
436                 $table{$row}->{totalrow}+=$value;
437                 $grantotal += $value;
438         }
439         
440         push @loopcol,{coltitle => "NULL"} if ($emptycol);
441         
442         foreach my $row (sort keys %table) {
443                 my @loopcell;
444                 #@loopcol ensures the order for columns is common with column titles
445                 # and the number matches the number of columns
446                 foreach my $col ( @loopcol ) {
447             my $coltitle = $col->{coltitle} // '';
448             $coltitle = $coltitle eq "NULL" ? "zzEMPTY" : $coltitle;
449                         my $value =$table{$row}->{$coltitle};
450                         push @loopcell, {value => $value};
451                 }
452                 push @looprow,{
453                         'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
454                         'rowtitle_display' => $table{$row}->{rowtitle_display} || ($row eq "zzEMPTY" ? "NULL" : $row),
455                         'loopcell' => \@loopcell,
456                         'totalrow' => $table{$row}->{totalrow}
457                 };
458         }
459         
460         foreach my $col ( @loopcol ) {
461                 my $total=0;
462                 foreach my $row ( @looprow ) {
463             my $rowtitle = $row->{rowtitle} // '';
464             $rowtitle = ($rowtitle eq "NULL") ? "zzEMPTY" : $rowtitle;
465             my $coltitle = $col->{coltitle} // '';
466             $coltitle = ($coltitle eq "NULL") ? "zzEMPTY" : $coltitle;
467
468             $total += $table{$rowtitle}->{$coltitle} || 0;
469 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
470                 }
471 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
472                 push @loopfooter, {'totalcol' => $total};
473         }
474                         
475
476         # the header of the table
477         $globalline{loopfilter}=\@loopfilter;
478         # the core of the table
479         $globalline{looprow} = \@looprow;
480         $globalline{loopcol} = \@loopcol;
481 #       # the foot (totals by borrower type)
482         $globalline{loopfooter} = \@loopfooter;
483         $globalline{total}= $grantotal;
484         $globalline{line} = ($line_attribute_type) ? $line_attribute_type : $line;
485         $globalline{column} = ($column_attribute_type) ? $column_attribute_type : $column;
486         push @mainloop,\%globalline;
487         return \@mainloop;
488 }
489
490 sub parse_extended_patron_attributes {
491     my ($input) = @_;
492
493     my @params_names = $input->param;
494     my %attr;
495     foreach my $name (@params_names) {
496         if ($name =~ /^Filter_patron_attr\.(.*)$/) {
497             my $code = $1;
498             my $value = $input->param($name);
499             $attr{$code} = $value;
500         }
501     }
502
503     return \%attr;
504 }
505
506
507 sub patron_attributes_form {
508     my $template = shift;
509
510     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
511
512     my %items_by_class;
513     foreach my $type (@types) {
514         my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
515         my $entry = {
516             class             => $attr_type->class(),
517             code              => $attr_type->code(),
518             description       => $attr_type->description(),
519             repeatable        => $attr_type->repeatable(),
520             category          => $attr_type->authorised_value_category(),
521             category_code     => $attr_type->category_code(),
522         };
523
524         my $newentry = { %$entry };
525         if ($attr_type->authorised_value_category()) {
526             $newentry->{use_dropdown} = 1;
527             $newentry->{auth_val_loop} = GetAuthorisedValues(
528                 $attr_type->authorised_value_category()
529             );
530         }
531         push @{ $items_by_class{ $attr_type->class() } }, $newentry;
532     }
533
534     my @attribute_loop;
535     foreach my $class ( sort keys %items_by_class ) {
536         my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
537         push @attribute_loop, {
538             class => $class,
539             items => $items_by_class{$class},
540             lib   => $lib,
541         };
542     }
543
544     $template->param(patron_attributes => \@attribute_loop);
545
546 }