Bug 20443: Move C4::Members::AttributeTypes::GetAttributeTypes to Koha::Patron::Attri...
[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
32 use Koha::AuthorisedValues;
33 use Koha::DateUtils;
34 use Koha::Libraries;
35 use Koha::Patron::Attribute::Types;
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 destroy 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         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     if ($line =~ /^patron_attr\.(.*)/) {
161         my $attribute_type = $1;
162         return unless Koha::Patron::Attribute::Types->find($attribute_type);
163     } else {
164         return unless (grep { $_ eq $line } @valid_names);
165     }
166     if ($column =~ /^patron_attr\.(.*)/) {
167         my $attribute_type = $1;
168         return unless Koha::Patron::Attribute::Types->find($attribute_type);
169     } else {
170         return unless (grep { $_ eq $column } @valid_names);
171     }
172     return if ($digits and $digits !~ /^\d+$/);
173     return if ($status and (grep { $_ eq $status } qw(debarred gonenoaddress lost)) == 0);
174     return if ($activity and (grep { $_ eq $activity } qw(active nonactive)) == 0);
175
176     # Filters
177     my $linefilter;
178     if    ( $line =~ /categorycode/ ) { $linefilter = @$filters[0]; }
179     elsif ( $line =~ /zipcode/ )      { $linefilter = @$filters[1]; }
180     elsif ( $line =~ /branchcode/ )   { $linefilter = @$filters[2]; }
181     elsif ( $line =~ /sex/ )          { $linefilter = @$filters[5]; }
182     elsif ( $line =~ /sort1/ )        { $linefilter = @$filters[6]; }
183     elsif ( $line =~ /sort2/ )        { $linefilter = @$filters[7]; }
184     elsif ( $line =~ /^patron_attr\.(.*)$/ ) { $linefilter = $attr_filters->{$1}; }
185     else  { $linefilter = ''; }
186
187     my $colfilter;
188     if    ( $column =~ /categorycode/ ) { $colfilter = @$filters[0]; }
189     elsif ( $column =~ /zipcode/ )      { $colfilter = @$filters[1]; }
190     elsif ( $column =~ /branchcode/)    { $colfilter = @$filters[2]; }
191     elsif ( $column =~ /sex/)           { $colfilter = @$filters[5]; }
192     elsif ( $column =~ /sort1/)         { $colfilter = @$filters[6]; }
193     elsif ( $column =~ /sort2/)         { $colfilter = @$filters[7]; }
194     elsif ( $column =~ /^patron_attr\.(.*)$/) { $colfilter = $attr_filters->{$1}; }
195     else  { $colfilter = ''; }
196
197     my @loopfilter;
198     foreach my $i (0 .. scalar @$filters) {
199         my %cell;
200         if ( @$filters[$i] ) {
201             if ($i == 3 or $i == 4) {
202                 $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
203                     if ( @$filters[$i] );
204             } else {
205                 $cell{filter} = @$filters[$i];
206             }
207
208             if    ( $i == 0)  { $cell{crit} = "Cat code"; }
209             elsif ( $i == 1 ) { $cell{crit} = "ZIP/Postal code"; }
210             elsif ( $i == 2 ) { $cell{crit} = "Branch code"; }
211             elsif ( $i == 3 ||
212                     $i == 4 ) { $cell{crit} = "Date of birth"; }
213             elsif ( $i == 5 ) { $cell{crit} = "Sex"; }
214             elsif ( $i == 6 ) { $cell{crit} = "Sort1"; }
215             elsif ( $i == 7 ) { $cell{crit} = "Sort2"; }
216             else { $cell{crit} = "Unknown"; }
217
218             push @loopfilter, \%cell;
219         }
220     }
221     foreach my $type (keys %$attr_filters) {
222         if($attr_filters->{$type}) {
223             push @loopfilter, {
224                 crit => "Attribute $type",
225                 filter => $attr_filters->{$type}
226             }
227         }
228     }
229
230     my @branchcodes = map { $_->branchcode } Koha::Libraries->search;
231         ($status  ) and push @loopfilter,{crit=>"Status",  filter=>$status  };
232         ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
233 # year of activity
234         my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
235         my $newperioddate=$period_year."-".$period_month."-".$period_day;
236 # 1st, loop rows.
237         my $linefield;
238
239     my $line_attribute_type;
240     if ($line  =~/^patron_attr\.(.*)$/) {
241         $line_attribute_type = $1;
242         $line = 'borrower_attributes.attribute';
243     }
244
245     if (($line =~/zipcode/) and ($digits)) {
246         $linefield = "left($line,$digits)";
247     } else {
248         $linefield = $line;
249     }
250     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']});
251
252     my $strsth;
253     my @strparams; # bind parameters for the query
254     if ($line_attribute_type) {
255         $strsth = "SELECT distinct attribute FROM borrower_attributes
256             WHERE attribute IS NOT NULL AND code=?";
257         push @strparams, $line_attribute_type;
258     } else {
259         $strsth = "SELECT distinctrow $linefield FROM borrowers
260             WHERE $line IS NOT NULL ";
261     }
262
263         $linefilter =~ s/\*/%/g;
264         if ( $linefilter ) {
265                 $strsth .= " AND $linefield LIKE ? " ;
266                 push @strparams, $linefilter;
267         }
268         $strsth .= " AND $status='1' " if ($status);
269     $strsth .=" order by $linefield";
270         
271         my $sth = $dbh->prepare($strsth);
272     $sth->execute(@strparams);
273         while (my ($celvalue) = $sth->fetchrow) {
274                 my %cell;
275                 if ($celvalue) {
276                         $cell{rowtitle} = $celvalue;
277             $cell{rowtitle_display} = ($patron_categories->find($celvalue)->description || "$celvalue\*") if ($line eq 'categorycode');
278                 }
279                 $cell{totalrow} = 0;
280                 push @loopline, \%cell;
281         }
282
283 # 2nd, loop cols.
284         my $colfield;
285
286     my $column_attribute_type;
287     if ($column  =~/^patron_attr.(.*)$/) {
288         $column_attribute_type = $1;
289         $column = 'borrower_attributes.attribute';
290     }
291
292     if (($column =~/zipcode/) and ($digits)) {
293         $colfield = "left($column,$digits)";
294     } else {
295         $colfield = $column;
296     }
297
298     my $strsth2;
299     my @strparams2; # bind parameters for the query
300     if ($column_attribute_type) {
301         $strsth2 = "SELECT DISTINCT attribute FROM borrower_attributes
302             WHERE attribute IS NOT NULL AND code=?";
303         push @strparams2, $column_attribute_type;
304     } else {
305         $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
306             WHERE $column IS NOT NULL";
307     }
308
309         if ($colfilter) {
310                 $colfilter =~ s/\*/%/g;
311                 $strsth2 .= " AND $colfield LIKE ? ";
312         push @strparams2, $colfield;
313         }
314         $strsth2 .= " AND $status='1' " if ($status);
315
316     $strsth2 .= " order by $colfield";
317         my $sth2 = $dbh->prepare($strsth2);
318     $sth2->execute(@strparams2);
319         while (my ($celvalue) = $sth2->fetchrow) {
320                 my %cell;
321              if (defined $celvalue) {
322                         $cell{coltitle} = $celvalue;
323                         # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
324             $cell{coltitle_display} = $patron_categories->find($celvalue)->description if ($column eq 'categorycode');
325                 }
326                 push @loopcol, \%cell;
327         }
328
329         my $i=0;
330         #Initialization of cell values.....
331         my %table;
332 #       warn "init table";
333         foreach my $row (@loopline) {
334                 foreach my $col ( @loopcol ) {
335             my $rowtitle = $row->{rowtitle} // '';
336             my $coltitle = $row->{coltitle} // '';
337             $table{$rowtitle}->{$coltitle} = 0;
338                 }
339         $row->{rowtitle} ||= '';
340                 $table{$row->{rowtitle}}->{totalrow}=0;
341                 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
342         }
343
344     # preparing calculation
345     my $strcalc;
346     my @calcparams;
347     $strcalc = "SELECT ";
348     if ($line_attribute_type) {
349         $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
350     } else {
351         $strcalc .= " $linefield, ";
352     }
353     if ($column_attribute_type) {
354         $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
355     } else {
356         $strcalc .= " $colfield, ";
357     }
358
359     $strcalc .= " COUNT(*) FROM borrowers ";
360     foreach my $type (keys %$attr_filters) {
361         if (
362             ($line_attribute_type and $line_attribute_type eq $type)
363          or ($column_attribute_type and $column_attribute_type eq $type)
364          or ($attr_filters->{$type})
365         ) {
366             $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
367                 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
368                     AND attribute_$type.code = " . $dbh->quote($type) . ") ";
369         }
370     }
371     $strcalc .= " WHERE 1 ";
372
373         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
374         $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
375         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
376         $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
377         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
378         $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
379         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
380         $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
381         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
382         $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
383     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
384     $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] );
385     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
386         $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
387         @$filters[7]=~ s/\*/%/g if (@$filters[7]);
388         $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
389
390     foreach my $type (keys %$attr_filters) {
391         if($attr_filters->{$type}) {
392             my $filter = $attr_filters->{$type};
393             $filter =~ s/\*/%/g;
394             $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
395         }
396     }
397     $strcalc .= " AND borrowers.borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
398     $strcalc .= " AND borrowers.borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "' AND borrowernumber IS NOT NULL)" if ($activity eq 'nonactive');
399         $strcalc .= " AND $status='1' " if ($status);
400
401     $strcalc .= " GROUP BY ";
402     if ($line_attribute_type) {
403         $strcalc .= " line_attribute, ";
404     } else {
405         $strcalc .= " $linefield, ";
406     }
407     if ($column_attribute_type) {
408         $strcalc .= " column_attribute ";
409     } else {
410         $strcalc .= " $colfield ";
411     }
412
413         my $dbcalc = $dbh->prepare($strcalc);
414         (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
415         
416         my $emptycol; 
417         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
418 #               warn "filling table $row / $col / $value ";
419                 $emptycol = 1 if (!defined($col));
420                 $col = "zzEMPTY" if (!defined($col));
421                 $row = "zzEMPTY" if (!defined($row));
422                 
423                 $table{$row}->{$col}+=$value;
424                 $table{$row}->{totalrow}+=$value;
425                 $grantotal += $value;
426         }
427         
428         push @loopcol,{coltitle => "NULL"} if ($emptycol);
429         
430         foreach my $row (sort keys %table) {
431                 my @loopcell;
432                 #@loopcol ensures the order for columns is common with column titles
433                 # and the number matches the number of columns
434                 foreach my $col ( @loopcol ) {
435             my $coltitle = $col->{coltitle} // '';
436             $coltitle = $coltitle eq "NULL" ? "zzEMPTY" : $coltitle;
437                         my $value =$table{$row}->{$coltitle};
438                         push @loopcell, {value => $value};
439                 }
440                 push @looprow,{
441                         'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
442                         'rowtitle_display' => $table{$row}->{rowtitle_display} || ($row eq "zzEMPTY" ? "NULL" : $row),
443                         'loopcell' => \@loopcell,
444                         'totalrow' => $table{$row}->{totalrow}
445                 };
446         }
447         
448         foreach my $col ( @loopcol ) {
449                 my $total=0;
450                 foreach my $row ( @looprow ) {
451             my $rowtitle = $row->{rowtitle} // '';
452             $rowtitle = ($rowtitle eq "NULL") ? "zzEMPTY" : $rowtitle;
453             my $coltitle = $col->{coltitle} // '';
454             $coltitle = ($coltitle eq "NULL") ? "zzEMPTY" : $coltitle;
455
456             $total += $table{$rowtitle}->{$coltitle} || 0;
457 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
458                 }
459 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
460                 push @loopfooter, {'totalcol' => $total};
461         }
462                         
463
464         # the header of the table
465         $globalline{loopfilter}=\@loopfilter;
466         # the core of the table
467         $globalline{looprow} = \@looprow;
468         $globalline{loopcol} = \@loopcol;
469 #       # the foot (totals by borrower type)
470         $globalline{loopfooter} = \@loopfooter;
471         $globalline{total}= $grantotal;
472         $globalline{line} = ($line_attribute_type) ? $line_attribute_type : $line;
473         $globalline{column} = ($column_attribute_type) ? $column_attribute_type : $column;
474         push @mainloop,\%globalline;
475         return \@mainloop;
476 }
477
478 sub parse_extended_patron_attributes {
479     my ($input) = @_;
480
481     my @params_names = $input->param;
482     my %attr;
483     foreach my $name (@params_names) {
484         if ($name =~ /^Filter_patron_attr\.(.*)$/) {
485             my $code = $1;
486             my $value = $input->param($name);
487             $attr{$code} = $value;
488         }
489     }
490
491     return \%attr;
492 }
493
494
495 sub patron_attributes_form {
496     my $template = shift;
497
498     my $attribute_types = Koha::Patron::Attribute::Types->filter_by_branch_limitations;
499
500     my %items_by_class;
501     while ( my $attr_type = $attribute_types->next ) {
502         # TODO The following can be simplified easily
503         my $entry = {
504             class             => $attr_type->class(),
505             code              => $attr_type->code(),
506             description       => $attr_type->description(),
507             repeatable        => $attr_type->repeatable(),
508             category          => $attr_type->authorised_value_category(),
509             category_code     => $attr_type->category_code(),
510         };
511
512         my $newentry = { %$entry };
513         if ($attr_type->authorised_value_category()) {
514             $newentry->{use_dropdown} = 1;
515             $newentry->{auth_val_loop} = GetAuthorisedValues(
516                 $attr_type->authorised_value_category()
517             );
518         }
519         push @{ $items_by_class{ $attr_type->class() } }, $newentry;
520     }
521
522     my @attribute_loop;
523     foreach my $class ( sort keys %items_by_class ) {
524         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
525         my $lib = $av->count ? $av->next->lib : $class;
526         push @attribute_loop, {
527             class => $class,
528             items => $items_by_class{$class},
529             lib   => $lib,
530         };
531     }
532
533     $template->param(patron_attributes => \@attribute_loop);
534
535 }