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