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>.
23 use C4::Auth qw( get_template_and_user );
25 use C4::Koha qw( GetAuthorisedValues );
26 use C4::Output qw( output_html_with_http_headers );
27 use C4::Reports qw( GetDelimiterChoices );
29 use Koha::AuthorisedValues;
30 use Koha::DateUtils qw( dt_from_string output_pref );
32 use Koha::Patron::Attribute::Types;
33 use Koha::Patron::Categories;
35 use Date::Calc qw( Add_Delta_YM Today );
39 plugin that shows a stats on borrowers
46 my $do_it=$input->param('do_it');
47 my $fullreportname = "reports/borrowers_stats.tt";
48 my $line = $input->param("Line");
49 my $column = $input->param("Column");
50 my @filters = $input->multi_param("Filter");
51 $filters[3] = eval { output_pref( { dt => dt_from_string( $filters[3]), dateonly => 1, dateformat => 'iso' } ); }
53 $filters[4] = eval { output_pref ({ dt => dt_from_string( $filters[4]), dateonly => 1, dateformat => 'iso' } ); }
55 my $digits = $input->param("digits");
56 our $period = $input->param("period");
57 my $borstat = $input->param("status");
58 my $borstat1 = $input->param("activity");
59 my $output = $input->param("output");
60 my $basename = $input->param("basename");
61 our $sep = $input->param("sep");
62 $sep = "\t" if ($sep and $sep eq 'tabulation');
64 my ($template, $borrowernumber, $cookie)
65 = get_template_and_user({template_name => $fullreportname,
68 flagsrequired => {reports => '*'},
70 $template->param(do_it => $do_it);
73 if (C4::Context->preference('ExtendedPatronAttributes')) {
74 $attributes = parse_extended_patron_attributes($input);
76 my $results = calculate($line, $column, $digits, $borstat,$borstat1 ,\@filters, $attributes);
77 if ($output eq "screen"){
78 $template->param(mainloop => $results);
79 output_html_with_http_headers $input, $cookie, $template->output;
81 print $input->header(-type => 'application/vnd.sun.xml.calc',
83 -name => "$basename.csv",
84 -attachment => "$basename.csv");
85 my $cols = @$results[0]->{loopcol};
86 my $lines = @$results[0]->{looprow};
87 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
88 foreach my $col ( @$cols ) {
89 print $col->{coltitle}.$sep;
92 foreach my $line ( @$lines ) {
93 my $x = $line->{loopcell};
94 print $line->{rowtitle}.$sep;
95 foreach my $cell (@$x) {
96 print $cell->{value}.$sep;
98 print $line->{totalrow};
102 $cols = @$results[0]->{loopfooter};
103 foreach my $col ( @$cols ) {
104 print $sep.$col->{totalcol};
106 print $sep.@$results[0]->{total};
108 exit; # exit after do_it, regardless
110 my $dbh = C4::Context->dbh;
112 my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']});
113 $template->param( patron_categories => $patron_categories );
114 $req = $dbh->prepare("SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode");
116 $template->param( ZIP_LOOP => $req->fetchall_arrayref({}));
117 $req = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' ORDER BY lib");
119 $template->param( SORT1_LOOP => $req->fetchall_arrayref({}));
120 $req = $dbh->prepare("SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort2 <> '' ORDER BY sort2 LIMIT 200");
121 # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destroy DB performance.
123 $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
125 my $CGIextChoice = ( 'CSV' ); # FIXME translation
126 my $CGIsepChoice=GetDelimiterChoices;
128 CGIextChoice => $CGIextChoice,
129 CGIsepChoice => $CGIsepChoice,
131 if (C4::Context->preference('ExtendedPatronAttributes')) {
132 patron_attributes_form($template);
135 output_html_with_http_headers $input, $cookie, $template->output;
138 my ($line, $column, $digits, $status, $activity, $filters, $attr_filters) = @_;
148 my $dbh = C4::Context->dbh;
151 my @valid_names = qw(categorycode zipcode branchcode sex sort1 sort2);
152 if ($line =~ /^patron_attr\.(.*)/) {
153 my $attribute_type = $1;
154 return unless Koha::Patron::Attribute::Types->find($attribute_type);
156 return unless (grep { $_ eq $line } @valid_names);
158 if ($column =~ /^patron_attr\.(.*)/) {
159 my $attribute_type = $1;
160 return unless Koha::Patron::Attribute::Types->find($attribute_type);
162 return unless (grep { $_ eq $column } @valid_names);
164 return if ($digits and $digits !~ /^\d+$/);
165 return if ($status and (grep { $_ eq $status } qw(debarred gonenoaddress lost)) == 0);
166 return if ($activity and (grep { $_ eq $activity } qw(active nonactive)) == 0);
170 if ( $line =~ /categorycode/ ) { $linefilter = @$filters[0]; }
171 elsif ( $line =~ /zipcode/ ) { $linefilter = @$filters[1]; }
172 elsif ( $line =~ /branchcode/ ) { $linefilter = @$filters[2]; }
173 elsif ( $line =~ /sex/ ) { $linefilter = @$filters[5]; }
174 elsif ( $line =~ /sort1/ ) { $linefilter = @$filters[6]; }
175 elsif ( $line =~ /sort2/ ) { $linefilter = @$filters[7]; }
176 elsif ( $line =~ /^patron_attr\.(.*)$/ ) { $linefilter = $attr_filters->{$1}; }
177 else { $linefilter = ''; }
180 if ( $column =~ /categorycode/ ) { $colfilter = @$filters[0]; }
181 elsif ( $column =~ /zipcode/ ) { $colfilter = @$filters[1]; }
182 elsif ( $column =~ /branchcode/) { $colfilter = @$filters[2]; }
183 elsif ( $column =~ /sex/) { $colfilter = @$filters[5]; }
184 elsif ( $column =~ /sort1/) { $colfilter = @$filters[6]; }
185 elsif ( $column =~ /sort2/) { $colfilter = @$filters[7]; }
186 elsif ( $column =~ /^patron_attr\.(.*)$/) { $colfilter = $attr_filters->{$1}; }
187 else { $colfilter = ''; }
190 foreach my $i (0 .. scalar @$filters) {
192 if ( @$filters[$i] ) {
193 if ($i == 3 or $i == 4) {
194 $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
195 if ( @$filters[$i] );
197 $cell{filter} = @$filters[$i];
200 if ( $i == 0) { $cell{crit} = "Cat code"; }
201 elsif ( $i == 1 ) { $cell{crit} = "ZIP/Postal code"; }
202 elsif ( $i == 2 ) { $cell{crit} = "Branch code"; }
204 $i == 4 ) { $cell{crit} = "Date of birth"; }
205 elsif ( $i == 5 ) { $cell{crit} = "Sex"; }
206 elsif ( $i == 6 ) { $cell{crit} = "Sort1"; }
207 elsif ( $i == 7 ) { $cell{crit} = "Sort2"; }
208 else { $cell{crit} = "Unknown"; }
210 push @loopfilter, \%cell;
213 foreach my $type (keys %$attr_filters) {
214 if($attr_filters->{$type}) {
216 crit => "Attribute $type",
217 filter => $attr_filters->{$type}
222 my @branchcodes = map { $_->branchcode } Koha::Libraries->search;
223 ($status ) and push @loopfilter,{crit=>"Status", filter=>$status };
224 ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
226 my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
227 my $newperioddate=$period_year."-".$period_month."-".$period_day;
231 my $line_attribute_type;
232 if ($line =~/^patron_attr\.(.*)$/) {
233 $line_attribute_type = $1;
234 $line = 'borrower_attributes.attribute';
237 if (($line =~/zipcode/) and ($digits)) {
238 $linefield = "left($line,$digits)";
242 my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']});
245 my @strparams; # bind parameters for the query
246 if ($line_attribute_type) {
247 $strsth = "SELECT distinct attribute FROM borrower_attributes
248 WHERE attribute IS NOT NULL AND code=?";
249 push @strparams, $line_attribute_type;
251 $strsth = "SELECT distinctrow $linefield FROM borrowers
252 WHERE $line IS NOT NULL ";
255 $linefilter =~ s/\*/%/g;
257 $strsth .= " AND $linefield LIKE ? " ;
258 push @strparams, $linefilter;
260 $strsth .= " AND $status='1' " if ($status);
261 $strsth .=" order by $linefield";
263 my $sth = $dbh->prepare($strsth);
264 $sth->execute(@strparams);
265 while (my ($celvalue) = $sth->fetchrow) {
268 $cell{rowtitle} = $celvalue;
269 $cell{rowtitle_display} = ($patron_categories->find($celvalue)->description || "$celvalue\*") if ($line eq 'categorycode');
272 push @loopline, \%cell;
278 my $column_attribute_type;
279 if ($column =~/^patron_attr.(.*)$/) {
280 $column_attribute_type = $1;
281 $column = 'borrower_attributes.attribute';
284 if (($column =~/zipcode/) and ($digits)) {
285 $colfield = "left($column,$digits)";
291 my @strparams2; # bind parameters for the query
292 if ($column_attribute_type) {
293 $strsth2 = "SELECT DISTINCT attribute FROM borrower_attributes
294 WHERE attribute IS NOT NULL AND code=?";
295 push @strparams2, $column_attribute_type;
297 $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
298 WHERE $column IS NOT NULL";
302 $colfilter =~ s/\*/%/g;
303 $strsth2 .= " AND $colfield LIKE ? ";
304 push @strparams2, $colfield;
306 $strsth2 .= " AND $status='1' " if ($status);
308 $strsth2 .= " order by $colfield";
309 my $sth2 = $dbh->prepare($strsth2);
310 $sth2->execute(@strparams2);
311 while (my ($celvalue) = $sth2->fetchrow) {
313 if (defined $celvalue) {
314 $cell{coltitle} = $celvalue;
315 # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
316 $cell{coltitle_display} = $patron_categories->find($celvalue)->description if ($column eq 'categorycode');
318 push @loopcol, \%cell;
322 #Initialization of cell values.....
325 foreach my $row (@loopline) {
326 foreach my $col ( @loopcol ) {
327 my $rowtitle = $row->{rowtitle} // '';
328 my $coltitle = $row->{coltitle} // '';
329 $table{$rowtitle}->{$coltitle} = 0;
331 $row->{rowtitle} ||= '';
332 $table{$row->{rowtitle}}->{totalrow}=0;
333 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
336 # preparing calculation
339 $strcalc = "SELECT ";
340 if ($line_attribute_type) {
341 $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
343 $strcalc .= " $linefield, ";
345 if ($column_attribute_type) {
346 $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
348 $strcalc .= " $colfield, ";
351 $strcalc .= " COUNT(*) FROM borrowers ";
352 foreach my $type (keys %$attr_filters) {
354 ($line_attribute_type and $line_attribute_type eq $type)
355 or ($column_attribute_type and $column_attribute_type eq $type)
356 or ($attr_filters->{$type})
358 $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
359 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
360 AND attribute_$type.code = " . $dbh->quote($type) . ") ";
363 $strcalc .= " WHERE 1 ";
365 @$filters[0]=~ s/\*/%/g if (@$filters[0]);
366 $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
367 @$filters[1]=~ s/\*/%/g if (@$filters[1]);
368 $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
369 @$filters[2]=~ s/\*/%/g if (@$filters[2]);
370 $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
371 @$filters[3]=~ s/\*/%/g if (@$filters[3]);
372 $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
373 @$filters[4]=~ s/\*/%/g if (@$filters[4]);
374 $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
375 @$filters[5]=~ s/\*/%/g if (@$filters[5]);
376 $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] );
377 @$filters[6]=~ s/\*/%/g if (@$filters[6]);
378 $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
379 @$filters[7]=~ s/\*/%/g if (@$filters[7]);
380 $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
382 foreach my $type (keys %$attr_filters) {
383 if($attr_filters->{$type}) {
384 my $filter = $attr_filters->{$type};
386 $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
389 $strcalc .= " AND borrowers.borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
390 $strcalc .= " AND borrowers.borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "' AND borrowernumber IS NOT NULL)" if ($activity eq 'nonactive');
391 $strcalc .= " AND $status='1' " if ($status);
393 $strcalc .= " GROUP BY ";
394 if ($line_attribute_type) {
395 $strcalc .= " line_attribute, ";
397 $strcalc .= " $linefield, ";
399 if ($column_attribute_type) {
400 $strcalc .= " column_attribute ";
402 $strcalc .= " $colfield ";
405 my $dbcalc = $dbh->prepare($strcalc);
406 (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
409 while (my ($row, $col, $value) = $dbcalc->fetchrow) {
410 # warn "filling table $row / $col / $value ";
411 $emptycol = 1 if (!defined($col));
412 $col = "zzEMPTY" if (!defined($col));
413 $row = "zzEMPTY" if (!defined($row));
415 $table{$row}->{$col}+=$value;
416 $table{$row}->{totalrow}+=$value;
417 $grantotal += $value;
420 push @loopcol,{coltitle => "NULL"} if ($emptycol);
422 foreach my $row (sort keys %table) {
424 #@loopcol ensures the order for columns is common with column titles
425 # and the number matches the number of columns
426 foreach my $col ( @loopcol ) {
427 my $coltitle = $col->{coltitle} // '';
428 $coltitle = $coltitle eq "NULL" ? "zzEMPTY" : $coltitle;
429 my $value =$table{$row}->{$coltitle};
430 push @loopcell, {value => $value};
433 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
434 'rowtitle_display' => $table{$row}->{rowtitle_display} || ($row eq "zzEMPTY" ? "NULL" : $row),
435 'loopcell' => \@loopcell,
436 'totalrow' => $table{$row}->{totalrow}
440 foreach my $col ( @loopcol ) {
442 foreach my $row ( @looprow ) {
443 my $rowtitle = $row->{rowtitle} // '';
444 $rowtitle = ($rowtitle eq "NULL") ? "zzEMPTY" : $rowtitle;
445 my $coltitle = $col->{coltitle} // '';
446 $coltitle = ($coltitle eq "NULL") ? "zzEMPTY" : $coltitle;
448 $total += $table{$rowtitle}->{$coltitle} || 0;
449 # warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
451 # warn "summ for column ".$col->{coltitle}." = ".$total;
452 push @loopfooter, {'totalcol' => $total};
456 # the header of the table
457 $globalline{loopfilter}=\@loopfilter;
458 # the core of the table
459 $globalline{looprow} = \@looprow;
460 $globalline{loopcol} = \@loopcol;
461 # # the foot (totals by borrower type)
462 $globalline{loopfooter} = \@loopfooter;
463 $globalline{total}= $grantotal;
464 $globalline{line} = ($line_attribute_type) ? $line_attribute_type : $line;
465 $globalline{column} = ($column_attribute_type) ? $column_attribute_type : $column;
466 push @mainloop,\%globalline;
470 sub parse_extended_patron_attributes {
473 my @params_names = $input->param;
475 foreach my $name (@params_names) {
476 if ($name =~ /^Filter_patron_attr\.(.*)$/) {
478 my $value = $input->param($name);
479 $attr{$code} = $value;
487 sub patron_attributes_form {
488 my $template = shift;
490 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
491 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
494 while ( my $attr_type = $attribute_types->next ) {
495 # TODO The following can be simplified easily
497 class => $attr_type->class(),
498 code => $attr_type->code(),
499 description => $attr_type->description(),
500 repeatable => $attr_type->repeatable(),
501 category => $attr_type->authorised_value_category(),
502 category_code => $attr_type->category_code(),
505 my $newentry = { %$entry };
506 if ($attr_type->authorised_value_category()) {
507 $newentry->{use_dropdown} = 1;
508 $newentry->{auth_val_loop} = GetAuthorisedValues(
509 $attr_type->authorised_value_category()
512 push @{ $items_by_class{ $attr_type->class() } }, $newentry;
516 foreach my $class ( sort keys %items_by_class ) {
517 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
518 my $lib = $av->count ? $av->next->lib : $class;
519 push @attribute_loop, {
521 items => $items_by_class{$class},
526 $template->param(patron_attributes => \@attribute_loop);