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