Bug 35994: Show acq_status on catalogue/detail
[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";        $cell{filter} = @$filters[$i]; }
188             elsif ( $i == 1 )            { $cell{crit} = "ZIP/Postal code"; $cell{filter} = @$filters[$i]; }
189             elsif ( $i == 2 )            { $cell{crit} = "Branch code";     $cell{filter} = @$filters[$i]; }
190             elsif ( $i == 3 || $i == 4 ) { $cell{crit} = "Date of birth";   $cell{filter} = @$filters[$i]; }
191             elsif ( $i == 5 )            { $cell{crit} = "Sex";             $cell{filter} = @$filters[$i]; }
192             elsif ( $i == 6 )            { $cell{crit} = "Sort1";           $cell{filter} = @$filters[$i]; }
193             elsif ( $i == 7 )            { $cell{crit} = "Sort2";           $cell{filter} = @$filters[$i]; }
194             else                         { $cell{crit} = "Unknown"; }
195
196             push @loopfilter, \%cell;
197         }
198     }
199     foreach my $type (keys %$attr_filters) {
200         if($attr_filters->{$type}) {
201             push @loopfilter, {
202                 crit => "Attribute $type",
203                 filter => $attr_filters->{$type}
204             }
205         }
206     }
207
208     my @branchcodes = Koha::Libraries->search->get_column('branchcode');
209         ($status  ) and push @loopfilter,{crit=>"Status",  filter=>$status  };
210         ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
211 # year of activity
212         my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
213         my $newperioddate=$period_year."-".$period_month."-".$period_day;
214 # 1st, loop rows.
215         my $linefield;
216
217     my $line_attribute_type;
218     if ($line  =~/^patron_attr\.(.*)$/) {
219         $line_attribute_type = $1;
220         $line = 'borrower_attributes.attribute';
221     }
222
223     if (($line =~/zipcode/) and ($digits)) {
224         $linefield = "left($line,$digits)";
225     } else {
226         $linefield = $line;
227     }
228     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']});
229
230     my $strsth;
231     my @strparams; # bind parameters for the query
232     if ($line_attribute_type) {
233         $strsth = "SELECT distinct attribute FROM borrower_attributes
234             WHERE attribute IS NOT NULL AND code=?";
235         push @strparams, $line_attribute_type;
236     } else {
237         $strsth = "SELECT distinctrow $linefield FROM borrowers
238             WHERE $line IS NOT NULL ";
239     }
240
241         $linefilter =~ s/\*/%/g;
242         if ( $linefilter ) {
243                 $strsth .= " AND $linefield LIKE ? " ;
244                 push @strparams, $linefilter;
245         }
246         $strsth .= " AND $status='1' " if ($status);
247     $strsth .=" order by $linefield";
248         
249         my $sth = $dbh->prepare($strsth);
250     $sth->execute(@strparams);
251         while (my ($celvalue) = $sth->fetchrow) {
252                 my %cell;
253                 if ($celvalue) {
254                         $cell{rowtitle} = $celvalue;
255             $cell{rowtitle_display} = ($patron_categories->find($celvalue)->description || "$celvalue\*") if ($line eq 'categorycode');
256                 }
257                 $cell{totalrow} = 0;
258                 push @loopline, \%cell;
259         }
260
261 # 2nd, loop cols.
262         my $colfield;
263
264     my $column_attribute_type;
265     if ($column  =~/^patron_attr.(.*)$/) {
266         $column_attribute_type = $1;
267         $column = 'borrower_attributes.attribute';
268     }
269
270     if (($column =~/zipcode/) and ($digits)) {
271         $colfield = "left($column,$digits)";
272     } else {
273         $colfield = $column;
274     }
275
276     my $strsth2;
277     my @strparams2; # bind parameters for the query
278     if ($column_attribute_type) {
279         $strsth2 = "SELECT DISTINCT attribute FROM borrower_attributes
280             WHERE attribute IS NOT NULL AND code=?";
281         push @strparams2, $column_attribute_type;
282     } else {
283         $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
284             WHERE $column IS NOT NULL";
285     }
286
287         if ($colfilter) {
288                 $colfilter =~ s/\*/%/g;
289                 $strsth2 .= " AND $colfield LIKE ? ";
290         push @strparams2, $colfield;
291         }
292         $strsth2 .= " AND $status='1' " if ($status);
293
294     $strsth2 .= " order by $colfield";
295         my $sth2 = $dbh->prepare($strsth2);
296     $sth2->execute(@strparams2);
297         while (my ($celvalue) = $sth2->fetchrow) {
298                 my %cell;
299              if (defined $celvalue) {
300                         $cell{coltitle} = $celvalue;
301                         # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
302             $cell{coltitle_display} = $patron_categories->find($celvalue)->description if ($column eq 'categorycode');
303                 }
304                 push @loopcol, \%cell;
305         }
306
307         my $i=0;
308         #Initialization of cell values.....
309         my %table;
310 #       warn "init table";
311         foreach my $row (@loopline) {
312                 foreach my $col ( @loopcol ) {
313             my $rowtitle = $row->{rowtitle} // '';
314             my $coltitle = $row->{coltitle} // '';
315             $table{$rowtitle}->{$coltitle} = 0;
316                 }
317         $row->{rowtitle} ||= '';
318                 $table{$row->{rowtitle}}->{totalrow}=0;
319                 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
320         }
321
322     # preparing calculation
323     my $strcalc;
324     my @calcparams;
325     $strcalc = "SELECT ";
326     if ($line_attribute_type) {
327         $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
328     } else {
329         $strcalc .= " $linefield, ";
330     }
331     if ($column_attribute_type) {
332         $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
333     } else {
334         $strcalc .= " $colfield, ";
335     }
336
337     $strcalc .= " COUNT(*) FROM borrowers ";
338     foreach my $type (keys %$attr_filters) {
339         if (
340             ($line_attribute_type and $line_attribute_type eq $type)
341          or ($column_attribute_type and $column_attribute_type eq $type)
342          or ($attr_filters->{$type})
343         ) {
344             $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
345                 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
346                     AND attribute_$type.code = " . $dbh->quote($type) . ") ";
347         }
348     }
349     $strcalc .= " WHERE 1 ";
350
351         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
352         $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
353         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
354         $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
355         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
356         $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
357         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
358         $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
359         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
360         $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
361     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
362     $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] );
363     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
364         $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
365         @$filters[7]=~ s/\*/%/g if (@$filters[7]);
366         $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
367
368     foreach my $type (keys %$attr_filters) {
369         if($attr_filters->{$type}) {
370             my $filter = $attr_filters->{$type};
371             $filter =~ s/\*/%/g;
372             $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
373         }
374     }
375     $strcalc .= " AND borrowers.borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
376     $strcalc .= " AND borrowers.borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "' AND borrowernumber IS NOT NULL)" if ($activity eq 'nonactive');
377         $strcalc .= " AND $status='1' " if ($status);
378
379     $strcalc .= " GROUP BY ";
380     if ($line_attribute_type) {
381         $strcalc .= " line_attribute, ";
382     } else {
383         $strcalc .= " $linefield, ";
384     }
385     if ($column_attribute_type) {
386         $strcalc .= " column_attribute ";
387     } else {
388         $strcalc .= " $colfield ";
389     }
390
391         my $dbcalc = $dbh->prepare($strcalc);
392         (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
393         
394         my $emptycol; 
395         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
396 #               warn "filling table $row / $col / $value ";
397                 $emptycol = 1 if (!defined($col));
398                 $col = "zzEMPTY" if (!defined($col));
399                 $row = "zzEMPTY" if (!defined($row));
400                 
401                 $table{$row}->{$col}+=$value;
402                 $table{$row}->{totalrow}+=$value;
403                 $grantotal += $value;
404         }
405         
406         push @loopcol,{coltitle => "NULL"} if ($emptycol);
407         
408         foreach my $row (sort keys %table) {
409                 my @loopcell;
410                 #@loopcol ensures the order for columns is common with column titles
411                 # and the number matches the number of columns
412                 foreach my $col ( @loopcol ) {
413             my $coltitle = $col->{coltitle} // '';
414             $coltitle = $coltitle eq "NULL" ? "zzEMPTY" : $coltitle;
415                         my $value =$table{$row}->{$coltitle};
416                         push @loopcell, {value => $value};
417                 }
418                 push @looprow,{
419                         'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
420                         'rowtitle_display' => $table{$row}->{rowtitle_display} || ($row eq "zzEMPTY" ? "NULL" : $row),
421                         'loopcell' => \@loopcell,
422                         'totalrow' => $table{$row}->{totalrow}
423                 };
424         }
425         
426         foreach my $col ( @loopcol ) {
427                 my $total=0;
428                 foreach my $row ( @looprow ) {
429             my $rowtitle = $row->{rowtitle} // '';
430             $rowtitle = ($rowtitle eq "NULL") ? "zzEMPTY" : $rowtitle;
431             my $coltitle = $col->{coltitle} // '';
432             $coltitle = ($coltitle eq "NULL") ? "zzEMPTY" : $coltitle;
433
434             $total += $table{$rowtitle}->{$coltitle} || 0;
435 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
436                 }
437 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
438                 push @loopfooter, {'totalcol' => $total};
439         }
440                         
441
442         # the header of the table
443         $globalline{loopfilter}=\@loopfilter;
444         # the core of the table
445         $globalline{looprow} = \@looprow;
446         $globalline{loopcol} = \@loopcol;
447 #       # the foot (totals by borrower type)
448         $globalline{loopfooter} = \@loopfooter;
449         $globalline{total}= $grantotal;
450         $globalline{line} = ($line_attribute_type) ? $line_attribute_type : $line;
451         $globalline{column} = ($column_attribute_type) ? $column_attribute_type : $column;
452         push @mainloop,\%globalline;
453         return \@mainloop;
454 }
455
456 sub parse_extended_patron_attributes {
457     my ($input) = @_;
458
459     my @params_names = $input->param;
460     my %attr;
461     foreach my $name (@params_names) {
462         if ($name =~ /^Filter_patron_attr\.(.*)$/) {
463             my $code = $1;
464             my $value = $input->param($name);
465             $attr{$code} = $value;
466         }
467     }
468
469     return \%attr;
470 }
471
472
473 sub patron_attributes_form {
474     my $template = shift;
475
476     my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
477     my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
478
479     my %items_by_class;
480     while ( my $attr_type = $attribute_types->next ) {
481         # TODO The following can be simplified easily
482         my $entry = {
483             class             => $attr_type->class(),
484             code              => $attr_type->code(),
485             description       => $attr_type->description(),
486             repeatable        => $attr_type->repeatable(),
487             category          => $attr_type->authorised_value_category(),
488             category_code     => $attr_type->category_code(),
489         };
490
491         my $newentry = { %$entry };
492         if ($attr_type->authorised_value_category()) {
493             $newentry->{use_dropdown} = 1;
494             $newentry->{auth_val_loop} = GetAuthorisedValues(
495                 $attr_type->authorised_value_category()
496             );
497         }
498         push @{ $items_by_class{ $attr_type->class() } }, $newentry;
499     }
500
501     my @attribute_loop;
502     foreach my $class ( sort keys %items_by_class ) {
503         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
504         my $lib = $av->count ? $av->next->lib : $class;
505         push @attribute_loop, {
506             class => $class,
507             items => $items_by_class{$class},
508             lib   => $lib,
509         };
510     }
511
512     $template->param(patron_attributes => \@attribute_loop);
513
514 }