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;
31 use Koha::Patron::Attribute::Types;
32 use Koha::Patron::Categories;
34 use Date::Calc qw( Add_Delta_YM Today );
38 plugin that shows a stats on borrowers
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"));
58 my ($template, $borrowernumber, $cookie)
59 = get_template_and_user({template_name => $fullreportname,
62 flagsrequired => {reports => '*'},
64 $template->param(do_it => $do_it);
67 if (C4::Context->preference('ExtendedPatronAttributes')) {
68 $attributes = parse_extended_patron_attributes($input);
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;
75 print $input->header(-type => 'application/vnd.sun.xml.calc',
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;
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;
92 print $line->{totalrow};
96 $cols = @$results[0]->{loopfooter};
97 foreach my $col ( @$cols ) {
98 print $sep.$col->{totalcol};
100 print $sep.@$results[0]->{total};
102 exit; # exit after do_it, regardless
104 my $dbh = C4::Context->dbh;
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");
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");
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.
117 $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
119 my $CGIextChoice = ( 'CSV' ); # FIXME translation
120 my $CGIsepChoice=GetDelimiterChoices;
122 CGIextChoice => $CGIextChoice,
123 CGIsepChoice => $CGIsepChoice,
125 if (C4::Context->preference('ExtendedPatronAttributes')) {
126 patron_attributes_form($template);
129 output_html_with_http_headers $input, $cookie, $template->output;
132 my ($line, $column, $digits, $status, $activity, $filters, $attr_filters) = @_;
142 my $dbh = C4::Context->dbh;
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);
150 return unless (grep { $_ eq $line } @valid_names);
152 if ($column =~ /^patron_attr\.(.*)/) {
153 my $attribute_type = $1;
154 return unless Koha::Patron::Attribute::Types->find($attribute_type);
156 return unless (grep { $_ eq $column } @valid_names);
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);
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 = ''; }
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 = ''; }
184 foreach my $i (0 .. scalar @$filters) {
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"; }
196 push @loopfilter, \%cell;
199 foreach my $type (keys %$attr_filters) {
200 if($attr_filters->{$type}) {
202 crit => "Attribute $type",
203 filter => $attr_filters->{$type}
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};
212 my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
213 my $newperioddate=$period_year."-".$period_month."-".$period_day;
217 my $line_attribute_type;
218 if ($line =~/^patron_attr\.(.*)$/) {
219 $line_attribute_type = $1;
220 $line = 'borrower_attributes.attribute';
223 if (($line =~/zipcode/) and ($digits)) {
224 $linefield = "left($line,$digits)";
228 my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']});
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;
237 $strsth = "SELECT distinctrow $linefield FROM borrowers
238 WHERE $line IS NOT NULL ";
241 $linefilter =~ s/\*/%/g;
243 $strsth .= " AND $linefield LIKE ? " ;
244 push @strparams, $linefilter;
246 $strsth .= " AND $status='1' " if ($status);
247 $strsth .=" order by $linefield";
249 my $sth = $dbh->prepare($strsth);
250 $sth->execute(@strparams);
251 while (my ($celvalue) = $sth->fetchrow) {
254 $cell{rowtitle} = $celvalue;
255 $cell{rowtitle_display} = ($patron_categories->find($celvalue)->description || "$celvalue\*") if ($line eq 'categorycode');
258 push @loopline, \%cell;
264 my $column_attribute_type;
265 if ($column =~/^patron_attr.(.*)$/) {
266 $column_attribute_type = $1;
267 $column = 'borrower_attributes.attribute';
270 if (($column =~/zipcode/) and ($digits)) {
271 $colfield = "left($column,$digits)";
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;
283 $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
284 WHERE $column IS NOT NULL";
288 $colfilter =~ s/\*/%/g;
289 $strsth2 .= " AND $colfield LIKE ? ";
290 push @strparams2, $colfield;
292 $strsth2 .= " AND $status='1' " if ($status);
294 $strsth2 .= " order by $colfield";
295 my $sth2 = $dbh->prepare($strsth2);
296 $sth2->execute(@strparams2);
297 while (my ($celvalue) = $sth2->fetchrow) {
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');
304 push @loopcol, \%cell;
308 #Initialization of cell values.....
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;
317 $row->{rowtitle} ||= '';
318 $table{$row->{rowtitle}}->{totalrow}=0;
319 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
322 # preparing calculation
325 $strcalc = "SELECT ";
326 if ($line_attribute_type) {
327 $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
329 $strcalc .= " $linefield, ";
331 if ($column_attribute_type) {
332 $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
334 $strcalc .= " $colfield, ";
337 $strcalc .= " COUNT(*) FROM borrowers ";
338 foreach my $type (keys %$attr_filters) {
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})
344 $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
345 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
346 AND attribute_$type.code = " . $dbh->quote($type) . ") ";
349 $strcalc .= " WHERE 1 ";
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] );
368 foreach my $type (keys %$attr_filters) {
369 if($attr_filters->{$type}) {
370 my $filter = $attr_filters->{$type};
372 $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
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);
379 $strcalc .= " GROUP BY ";
380 if ($line_attribute_type) {
381 $strcalc .= " line_attribute, ";
383 $strcalc .= " $linefield, ";
385 if ($column_attribute_type) {
386 $strcalc .= " column_attribute ";
388 $strcalc .= " $colfield ";
391 my $dbcalc = $dbh->prepare($strcalc);
392 (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
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));
401 $table{$row}->{$col}+=$value;
402 $table{$row}->{totalrow}+=$value;
403 $grantotal += $value;
406 push @loopcol,{coltitle => "NULL"} if ($emptycol);
408 foreach my $row (sort keys %table) {
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};
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}
426 foreach my $col ( @loopcol ) {
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;
434 $total += $table{$rowtitle}->{$coltitle} || 0;
435 # warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
437 # warn "summ for column ".$col->{coltitle}." = ".$total;
438 push @loopfooter, {'totalcol' => $total};
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;
456 sub parse_extended_patron_attributes {
459 my @params_names = $input->param;
461 foreach my $name (@params_names) {
462 if ($name =~ /^Filter_patron_attr\.(.*)$/) {
464 my $value = $input->param($name);
465 $attr{$code} = $value;
473 sub patron_attributes_form {
474 my $template = shift;
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);
480 while ( my $attr_type = $attribute_types->next ) {
481 # TODO The following can be simplified easily
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(),
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()
498 push @{ $items_by_class{ $attr_type->class() } }, $newentry;
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, {
507 items => $items_by_class{$class},
512 $template->param(patron_attributes => \@attribute_loop);