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