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