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