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>.
22 use List::MoreUtils qw/uniq/;
32 use Koha::AuthorisedValues;
35 use Koha::Patron::Attribute::Types;
36 use Koha::Patron::Categories;
45 plugin that shows a stats on borrowers
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' } ); }
59 $filters[4] = eval { output_pref ({ dt => dt_from_string( $filters[4]), dateonly => 1, dateformat => 'iso' } ); }
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');
70 my ($template, $borrowernumber, $cookie)
71 = get_template_and_user({template_name => $fullreportname,
74 flagsrequired => {reports => '*'},
76 $template->param(do_it => $do_it);
79 if (C4::Context->preference('ExtendedPatronAttributes')) {
80 $attributes = parse_extended_patron_attributes($input);
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;
87 print $input->header(-type => 'application/vnd.sun.xml.calc',
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;
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;
104 print $line->{totalrow};
108 $cols = @$results[0]->{loopfooter};
109 foreach my $col ( @$cols ) {
110 print $sep.$col->{totalcol};
112 print $sep.@$results[0]->{total};
114 exit; # exit after do_it, regardless
116 my $dbh = C4::Context->dbh;
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");
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");
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.
129 $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
131 my $CGIextChoice = ( 'CSV' ); # FIXME translation
132 my $CGIsepChoice=GetDelimiterChoices;
134 CGIextChoice => $CGIextChoice,
135 CGIsepChoice => $CGIsepChoice,
137 if (C4::Context->preference('ExtendedPatronAttributes')) {
138 patron_attributes_form($template);
141 output_html_with_http_headers $input, $cookie, $template->output;
144 my ($line, $column, $digits, $status, $activity, $filters, $attr_filters) = @_;
154 my $dbh = C4::Context->dbh;
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);
162 return unless (grep { $_ eq $line } @valid_names);
164 if ($column =~ /^patron_attr\.(.*)/) {
165 my $attribute_type = $1;
166 return unless Koha::Patron::Attribute::Types->find($attribute_type);
168 return unless (grep { $_ eq $column } @valid_names);
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);
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 = ''; }
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 = ''; }
196 foreach my $i (0 .. scalar @$filters) {
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] );
203 $cell{filter} = @$filters[$i];
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"; }
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"; }
216 push @loopfilter, \%cell;
219 foreach my $type (keys %$attr_filters) {
220 if($attr_filters->{$type}) {
222 crit => "Attribute $type",
223 filter => $attr_filters->{$type}
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};
232 my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
233 my $newperioddate=$period_year."-".$period_month."-".$period_day;
237 my $line_attribute_type;
238 if ($line =~/^patron_attr\.(.*)$/) {
239 $line_attribute_type = $1;
240 $line = 'borrower_attributes.attribute';
243 if (($line =~/zipcode/) and ($digits)) {
244 $linefield = "left($line,$digits)";
248 my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']});
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;
257 $strsth = "SELECT distinctrow $linefield FROM borrowers
258 WHERE $line IS NOT NULL ";
261 $linefilter =~ s/\*/%/g;
263 $strsth .= " AND $linefield LIKE ? " ;
264 push @strparams, $linefilter;
266 $strsth .= " AND $status='1' " if ($status);
267 $strsth .=" order by $linefield";
269 my $sth = $dbh->prepare($strsth);
270 $sth->execute(@strparams);
271 while (my ($celvalue) = $sth->fetchrow) {
274 $cell{rowtitle} = $celvalue;
275 $cell{rowtitle_display} = ($patron_categories->find($celvalue)->description || "$celvalue\*") if ($line eq 'categorycode');
278 push @loopline, \%cell;
284 my $column_attribute_type;
285 if ($column =~/^patron_attr.(.*)$/) {
286 $column_attribute_type = $1;
287 $column = 'borrower_attributes.attribute';
290 if (($column =~/zipcode/) and ($digits)) {
291 $colfield = "left($column,$digits)";
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;
303 $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
304 WHERE $column IS NOT NULL";
308 $colfilter =~ s/\*/%/g;
309 $strsth2 .= " AND $colfield LIKE ? ";
310 push @strparams2, $colfield;
312 $strsth2 .= " AND $status='1' " if ($status);
314 $strsth2 .= " order by $colfield";
315 my $sth2 = $dbh->prepare($strsth2);
316 $sth2->execute(@strparams2);
317 while (my ($celvalue) = $sth2->fetchrow) {
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');
324 push @loopcol, \%cell;
328 #Initialization of cell values.....
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;
337 $row->{rowtitle} ||= '';
338 $table{$row->{rowtitle}}->{totalrow}=0;
339 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
342 # preparing calculation
345 $strcalc = "SELECT ";
346 if ($line_attribute_type) {
347 $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
349 $strcalc .= " $linefield, ";
351 if ($column_attribute_type) {
352 $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
354 $strcalc .= " $colfield, ";
357 $strcalc .= " COUNT(*) FROM borrowers ";
358 foreach my $type (keys %$attr_filters) {
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})
364 $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
365 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
366 AND attribute_$type.code = " . $dbh->quote($type) . ") ";
369 $strcalc .= " WHERE 1 ";
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] );
388 foreach my $type (keys %$attr_filters) {
389 if($attr_filters->{$type}) {
390 my $filter = $attr_filters->{$type};
392 $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
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);
399 $strcalc .= " GROUP BY ";
400 if ($line_attribute_type) {
401 $strcalc .= " line_attribute, ";
403 $strcalc .= " $linefield, ";
405 if ($column_attribute_type) {
406 $strcalc .= " column_attribute ";
408 $strcalc .= " $colfield ";
411 my $dbcalc = $dbh->prepare($strcalc);
412 (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
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));
421 $table{$row}->{$col}+=$value;
422 $table{$row}->{totalrow}+=$value;
423 $grantotal += $value;
426 push @loopcol,{coltitle => "NULL"} if ($emptycol);
428 foreach my $row (sort keys %table) {
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};
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}
446 foreach my $col ( @loopcol ) {
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;
454 $total += $table{$rowtitle}->{$coltitle} || 0;
455 # warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
457 # warn "summ for column ".$col->{coltitle}." = ".$total;
458 push @loopfooter, {'totalcol' => $total};
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;
476 sub parse_extended_patron_attributes {
479 my @params_names = $input->param;
481 foreach my $name (@params_names) {
482 if ($name =~ /^Filter_patron_attr\.(.*)$/) {
484 my $value = $input->param($name);
485 $attr{$code} = $value;
493 sub patron_attributes_form {
494 my $template = shift;
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);
500 while ( my $attr_type = $attribute_types->next ) {
501 # TODO The following can be simplified easily
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(),
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()
518 push @{ $items_by_class{ $attr_type->class() } }, $newentry;
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, {
527 items => $items_by_class{$class},
532 $template->param(patron_attributes => \@attribute_loop);