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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 use List
::MoreUtils qw
/uniq/;
26 use C4
::Branch
; # GetBranches
33 use C4
::Members
::AttributeTypes
;
34 use C4
::Dates qw
/format_date format_date_in_iso/;
42 plugin that shows a stats on borrowers
51 my $do_it=$input->param('do_it');
52 my $fullreportname = "reports/borrowers_stats.tmpl";
53 my $line = $input->param("Line");
54 my $column = $input->param("Column");
55 my @filters = $input->param("Filter");
56 $filters[3]=format_date_in_iso
($filters[3]);
57 $filters[4]=format_date_in_iso
($filters[4]);
58 my $digits = $input->param("digits");
59 our $period = $input->param("period");
60 my $borstat = $input->param("status");
61 my $borstat1 = $input->param("activity");
62 my $output = $input->param("output");
63 my $basename = $input->param("basename");
64 our $sep = $input->param("sep");
65 $sep = "\t" if ($sep and $sep eq 'tabulation');
66 my $selected_branch; # = $input->param("?");
68 our $branches = GetBranches
;
70 my ($template, $borrowernumber, $cookie)
71 = get_template_and_user
({template_name
=> $fullreportname,
75 flagsrequired
=> {reports
=> '*'},
78 $template->param(do_it
=> $do_it);
81 if (C4
::Context
->preference('ExtendedPatronAttributes')) {
82 $attributes = parse_extended_patron_attributes
($input);
84 my $results = calculate
($line, $column, $digits, $borstat,$borstat1 ,\
@filters, $attributes);
85 if ($output eq "screen"){
86 $template->param(mainloop
=> $results);
87 output_html_with_http_headers
$input, $cookie, $template->output;
89 print $input->header(-type
=> 'application/vnd.sun.xml.calc',
91 -name
=> "$basename.csv",
92 -attachment
=> "$basename.csv");
93 my $cols = @
$results[0]->{loopcol
};
94 my $lines = @
$results[0]->{looprow
};
95 print @
$results[0]->{line
} ."/". @
$results[0]->{column
} .$sep;
96 foreach my $col ( @
$cols ) {
97 print $col->{coltitle
}.$sep;
100 foreach my $line ( @
$lines ) {
101 my $x = $line->{loopcell
};
102 print $line->{rowtitle
}.$sep;
103 foreach my $cell (@
$x) {
104 print $cell->{value
}.$sep;
106 print $line->{totalrow
};
110 $cols = @
$results[0]->{loopfooter
};
111 foreach my $col ( @
$cols ) {
112 print $sep.$col->{totalcol
};
114 print $sep.@
$results[0]->{total
};
116 exit; # exit after do_it, regardless
118 my $dbh = C4
::Context
->dbh;
120 $template->param( CAT_LOOP
=> &catcode_aref
);
122 foreach (sort {$branches->{$a}->{branchname
} cmp $branches->{$b}->{branchname
}} keys %$branches) {
123 my $line = {branchcode
=> $_, branchname
=> $branches->{$_}->{branchname
} || 'UNKNOWN'};
124 $line->{selected
} = 'selected' if ($selected_branch and $selected_branch eq $_);
125 push @branchloop, $line;
127 $template->param(BRANCH_LOOP
=> \
@branchloop);
128 $req = $dbh->prepare("SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode");
130 $template->param( ZIP_LOOP
=> $req->fetchall_arrayref({}));
131 $req = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' ORDER BY lib");
133 $template->param( SORT1_LOOP
=> $req->fetchall_arrayref({}));
134 $req = $dbh->prepare("SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort2 <> '' ORDER BY sort2 LIMIT 200");
135 # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destory DB performance.
137 $template->param( SORT2_LOOP
=> $req->fetchall_arrayref({}));
139 my $CGIextChoice=CGI
::scrolling_list
(
142 -values => ['CSV'], # FIXME translation
145 my $CGIsepChoice=GetDelimiterChoices
;
147 CGIextChoice
=> $CGIextChoice,
148 CGIsepChoice
=> $CGIsepChoice,
150 if (C4
::Context
->preference('ExtendedPatronAttributes')) {
151 $template->param(ExtendedPatronAttributes
=> 1);
152 patron_attributes_form
($template);
155 output_html_with_http_headers
$input, $cookie, $template->output;
158 my $req = C4
::Context
->dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
160 return $req->fetchall_arrayref({});
162 sub catcodes_hash
() {
164 my $catcodes = &catcode_aref
;
165 foreach (@
$catcodes) {
166 $cathash{$_->{categorycode
}} = ($_->{description
} || 'NO_DESCRIPTION') . " ($_->{categorycode})";
172 my ($line, $column, $digits, $status, $activity, $filters, $attr_filters) = @_;
182 my $dbh = C4
::Context
->dbh;
185 my @valid_names = qw(categorycode zipcode branchcode sex sort1 sort2);
186 my @attribute_types = C4
::Members
::AttributeTypes
::GetAttributeTypes
;
187 if ($line =~ /^patron_attr\.(.*)/) {
188 my $attribute_type = $1;
189 return unless (grep {$attribute_type eq $_->{code
}} @attribute_types);
191 return unless (grep /^$line$/, @valid_names);
193 if ($column =~ /^patron_attr\.(.*)/) {
194 my $attribute_type = $1;
195 return unless (grep {$attribute_type eq $_->{code
}} @attribute_types);
197 return unless (grep /^$column$/, @valid_names);
199 return if ($digits and $digits !~ /^\d+$/);
200 return if ($status and (grep /^$status$/, qw(debarred gonenoaddress lost)) == 0);
201 return if ($activity and (grep /^$activity$/, qw(active nonactive)) == 0);
206 when (/categorycode/) { $linefilter = @
$filters[0] }
207 when (/zipcode/) { $linefilter = @
$filters[1] }
208 when (/branchcode/) { $linefilter = @
$filters[2] }
209 when (/sex/) { $linefilter = @
$filters[5] }
210 when (/sort1/) { $linefilter = @
$filters[6] }
211 when (/sort2/) { $linefilter = @
$filters[7] }
212 when (/^patron_attr\.(.*)$/) { $linefilter = $attr_filters->{$1} }
213 default { $linefilter = '' }
218 when (/categorycode/) { $colfilter = @
$filters[0] }
219 when (/zipcode/) { $colfilter = @
$filters[1] }
220 when (/branchcode/) { $colfilter = @
$filters[2] }
221 when (/sex/) { $colfilter = @
$filters[5] }
222 when (/sort1/) { $colfilter = @
$filters[6] }
223 when (/sort2/) { $colfilter = @
$filters[7] }
224 when (/^patron_attr\.(.*)$/) { $colfilter = $attr_filters->{$1} }
225 default { $colfilter = '' }
229 foreach my $i (0 .. scalar @
$filters) {
231 if ( @
$filters[$i] ) {
232 if ($i == 3 or $i == 4) {
233 $cell{filter
} = format_date
(@
$filters[$i]);
235 $cell{filter
} = @
$filters[$i];
239 when (0) { $cell{crit
} = "Cat code" }
240 when (1) { $cell{crit
} = "Zip code" }
241 when (2) { $cell{crit
} = "Branch code" }
242 when ([3,4]) { $cell{crit
} = "Date of birth" }
243 when (5) { $cell{crit
} = "Sex" }
244 when (6) { $cell{crit
} = "Sort1" }
245 when (7) { $cell{crit
} = "Sort2" }
246 default { $cell{crit
} = "Unknown" }
248 push @loopfilter, \
%cell;
251 foreach my $type (keys %$attr_filters) {
252 if($attr_filters->{$type}) {
254 crit
=> "Attribute $type",
255 filter
=> $attr_filters->{$type}
260 ($status ) and push @loopfilter,{crit
=>"Status", filter
=>$status };
261 ($activity) and push @loopfilter,{crit
=>"Activity",filter
=>$activity};
262 push @loopfilter,{debug
=>1, crit
=>"Branches",filter
=>join(" ", sort keys %$branches)};
263 push @loopfilter,{debug
=>1, crit
=>"(line, column)", filter
=>"($line,$column)"};
265 my ( $period_year, $period_month, $period_day )=Add_Delta_YM
( Today
(),-$period, 0);
266 my $newperioddate=$period_year."-".$period_month."-".$period_day;
270 my $line_attribute_type;
271 if ($line =~/^patron_attr\.(.*)$/) {
272 $line_attribute_type = $1;
273 $line = 'borrower_attributes.attribute';
276 if (($line =~/zipcode/) and ($digits)) {
277 $linefield = "left($line,$digits)";
282 my %cathash = ($line eq 'categorycode' or $column eq 'categorycode') ?
&catcodes_hash
: ();
283 push @loopfilter, {debug
=>1, crit
=>"\%cathash", filter
=>join(", ", map {$cathash{$_}} sort keys %cathash)};
286 my @strparams; # bind parameters for the query
287 if ($line_attribute_type) {
288 $strsth = "SELECT distinct attribute FROM borrower_attributes
289 WHERE attribute IS NOT NULL AND code=?";
290 push @strparams, $line_attribute_type;
292 $strsth = "SELECT distinctrow $linefield FROM borrowers
293 WHERE $line IS NOT NULL ";
296 $linefilter =~ s/\*/%/g;
298 $strsth .= " AND $linefield LIKE ? " ;
299 push @strparams, $linefilter;
301 $strsth .= " AND $status='1' " if ($status);
302 $strsth .=" order by $linefield";
304 push @loopfilter, {sql
=>1, crit
=>"Query", filter
=>$strsth};
305 my $sth = $dbh->prepare($strsth);
306 $sth->execute(@strparams);
307 while (my ($celvalue) = $sth->fetchrow) {
310 $cell{rowtitle
} = $celvalue;
311 # $cell{rowtitle_display} = ($linefield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
312 $cell{rowtitle_display
} = ($cathash{$celvalue} || "$celvalue\*") if ($line eq 'categorycode');
315 push @loopline, \
%cell;
321 my $column_attribute_type;
322 if ($column =~/^patron_attr.(.*)$/) {
323 $column_attribute_type = $1;
324 $column = 'borrower_attributes.attribute';
327 if (($column =~/zipcode/) and ($digits)) {
328 $colfield = "left($column,$digits)";
334 my @strparams2; # bind parameters for the query
335 if ($column_attribute_type) {
336 $strsth2 = "SELECT DISTINCT attribute FROM borrower_attributes
337 WHERE attribute IS NOT NULL AND code=?";
338 push @strparams2, $column_attribute_type;
340 $strsth2 = "SELECT DISTINCTROW $colfield FROM borrowers
341 WHERE $column IS NOT NULL";
345 $colfilter =~ s/\*/%/g;
346 $strsth2 .= " AND $colfield LIKE ? ";
347 push @strparams2, $colfield;
349 $strsth2 .= " AND $status='1' " if ($status);
351 $strsth2 .= " order by $colfield";
352 push @loopfilter, {sql
=>1, crit
=>"Query", filter
=>$strsth2};
353 my $sth2 = $dbh->prepare($strsth2);
354 $sth2->execute(@strparams2);
355 while (my ($celvalue) = $sth2->fetchrow) {
357 if (defined $celvalue) {
358 $cell{coltitle
} = $celvalue;
359 # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue;
360 $cell{coltitle_display
} = $cathash{$celvalue} if ($column eq 'categorycode');
362 push @loopcol, \
%cell;
366 #Initialization of cell values.....
369 foreach my $row (@loopline) {
370 foreach my $col ( @loopcol ) {
371 my $rowtitle = $row->{rowtitle
} // '';
372 my $coltitle = $row->{coltitle
} // '';
373 $table{$rowtitle}->{$coltitle} = 0;
375 $row->{rowtitle
} ||= '';
376 $table{$row->{rowtitle
}}->{totalrow
}=0;
377 $table{$row->{rowtitle
}}->{rowtitle_display
} = $row->{rowtitle_display
};
380 # preparing calculation
383 $strcalc = "SELECT ";
384 if ($line_attribute_type) {
385 $strcalc .= " attribute_$line_attribute_type.attribute AS line_attribute, ";
387 $strcalc .= " $linefield, ";
389 if ($column_attribute_type) {
390 $strcalc .= " attribute_$column_attribute_type.attribute AS column_attribute, ";
392 $strcalc .= " $colfield, ";
395 $strcalc .= " COUNT(*) FROM borrowers ";
396 foreach my $type (keys %$attr_filters) {
398 ($line_attribute_type and $line_attribute_type eq $type)
399 or ($column_attribute_type and $column_attribute_type eq $type)
400 or ($attr_filters->{$type})
402 $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type
403 ON (borrowers.borrowernumber = attribute_$type.borrowernumber
404 AND attribute_$type.code = " . $dbh->quote($type) . ") ";
407 $strcalc .= " WHERE 1 ";
409 @
$filters[0]=~ s/\*/%/g if (@
$filters[0]);
410 $strcalc .= " AND categorycode like '" . @
$filters[0] ."'" if ( @
$filters[0] );
411 @
$filters[1]=~ s/\*/%/g if (@
$filters[1]);
412 $strcalc .= " AND zipcode like '" . @
$filters[1] ."'" if ( @
$filters[1] );
413 @
$filters[2]=~ s/\*/%/g if (@
$filters[2]);
414 $strcalc .= " AND branchcode like '" . @
$filters[2] ."'" if ( @
$filters[2] );
415 @
$filters[3]=~ s/\*/%/g if (@
$filters[3]);
416 $strcalc .= " AND dateofbirth > '" . @
$filters[3] ."'" if ( @
$filters[3] );
417 @
$filters[4]=~ s/\*/%/g if (@
$filters[4]);
418 $strcalc .= " AND dateofbirth < '" . @
$filters[4] ."'" if ( @
$filters[4] );
419 @
$filters[5]=~ s/\*/%/g if (@
$filters[5]);
420 $strcalc .= " AND sex like '" . @
$filters[5] ."'" if ( @
$filters[5] );
421 @
$filters[6]=~ s/\*/%/g if (@
$filters[6]);
422 $strcalc .= " AND sort1 like '" . @
$filters[6] ."'" if ( @
$filters[6] );
423 @
$filters[7]=~ s/\*/%/g if (@
$filters[7]);
424 $strcalc .= " AND sort2 like '" . @
$filters[7] ."'" if ( @
$filters[7] );
426 foreach my $type (keys %$attr_filters) {
427 if($attr_filters->{$type}) {
428 my $filter = $attr_filters->{$type};
430 $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
433 $strcalc .= " AND borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
434 $strcalc .= " AND borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'nonactive');
435 $strcalc .= " AND $status='1' " if ($status);
437 $strcalc .= " GROUP BY ";
438 if ($line_attribute_type) {
439 $strcalc .= " line_attribute, ";
441 $strcalc .= " $linefield, ";
443 if ($column_attribute_type) {
444 $strcalc .= " column_attribute ";
446 $strcalc .= " $colfield ";
449 push @loopfilter, {sql
=>1, crit
=>"Query", filter
=>$strcalc};
450 my $dbcalc = $dbh->prepare($strcalc);
451 (scalar(@calcparams)) ?
$dbcalc->execute(@calcparams) : $dbcalc->execute();
454 while (my ($row, $col, $value) = $dbcalc->fetchrow) {
455 # warn "filling table $row / $col / $value ";
456 $emptycol = 1 if (!defined($col));
457 $col = "zzEMPTY" if (!defined($col));
458 $row = "zzEMPTY" if (!defined($row));
460 $table{$row}->{$col}+=$value;
461 $table{$row}->{totalrow
}+=$value;
462 $grantotal += $value;
465 push @loopcol,{coltitle
=> "NULL"} if ($emptycol);
467 foreach my $row (sort keys %table) {
469 #@loopcol ensures the order for columns is common with column titles
470 # and the number matches the number of columns
471 foreach my $col ( @loopcol ) {
472 my $coltitle = $col->{coltitle
} // '';
473 $coltitle = $coltitle eq "NULL" ?
"zzEMPTY" : $coltitle;
474 my $value =$table{$row}->{$coltitle};
475 push @loopcell, {value
=> $value};
478 'rowtitle' => ($row eq "zzEMPTY")?
"NULL":$row,
479 'rowtitle_display' => $table{$row}->{rowtitle_display
} || ($row eq "zzEMPTY" ?
"NULL" : $row),
480 'loopcell' => \
@loopcell,
481 'totalrow' => $table{$row}->{totalrow
}
485 foreach my $col ( @loopcol ) {
487 foreach my $row ( @looprow ) {
488 my $rowtitle = $row->{rowtitle
} // '';
489 $rowtitle = ($rowtitle eq "NULL") ?
"zzEMPTY" : $rowtitle;
490 my $coltitle = $col->{coltitle
} // '';
491 $coltitle = ($coltitle eq "NULL") ?
"zzEMPTY" : $coltitle;
493 $total += $table{$rowtitle}->{$coltitle} || 0;
494 # warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
496 # warn "summ for column ".$col->{coltitle}." = ".$total;
497 push @loopfooter, {'totalcol' => $total};
501 # the header of the table
502 $globalline{loopfilter
}=\
@loopfilter;
503 # the core of the table
504 $globalline{looprow
} = \
@looprow;
505 $globalline{loopcol
} = \
@loopcol;
506 # # the foot (totals by borrower type)
507 $globalline{loopfooter
} = \
@loopfooter;
508 $globalline{total
}= $grantotal;
509 $globalline{line
} = ($line_attribute_type) ?
$line_attribute_type : $line;
510 $globalline{column
} = ($column_attribute_type) ?
$column_attribute_type : $column;
511 push @mainloop,\
%globalline;
515 sub parse_extended_patron_attributes
{
518 my @params_names = $input->param;
520 foreach my $name (@params_names) {
521 if ($name =~ /^Filter_patron_attr\.(.*)$/) {
523 my $value = $input->param($name);
524 $attr{$code} = $value;
532 sub patron_attributes_form
{
533 my $template = shift;
535 my @types = C4
::Members
::AttributeTypes
::GetAttributeTypes
();
538 foreach my $type (@types) {
539 my $attr_type = C4
::Members
::AttributeTypes
->fetch($type->{code
});
541 class => $attr_type->class(),
542 code
=> $attr_type->code(),
543 description
=> $attr_type->description(),
544 repeatable
=> $attr_type->repeatable(),
545 category
=> $attr_type->authorised_value_category(),
546 category_code
=> $attr_type->category_code(),
549 my $newentry = { %$entry };
550 if ($attr_type->authorised_value_category()) {
551 $newentry->{use_dropdown
} = 1;
552 $newentry->{auth_val_loop
} = GetAuthorisedValues
(
553 $attr_type->authorised_value_category()
556 push @
{ $items_by_class{ $attr_type->class() } }, $newentry;
560 foreach my $class ( sort keys %items_by_class ) {
561 my $lib = GetAuthorisedValueByCode
( 'PA_CLASS', $class ) || $class;
562 push @attribute_loop, {
564 items
=> $items_by_class{$class},
569 $template->param(patron_attributes
=> \
@attribute_loop);