Bug 14333: Update MARC21 frameworks to Update No. 20 and 21
[koha.git] / reports / borrowers_stats.pl
blob9ac0cac54927d04766399a74cc2761b61ea5c142
1 #!/usr/bin/perl
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
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.
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.
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>.
20 use Modern::Perl;
21 use CGI qw ( -utf8 );
22 use List::MoreUtils qw/uniq/;
24 use C4::Auth;
25 use C4::Context;
26 use C4::Branch; # GetBranches
27 use C4::Koha;
28 use Koha::DateUtils;
29 use C4::Acquisition;
30 use C4::Output;
31 use C4::Reports;
32 use C4::Circulation;
33 use C4::Members::AttributeTypes;
34 use C4::Dates qw/format_date format_date_in_iso/;
35 use Date::Calc qw(
36 Today
37 Add_Delta_YM
40 =head1 NAME
42 plugin that shows a stats on borrowers
44 =head1 DESCRIPTION
46 =over 2
48 =cut
50 my $input = new CGI;
51 my $do_it=$input->param('do_it');
52 my $fullreportname = "reports/borrowers_stats.tt";
53 my $line = $input->param("Line");
54 my $column = $input->param("Column");
55 my @filters = $input->param("Filter");
56 $filters[3] = eval { output_pref( { dt => dt_from_string( $filters[3]), dateonly => 1, dateformat => 'iso' } ); }
57 if ( $filters[3] );
58 $filters[4] = eval { output_pref ({ dt => dt_from_string( $filters[4]), dateonly => 1, dateformat => 'iso' } ); }
59 if ( $filters[4] );
60 my $digits = $input->param("digits");
61 our $period = $input->param("period");
62 my $borstat = $input->param("status");
63 my $borstat1 = $input->param("activity");
64 my $output = $input->param("output");
65 my $basename = $input->param("basename");
66 our $sep = $input->param("sep");
67 $sep = "\t" if ($sep and $sep eq 'tabulation');
68 my $selected_branch; # = $input->param("?");
70 our $branches = GetBranches;
72 my ($template, $borrowernumber, $cookie)
73 = get_template_and_user({template_name => $fullreportname,
74 query => $input,
75 type => "intranet",
76 authnotrequired => 0,
77 flagsrequired => {reports => '*'},
78 debug => 1,
79 });
80 $template->param(do_it => $do_it);
81 if ($do_it) {
82 my $attributes;
83 if (C4::Context->preference('ExtendedPatronAttributes')) {
84 $attributes = parse_extended_patron_attributes($input);
86 my $results = calculate($line, $column, $digits, $borstat,$borstat1 ,\@filters, $attributes);
87 if ($output eq "screen"){
88 $template->param(mainloop => $results);
89 output_html_with_http_headers $input, $cookie, $template->output;
90 } else {
91 print $input->header(-type => 'application/vnd.sun.xml.calc',
92 -encoding => 'utf-8',
93 -name => "$basename.csv",
94 -attachment => "$basename.csv");
95 my $cols = @$results[0]->{loopcol};
96 my $lines = @$results[0]->{looprow};
97 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
98 foreach my $col ( @$cols ) {
99 print $col->{coltitle}.$sep;
101 print "Total\n";
102 foreach my $line ( @$lines ) {
103 my $x = $line->{loopcell};
104 print $line->{rowtitle}.$sep;
105 foreach my $cell (@$x) {
106 print $cell->{value}.$sep;
108 print $line->{totalrow};
109 print "\n";
111 print "TOTAL";
112 $cols = @$results[0]->{loopfooter};
113 foreach my $col ( @$cols ) {
114 print $sep.$col->{totalcol};
116 print $sep.@$results[0]->{total};
118 exit; # exit after do_it, regardless
119 } else {
120 my $dbh = C4::Context->dbh;
121 my $req;
122 $template->param( CAT_LOOP => &catcode_aref);
123 my @branchloop;
124 foreach (sort {$branches->{$a}->{branchname} cmp $branches->{$b}->{branchname}} keys %$branches) {
125 my $line = {branchcode => $_, branchname => $branches->{$_}->{branchname} || 'UNKNOWN'};
126 $line->{selected} = 'selected' if ($selected_branch and $selected_branch eq $_);
127 push @branchloop, $line;
129 $template->param(BRANCH_LOOP => \@branchloop);
130 $req = $dbh->prepare("SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode");
131 $req->execute;
132 $template->param( ZIP_LOOP => $req->fetchall_arrayref({}));
133 $req = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' ORDER BY lib");
134 $req->execute;
135 $template->param( SORT1_LOOP => $req->fetchall_arrayref({}));
136 $req = $dbh->prepare("SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort2 <> '' ORDER BY sort2 LIMIT 200");
137 # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destory DB performance.
138 $req->execute;
139 $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
141 my $CGIextChoice = ( 'CSV' ); # FIXME translation
142 my $CGIsepChoice=GetDelimiterChoices;
143 $template->param(
144 CGIextChoice => $CGIextChoice,
145 CGIsepChoice => $CGIsepChoice,
147 if (C4::Context->preference('ExtendedPatronAttributes')) {
148 $template->param(ExtendedPatronAttributes => 1);
149 patron_attributes_form($template);
152 output_html_with_http_headers $input, $cookie, $template->output;
154 sub catcode_aref {
155 my $req = C4::Context->dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
156 $req->execute;
157 return $req->fetchall_arrayref({});
159 sub catcodes_hash {
160 my %cathash;
161 my $catcodes = &catcode_aref;
162 foreach (@$catcodes) {
163 $cathash{$_->{categorycode}} = ($_->{description} || 'NO_DESCRIPTION') . " ($_->{categorycode})";
165 return %cathash;
168 sub calculate {
169 my ($line, $column, $digits, $status, $activity, $filters, $attr_filters) = @_;
171 my @mainloop;
172 my @loopfooter;
173 my @loopcol;
174 my @loopline;
175 my @looprow;
176 my %globalline;
177 my $grantotal =0;
178 # extract parameters
179 my $dbh = C4::Context->dbh;
181 # check parameters
182 my @valid_names = qw(categorycode zipcode branchcode sex sort1 sort2);
183 my @attribute_types = C4::Members::AttributeTypes::GetAttributeTypes;
184 if ($line =~ /^patron_attr\.(.*)/) {
185 my $attribute_type = $1;
186 return unless (grep {$attribute_type eq $_->{code}} @attribute_types);
187 } else {
188 return unless (grep /^$line$/, @valid_names);
190 if ($column =~ /^patron_attr\.(.*)/) {
191 my $attribute_type = $1;
192 return unless (grep {$attribute_type eq $_->{code}} @attribute_types);
193 } else {
194 return unless (grep /^$column$/, @valid_names);
196 return if ($digits and $digits !~ /^\d+$/);
197 return if ($status and (grep /^$status$/, qw(debarred gonenoaddress lost)) == 0);
198 return if ($activity and (grep /^$activity$/, qw(active nonactive)) == 0);
200 # Filters
201 my $linefilter;
202 if ( $line =~ /categorycode/ ) { $linefilter = @$filters[0]; }
203 elsif ( $line =~ /zipcode/ ) { $linefilter = @$filters[1]; }
204 elsif ( $line =~ /branchcode/ ) { $linefilter = @$filters[2]; }
205 elsif ( $line =~ /sex/ ) { $linefilter = @$filters[5]; }
206 elsif ( $line =~ /sort1/ ) { $linefilter = @$filters[6]; }
207 elsif ( $line =~ /sort2/ ) { $linefilter = @$filters[7]; }
208 elsif ( $line =~ /^patron_attr\.(.*)$/ ) { $linefilter = $attr_filters->{$1}; }
209 else { $linefilter = ''; }
211 my $colfilter;
212 if ( $column =~ /categorycode/ ) { $colfilter = @$filters[0]; }
213 elsif ( $column =~ /zipcode/ ) { $colfilter = @$filters[1]; }
214 elsif ( $column =~ /branchcode/) { $colfilter = @$filters[2]; }
215 elsif ( $column =~ /sex/) { $colfilter = @$filters[5]; }
216 elsif ( $column =~ /sort1/) { $colfilter = @$filters[6]; }
217 elsif ( $column =~ /sort2/) { $colfilter = @$filters[7]; }
218 elsif ( $column =~ /^patron_attr\.(.*)$/) { $colfilter = $attr_filters->{$1}; }
219 else { $colfilter = ''; }
221 my @loopfilter;
222 foreach my $i (0 .. scalar @$filters) {
223 my %cell;
224 if ( @$filters[$i] ) {
225 if ($i == 3 or $i == 4) {
226 $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
227 if ( @$filters[$i] );
228 } else {
229 $cell{filter} = @$filters[$i];
232 if ( $i == 0) { $cell{crit} = "Cat code"; }
233 elsif ( $i == 1 ) { $cell{crit} = "Zip code"; }
234 elsif ( $i == 2 ) { $cell{crit} = "Branch code"; }
235 elsif ( $i == 3 ||
236 $i == 4 ) { $cell{crit} = "Date of birth"; }
237 elsif ( $i == 5 ) { $cell{crit} = "Sex"; }
238 elsif ( $i == 6 ) { $cell{crit} = "Sort1"; }
239 elsif ( $i == 7 ) { $cell{crit} = "Sort2"; }
240 else { $cell{crit} = "Unknown"; }
242 push @loopfilter, \%cell;
245 foreach my $type (keys %$attr_filters) {
246 if($attr_filters->{$type}) {
247 push @loopfilter, {
248 crit => "Attribute $type",
249 filter => $attr_filters->{$type}
254 ($status ) and push @loopfilter,{crit=>"Status", filter=>$status };
255 ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
256 push @loopfilter,{debug=>1, crit=>"Branches",filter=>join(" ", sort keys %$branches)};
257 push @loopfilter,{debug=>1, crit=>"(line, column)", filter=>"($line,$column)"};
258 # year of activity
259 my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
260 my $newperioddate=$period_year."-".$period_month."-".$period_day;
261 # 1st, loop rows.
262 my $linefield;
264 my $line_attribute_type;
265 if ($line =~/^patron_attr\.(.*)$/) {
266 $line_attribute_type = $1;
267 $line = 'borrower_attributes.attribute';
270 if (($line =~/zipcode/) and ($digits)) {
271 $linefield = "left($line,$digits)";
272 } else {
273 $linefield = $line;
276 my %cathash = ($line eq 'categorycode' or $column eq 'categorycode') ? &catcodes_hash : ();
277 push @loopfilter, {debug=>1, crit=>"\%cathash", filter=>join(", ", map {$cathash{$_}} sort keys %cathash)};
279 my $strsth;
280 my @strparams; # bind parameters for the query
281 if ($line_attribute_type) {
282 $strsth = "SELECT distinct attribute FROM borrower_attributes
283 WHERE attribute IS NOT NULL AND code=?";
284 push @strparams, $line_attribute_type;
285 } else {
286 $strsth = "SELECT distinctrow $linefield FROM borrowers
287 WHERE $line IS NOT NULL ";
290 $linefilter =~ s/\*/%/g;
291 if ( $linefilter ) {
292 $strsth .= " AND $linefield LIKE ? " ;
293 push @strparams, $linefilter;
295 $strsth .= " AND $status='1' " if ($status);
296 $strsth .=" order by $linefield";
298 push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth};
299 my $sth = $dbh->prepare($strsth);
300 $sth->execute(@strparams);
301 while (my ($celvalue) = $sth->fetchrow) {
302 my %cell;
303 if ($celvalue) {
304 $cell{rowtitle} = $celvalue;
305 # $cell{rowtitle_display} = ($linefield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
306 $cell{rowtitle_display} = ($cathash{$celvalue} || "$celvalue\*") if ($line eq 'categorycode');
308 $cell{totalrow} = 0;
309 push @loopline, \%cell;
312 # 2nd, loop cols.
313 my $colfield;
315 my $column_attribute_type;
316 if ($column =~/^patron_attr.(.*)$/) {
317 $column_attribute_type = $1;
318 $column = 'borrower_attributes.attribute';
321 if (($column =~/zipcode/) and ($digits)) {
322 $colfield = "left($column,$digits)";
323 } else {
324 $colfield = $column;
327 my $strsth2;
328 my @strparams2; # bind parameters for the query
329 if ($column_attribute_type) {
330 $strsth2 = "SELECT DISTINCT attribute FROM borrower_attributes
331 WHERE attribute IS NOT NULL AND code=?";
332 push @strparams2, $column_attribute_type;
333 } else {
334 $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
335 WHERE $column IS NOT NULL";
338 if ($colfilter) {
339 $colfilter =~ s/\*/%/g;
340 $strsth2 .= " AND $colfield LIKE ? ";
341 push @strparams2, $colfield;
343 $strsth2 .= " AND $status='1' " if ($status);
345 $strsth2 .= " order by $colfield";
346 push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth2};
347 my $sth2 = $dbh->prepare($strsth2);
348 $sth2->execute(@strparams2);
349 while (my ($celvalue) = $sth2->fetchrow) {
350 my %cell;
351 if (defined $celvalue) {
352 $cell{coltitle} = $celvalue;
353 # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
354 $cell{coltitle_display} = $cathash{$celvalue} if ($column eq 'categorycode');
356 push @loopcol, \%cell;
359 my $i=0;
360 #Initialization of cell values.....
361 my %table;
362 # warn "init table";
363 foreach my $row (@loopline) {
364 foreach my $col ( @loopcol ) {
365 my $rowtitle = $row->{rowtitle} // '';
366 my $coltitle = $row->{coltitle} // '';
367 $table{$rowtitle}->{$coltitle} = 0;
369 $row->{rowtitle} ||= '';
370 $table{$row->{rowtitle}}->{totalrow}=0;
371 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
374 # preparing calculation
375 my $strcalc;
376 my @calcparams;
377 $strcalc = "SELECT ";
378 if ($line_attribute_type) {
379 $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
380 } else {
381 $strcalc .= " $linefield, ";
383 if ($column_attribute_type) {
384 $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
385 } else {
386 $strcalc .= " $colfield, ";
389 $strcalc .= " COUNT(*) FROM borrowers ";
390 foreach my $type (keys %$attr_filters) {
391 if (
392 ($line_attribute_type and $line_attribute_type eq $type)
393 or ($column_attribute_type and $column_attribute_type eq $type)
394 or ($attr_filters->{$type})
396 $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
397 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
398 AND attribute_$type.code = " . $dbh->quote($type) . ") ";
401 $strcalc .= " WHERE 1 ";
403 @$filters[0]=~ s/\*/%/g if (@$filters[0]);
404 $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
405 @$filters[1]=~ s/\*/%/g if (@$filters[1]);
406 $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
407 @$filters[2]=~ s/\*/%/g if (@$filters[2]);
408 $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
409 @$filters[3]=~ s/\*/%/g if (@$filters[3]);
410 $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
411 @$filters[4]=~ s/\*/%/g if (@$filters[4]);
412 $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
413 @$filters[5]=~ s/\*/%/g if (@$filters[5]);
414 $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] );
415 @$filters[6]=~ s/\*/%/g if (@$filters[6]);
416 $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
417 @$filters[7]=~ s/\*/%/g if (@$filters[7]);
418 $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
420 foreach my $type (keys %$attr_filters) {
421 if($attr_filters->{$type}) {
422 my $filter = $attr_filters->{$type};
423 $filter =~ s/\*/%/g;
424 $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
427 $strcalc .= " AND borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
428 $strcalc .= " AND borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'nonactive');
429 $strcalc .= " AND $status='1' " if ($status);
431 $strcalc .= " GROUP BY ";
432 if ($line_attribute_type) {
433 $strcalc .= " line_attribute, ";
434 } else {
435 $strcalc .= " $linefield, ";
437 if ($column_attribute_type) {
438 $strcalc .= " column_attribute ";
439 } else {
440 $strcalc .= " $colfield ";
443 push @loopfilter, {sql=>1, crit=>"Query", filter=>$strcalc};
444 my $dbcalc = $dbh->prepare($strcalc);
445 (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
447 my $emptycol;
448 while (my ($row, $col, $value) = $dbcalc->fetchrow) {
449 # warn "filling table $row / $col / $value ";
450 $emptycol = 1 if (!defined($col));
451 $col = "zzEMPTY" if (!defined($col));
452 $row = "zzEMPTY" if (!defined($row));
454 $table{$row}->{$col}+=$value;
455 $table{$row}->{totalrow}+=$value;
456 $grantotal += $value;
459 push @loopcol,{coltitle => "NULL"} if ($emptycol);
461 foreach my $row (sort keys %table) {
462 my @loopcell;
463 #@loopcol ensures the order for columns is common with column titles
464 # and the number matches the number of columns
465 foreach my $col ( @loopcol ) {
466 my $coltitle = $col->{coltitle} // '';
467 $coltitle = $coltitle eq "NULL" ? "zzEMPTY" : $coltitle;
468 my $value =$table{$row}->{$coltitle};
469 push @loopcell, {value => $value};
471 push @looprow,{
472 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
473 'rowtitle_display' => $table{$row}->{rowtitle_display} || ($row eq "zzEMPTY" ? "NULL" : $row),
474 'loopcell' => \@loopcell,
475 'totalrow' => $table{$row}->{totalrow}
479 foreach my $col ( @loopcol ) {
480 my $total=0;
481 foreach my $row ( @looprow ) {
482 my $rowtitle = $row->{rowtitle} // '';
483 $rowtitle = ($rowtitle eq "NULL") ? "zzEMPTY" : $rowtitle;
484 my $coltitle = $col->{coltitle} // '';
485 $coltitle = ($coltitle eq "NULL") ? "zzEMPTY" : $coltitle;
487 $total += $table{$rowtitle}->{$coltitle} || 0;
488 # warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
490 # warn "summ for column ".$col->{coltitle}." = ".$total;
491 push @loopfooter, {'totalcol' => $total};
495 # the header of the table
496 $globalline{loopfilter}=\@loopfilter;
497 # the core of the table
498 $globalline{looprow} = \@looprow;
499 $globalline{loopcol} = \@loopcol;
500 # # the foot (totals by borrower type)
501 $globalline{loopfooter} = \@loopfooter;
502 $globalline{total}= $grantotal;
503 $globalline{line} = ($line_attribute_type) ? $line_attribute_type : $line;
504 $globalline{column} = ($column_attribute_type) ? $column_attribute_type : $column;
505 push @mainloop,\%globalline;
506 return \@mainloop;
509 sub parse_extended_patron_attributes {
510 my ($input) = @_;
512 my @params_names = $input->param;
513 my %attr;
514 foreach my $name (@params_names) {
515 if ($name =~ /^Filter_patron_attr\.(.*)$/) {
516 my $code = $1;
517 my $value = $input->param($name);
518 $attr{$code} = $value;
522 return \%attr;
526 sub patron_attributes_form {
527 my $template = shift;
529 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
531 my %items_by_class;
532 foreach my $type (@types) {
533 my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
534 my $entry = {
535 class => $attr_type->class(),
536 code => $attr_type->code(),
537 description => $attr_type->description(),
538 repeatable => $attr_type->repeatable(),
539 category => $attr_type->authorised_value_category(),
540 category_code => $attr_type->category_code(),
543 my $newentry = { %$entry };
544 if ($attr_type->authorised_value_category()) {
545 $newentry->{use_dropdown} = 1;
546 $newentry->{auth_val_loop} = GetAuthorisedValues(
547 $attr_type->authorised_value_category()
550 push @{ $items_by_class{ $attr_type->class() } }, $newentry;
553 my @attribute_loop;
554 foreach my $class ( sort keys %items_by_class ) {
555 my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
556 push @attribute_loop, {
557 class => $class,
558 items => $items_by_class{$class},
559 lib => $lib,
563 $template->param(patron_attributes => \@attribute_loop);