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