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