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 = C4::Context->csv_delimiter(scalar $input->param("sep"));
63 my ($template, $borrowernumber, $cookie)
64 = get_template_and_user({template_name => $fullreportname,
67 flagsrequired => {reports => '*'},
69 $template->param(do_it => $do_it);
72 if (C4::Context->preference('ExtendedPatronAttributes')) {
73 $attributes = parse_extended_patron_attributes($input);
75 my $results = calculate($line, $column, $digits, $borstat,$borstat1 ,\@filters, $attributes);
76 if ($output eq "screen"){
77 $template->param(mainloop => $results);
78 output_html_with_http_headers $input, $cookie, $template->output;
80 print $input->header(-type => 'application/vnd.sun.xml.calc',
82 -name => "$basename.csv",
83 -attachment => "$basename.csv");
84 my $cols = @$results[0]->{loopcol};
85 my $lines = @$results[0]->{looprow};
86 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
87 foreach my $col ( @$cols ) {
88 print $col->{coltitle}.$sep;
91 foreach my $line ( @$lines ) {
92 my $x = $line->{loopcell};
93 print $line->{rowtitle}.$sep;
94 foreach my $cell (@$x) {
95 print $cell->{value}.$sep;
97 print $line->{totalrow};
101 $cols = @$results[0]->{loopfooter};
102 foreach my $col ( @$cols ) {
103 print $sep.$col->{totalcol};
105 print $sep.@$results[0]->{total};
107 exit; # exit after do_it, regardless
109 my $dbh = C4::Context->dbh;
111 my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']});
112 $template->param( patron_categories => $patron_categories );
113 $req = $dbh->prepare("SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode");
115 $template->param( ZIP_LOOP => $req->fetchall_arrayref({}));
116 $req = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' ORDER BY lib");
118 $template->param( SORT1_LOOP => $req->fetchall_arrayref({}));
119 $req = $dbh->prepare("SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort2 <> '' ORDER BY sort2 LIMIT 200");
120 # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destroy DB performance.
122 $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
124 my $CGIextChoice = ( 'CSV' ); # FIXME translation
125 my $CGIsepChoice=GetDelimiterChoices;
127 CGIextChoice => $CGIextChoice,
128 CGIsepChoice => $CGIsepChoice,
130 if (C4::Context->preference('ExtendedPatronAttributes')) {
131 patron_attributes_form($template);
134 output_html_with_http_headers $input, $cookie, $template->output;
137 my ($line, $column, $digits, $status, $activity, $filters, $attr_filters) = @_;
147 my $dbh = C4::Context->dbh;
150 my @valid_names = qw(categorycode zipcode branchcode sex sort1 sort2);
151 if ($line =~ /^patron_attr\.(.*)/) {
152 my $attribute_type = $1;
153 return unless Koha::Patron::Attribute::Types->find($attribute_type);
155 return unless (grep { $_ eq $line } @valid_names);
157 if ($column =~ /^patron_attr\.(.*)/) {
158 my $attribute_type = $1;
159 return unless Koha::Patron::Attribute::Types->find($attribute_type);
161 return unless (grep { $_ eq $column } @valid_names);
163 return if ($digits and $digits !~ /^\d+$/);
164 return if ($status and (grep { $_ eq $status } qw(debarred gonenoaddress lost)) == 0);
165 return if ($activity and (grep { $_ eq $activity } qw(active nonactive)) == 0);
169 if ( $line =~ /categorycode/ ) { $linefilter = @$filters[0]; }
170 elsif ( $line =~ /zipcode/ ) { $linefilter = @$filters[1]; }
171 elsif ( $line =~ /branchcode/ ) { $linefilter = @$filters[2]; }
172 elsif ( $line =~ /sex/ ) { $linefilter = @$filters[5]; }
173 elsif ( $line =~ /sort1/ ) { $linefilter = @$filters[6]; }
174 elsif ( $line =~ /sort2/ ) { $linefilter = @$filters[7]; }
175 elsif ( $line =~ /^patron_attr\.(.*)$/ ) { $linefilter = $attr_filters->{$1}; }
176 else { $linefilter = ''; }
179 if ( $column =~ /categorycode/ ) { $colfilter = @$filters[0]; }
180 elsif ( $column =~ /zipcode/ ) { $colfilter = @$filters[1]; }
181 elsif ( $column =~ /branchcode/) { $colfilter = @$filters[2]; }
182 elsif ( $column =~ /sex/) { $colfilter = @$filters[5]; }
183 elsif ( $column =~ /sort1/) { $colfilter = @$filters[6]; }
184 elsif ( $column =~ /sort2/) { $colfilter = @$filters[7]; }
185 elsif ( $column =~ /^patron_attr\.(.*)$/) { $colfilter = $attr_filters->{$1}; }
186 else { $colfilter = ''; }
189 foreach my $i (0 .. scalar @$filters) {
191 if ( @$filters[$i] ) {
192 if ($i == 3 or $i == 4) {
193 $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
194 if ( @$filters[$i] );
196 $cell{filter} = @$filters[$i];
199 if ( $i == 0) { $cell{crit} = "Cat code"; }
200 elsif ( $i == 1 ) { $cell{crit} = "ZIP/Postal code"; }
201 elsif ( $i == 2 ) { $cell{crit} = "Branch code"; }
203 $i == 4 ) { $cell{crit} = "Date of birth"; }
204 elsif ( $i == 5 ) { $cell{crit} = "Sex"; }
205 elsif ( $i == 6 ) { $cell{crit} = "Sort1"; }
206 elsif ( $i == 7 ) { $cell{crit} = "Sort2"; }
207 else { $cell{crit} = "Unknown"; }
209 push @loopfilter, \%cell;
212 foreach my $type (keys %$attr_filters) {
213 if($attr_filters->{$type}) {
215 crit => "Attribute $type",
216 filter => $attr_filters->{$type}
221 my @branchcodes = map { $_->branchcode } Koha::Libraries->search;
222 ($status ) and push @loopfilter,{crit=>"Status", filter=>$status };
223 ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
225 my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
226 my $newperioddate=$period_year."-".$period_month."-".$period_day;
230 my $line_attribute_type;
231 if ($line =~/^patron_attr\.(.*)$/) {
232 $line_attribute_type = $1;
233 $line = 'borrower_attributes.attribute';
236 if (($line =~/zipcode/) and ($digits)) {
237 $linefield = "left($line,$digits)";
241 my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']});
244 my @strparams; # bind parameters for the query
245 if ($line_attribute_type) {
246 $strsth = "SELECT distinct attribute FROM borrower_attributes
247 WHERE attribute IS NOT NULL AND code=?";
248 push @strparams, $line_attribute_type;
250 $strsth = "SELECT distinctrow $linefield FROM borrowers
251 WHERE $line IS NOT NULL ";
254 $linefilter =~ s/\*/%/g;
256 $strsth .= " AND $linefield LIKE ? " ;
257 push @strparams, $linefilter;
259 $strsth .= " AND $status='1' " if ($status);
260 $strsth .=" order by $linefield";
262 my $sth = $dbh->prepare($strsth);
263 $sth->execute(@strparams);
264 while (my ($celvalue) = $sth->fetchrow) {
267 $cell{rowtitle} = $celvalue;
268 $cell{rowtitle_display} = ($patron_categories->find($celvalue)->description || "$celvalue\*") if ($line eq 'categorycode');
271 push @loopline, \%cell;
277 my $column_attribute_type;
278 if ($column =~/^patron_attr.(.*)$/) {
279 $column_attribute_type = $1;
280 $column = 'borrower_attributes.attribute';
283 if (($column =~/zipcode/) and ($digits)) {
284 $colfield = "left($column,$digits)";
290 my @strparams2; # bind parameters for the query
291 if ($column_attribute_type) {
292 $strsth2 = "SELECT DISTINCT attribute FROM borrower_attributes
293 WHERE attribute IS NOT NULL AND code=?";
294 push @strparams2, $column_attribute_type;
296 $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
297 WHERE $column IS NOT NULL";
301 $colfilter =~ s/\*/%/g;
302 $strsth2 .= " AND $colfield LIKE ? ";
303 push @strparams2, $colfield;
305 $strsth2 .= " AND $status='1' " if ($status);
307 $strsth2 .= " order by $colfield";
308 my $sth2 = $dbh->prepare($strsth2);
309 $sth2->execute(@strparams2);
310 while (my ($celvalue) = $sth2->fetchrow) {
312 if (defined $celvalue) {
313 $cell{coltitle} = $celvalue;
314 # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
315 $cell{coltitle_display} = $patron_categories->find($celvalue)->description if ($column eq 'categorycode');
317 push @loopcol, \%cell;
321 #Initialization of cell values.....
324 foreach my $row (@loopline) {
325 foreach my $col ( @loopcol ) {
326 my $rowtitle = $row->{rowtitle} // '';
327 my $coltitle = $row->{coltitle} // '';
328 $table{$rowtitle}->{$coltitle} = 0;
330 $row->{rowtitle} ||= '';
331 $table{$row->{rowtitle}}->{totalrow}=0;
332 $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display};
335 # preparing calculation
338 $strcalc = "SELECT ";
339 if ($line_attribute_type) {
340 $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
342 $strcalc .= " $linefield, ";
344 if ($column_attribute_type) {
345 $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
347 $strcalc .= " $colfield, ";
350 $strcalc .= " COUNT(*) FROM borrowers ";
351 foreach my $type (keys %$attr_filters) {
353 ($line_attribute_type and $line_attribute_type eq $type)
354 or ($column_attribute_type and $column_attribute_type eq $type)
355 or ($attr_filters->{$type})
357 $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
358 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
359 AND attribute_$type.code = " . $dbh->quote($type) . ") ";
362 $strcalc .= " WHERE 1 ";
364 @$filters[0]=~ s/\*/%/g if (@$filters[0]);
365 $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
366 @$filters[1]=~ s/\*/%/g if (@$filters[1]);
367 $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
368 @$filters[2]=~ s/\*/%/g if (@$filters[2]);
369 $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
370 @$filters[3]=~ s/\*/%/g if (@$filters[3]);
371 $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
372 @$filters[4]=~ s/\*/%/g if (@$filters[4]);
373 $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
374 @$filters[5]=~ s/\*/%/g if (@$filters[5]);
375 $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] );
376 @$filters[6]=~ s/\*/%/g if (@$filters[6]);
377 $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
378 @$filters[7]=~ s/\*/%/g if (@$filters[7]);
379 $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
381 foreach my $type (keys %$attr_filters) {
382 if($attr_filters->{$type}) {
383 my $filter = $attr_filters->{$type};
385 $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
388 $strcalc .= " AND borrowers.borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
389 $strcalc .= " AND borrowers.borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "' AND borrowernumber IS NOT NULL)" if ($activity eq 'nonactive');
390 $strcalc .= " AND $status='1' " if ($status);
392 $strcalc .= " GROUP BY ";
393 if ($line_attribute_type) {
394 $strcalc .= " line_attribute, ";
396 $strcalc .= " $linefield, ";
398 if ($column_attribute_type) {
399 $strcalc .= " column_attribute ";
401 $strcalc .= " $colfield ";
404 my $dbcalc = $dbh->prepare($strcalc);
405 (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
408 while (my ($row, $col, $value) = $dbcalc->fetchrow) {
409 # warn "filling table $row / $col / $value ";
410 $emptycol = 1 if (!defined($col));
411 $col = "zzEMPTY" if (!defined($col));
412 $row = "zzEMPTY" if (!defined($row));
414 $table{$row}->{$col}+=$value;
415 $table{$row}->{totalrow}+=$value;
416 $grantotal += $value;
419 push @loopcol,{coltitle => "NULL"} if ($emptycol);
421 foreach my $row (sort keys %table) {
423 #@loopcol ensures the order for columns is common with column titles
424 # and the number matches the number of columns
425 foreach my $col ( @loopcol ) {
426 my $coltitle = $col->{coltitle} // '';
427 $coltitle = $coltitle eq "NULL" ? "zzEMPTY" : $coltitle;
428 my $value =$table{$row}->{$coltitle};
429 push @loopcell, {value => $value};
432 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
433 'rowtitle_display' => $table{$row}->{rowtitle_display} || ($row eq "zzEMPTY" ? "NULL" : $row),
434 'loopcell' => \@loopcell,
435 'totalrow' => $table{$row}->{totalrow}
439 foreach my $col ( @loopcol ) {
441 foreach my $row ( @looprow ) {
442 my $rowtitle = $row->{rowtitle} // '';
443 $rowtitle = ($rowtitle eq "NULL") ? "zzEMPTY" : $rowtitle;
444 my $coltitle = $col->{coltitle} // '';
445 $coltitle = ($coltitle eq "NULL") ? "zzEMPTY" : $coltitle;
447 $total += $table{$rowtitle}->{$coltitle} || 0;
448 # warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
450 # warn "summ for column ".$col->{coltitle}." = ".$total;
451 push @loopfooter, {'totalcol' => $total};
455 # the header of the table
456 $globalline{loopfilter}=\@loopfilter;
457 # the core of the table
458 $globalline{looprow} = \@looprow;
459 $globalline{loopcol} = \@loopcol;
460 # # the foot (totals by borrower type)
461 $globalline{loopfooter} = \@loopfooter;
462 $globalline{total}= $grantotal;
463 $globalline{line} = ($line_attribute_type) ? $line_attribute_type : $line;
464 $globalline{column} = ($column_attribute_type) ? $column_attribute_type : $column;
465 push @mainloop,\%globalline;
469 sub parse_extended_patron_attributes {
472 my @params_names = $input->param;
474 foreach my $name (@params_names) {
475 if ($name =~ /^Filter_patron_attr\.(.*)$/) {
477 my $value = $input->param($name);
478 $attr{$code} = $value;
486 sub patron_attributes_form {
487 my $template = shift;
489 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
490 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
493 while ( my $attr_type = $attribute_types->next ) {
494 # TODO The following can be simplified easily
496 class => $attr_type->class(),
497 code => $attr_type->code(),
498 description => $attr_type->description(),
499 repeatable => $attr_type->repeatable(),
500 category => $attr_type->authorised_value_category(),
501 category_code => $attr_type->category_code(),
504 my $newentry = { %$entry };
505 if ($attr_type->authorised_value_category()) {
506 $newentry->{use_dropdown} = 1;
507 $newentry->{auth_val_loop} = GetAuthorisedValues(
508 $attr_type->authorised_value_category()
511 push @{ $items_by_class{ $attr_type->class() } }, $newentry;
515 foreach my $class ( sort keys %items_by_class ) {
516 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
517 my $lib = $av->count ? $av->next->lib : $class;
518 push @attribute_loop, {
520 items => $items_by_class{$class},
525 $template->param(patron_attributes => \@attribute_loop);