4 # Copyright 2000-2002 Katipo Communications
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #use warnings; FIXME - Bug 2505
30 use C4::Branch; # GetBranches
35 use C4::Dates qw/format_date format_date_in_iso/;
40 plugin that shows circulation stats
48 # my $debug = 1; # override for now.
50 my $fullreportname = "reports/issues_stats.tmpl";
51 my $do_it = $input->param('do_it');
52 my $line = $input->param("Line");
53 my $column = $input->param("Column");
54 my @filters = $input->param("Filter");
55 $filters[0]=format_date_in_iso($filters[0]);
56 $filters[1]=format_date_in_iso($filters[1]);
57 my $podsp = $input->param("DisplayBy");
58 my $type = $input->param("PeriodTypeSel");
59 my $daysel = $input->param("PeriodDaySel");
60 my $monthsel = $input->param("PeriodMonthSel");
61 my $calc = $input->param("Cellvalue");
62 my $output = $input->param("output");
63 my $basename = $input->param("basename");
64 my ($template, $borrowernumber, $cookie) = get_template_and_user({
65 template_name => $fullreportname,
69 flagsrequired => {reports => '*'},
72 our $sep = $input->param("sep");
73 $sep = "\t" if ($sep eq 'tabulation');
74 $template->param(do_it => $do_it,
77 my $itemtypes = GetItemTypes();
78 my $categoryloop = GetBorrowercategoryList;
80 my $ccodes = GetKohaAuthorisedValues("items.ccode");
81 my $locations = GetKohaAuthorisedValues("items.location");
83 my $Bsort1 = GetAuthorisedValues("Bsort1");
84 my $Bsort2 = GetAuthorisedValues("Bsort2");
85 my ($hassort1,$hassort2);
86 $hassort1=1 if $Bsort1;
87 $hassort2=1 if $Bsort2;
92 my $results = calculate($line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters);
93 if ($output eq "screen"){
94 # Printing results to screen
95 $template->param(mainloop => $results);
96 output_html_with_http_headers $input, $cookie, $template->output;
98 # Printing to a csv file
99 print $input->header(-type => 'application/vnd.sun.xml.calc',
100 -encoding => 'utf-8',
101 -attachment=>"$basename.csv",
102 -filename=>"$basename.csv" );
103 my $cols = @$results[0]->{loopcol};
104 my $lines = @$results[0]->{looprow};
106 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
108 foreach my $col ( @$cols ) {
109 print $col->{coltitle}.$sep;
113 foreach my $line ( @$lines ) {
114 my $x = $line->{loopcell};
115 print $line->{rowtitle}.$sep;
116 print map {$_->{value}.$sep} @$x;
117 print $line->{totalrow}, "\n";
121 $cols = @$results[0]->{loopfooter};
122 print map {$sep.$_->{totalcol}} @$cols;
123 print $sep.@$results[0]->{total};
125 exit; # exit either way after $do_it
128 my $dbh = C4::Context->dbh;
133 # create itemtype arrayref for <select>.
135 for my $itype ( sort {$itemtypes->{$a}->{description} cmp $itemtypes->{$b}->{description}} keys(%$itemtypes)) {
136 push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{description} } ;
141 foreach (sort keys %$locations) {
142 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
146 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
147 push @ccodes, { code => $_, description => $ccodes->{$_} };
150 my $CGIextChoice=CGI::scrolling_list(
153 -values => ['CSV'], # FIXME translation
157 my $CGIsepChoice=GetDelimiterChoices;
160 categoryloop => $categoryloop,
161 itemtypeloop => \@itemtypeloop,
162 locationloop => \@locations,
163 ccodeloop => \@ccodes,
164 branchloop => GetBranchesLoop(C4::Context->userenv->{'branch'}),
165 hassort1=> $hassort1,
166 hassort2=> $hassort2,
169 CGIextChoice => $CGIextChoice,
170 CGIsepChoice => $CGIsepChoice,
172 output_html_with_http_headers $input, $cookie, $template->output;
175 my ($line, $column, $dsp, $type,$daysel,$monthsel ,$process, $filters) = @_;
183 my $dbh = C4::Context->dbh;
189 for (my $i=0;$i<=12;$i++) {
191 (@$filters[$i]) or next;
192 if (($i==1) and (@$filters[$i-1])) {
193 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
195 # format the dates filters, otherwise just fill as is
197 $cell{filter} = @$filters[$i];
199 $cell{filter} = format_date(@$filters[$i]);
202 ( $i == 0 ) ? "Period From"
203 : ( $i == 1 ) ? "Period To"
204 : ( $i == 2 ) ? "Patron Category ="
205 : ( $i == 3 ) ? "Item Type ="
206 : ( $i == 4 ) ? "Library ="
207 : ( $i == 5 ) ? "Collection ="
208 : ( $i == 6 ) ? "Location ="
209 : ( $i == 7 ) ? "Item callnumber >="
210 : ( $i == 8 ) ? "Item callnumber <"
211 : ( $i == 9 ) ? "sort1 ="
212 : ( $i == 10 ) ? "sort2 ="
213 : ( $i == 11 ) ? "Home library ="
214 : ( $i == 12 )? "Holding library ="
215 : "UNKNOWN FILTER ($i)";
217 # FIXME - no translation mechanism !
218 push @loopfilter, \%cell;
220 push @loopfilter,{crit=>"Event", filter=>$type };
221 push @loopfilter,{crit=>"Display by", filter=>$dsp } if ($dsp);
222 push @loopfilter,{crit=>"Select Day", filter=>$daysel } if ($daysel);
223 push @loopfilter,{crit=>"Select Month",filter=>$monthsel} if ($monthsel);
226 $debug and warn "filtres ". join "|", @filters;
227 my ($colsource, $linesource);
228 $linefilter[1] = @$filters[1] if ($line =~ /datetime/);
230 ( $line =~ /datetime/ ) ? @$filters[0]
231 : ( $line =~ /category/ ) ? @$filters[2]
232 : ( $line =~ /itemtype/ ) ? @$filters[3]
233 : ( $line =~ /^branch/ ) ? @$filters[4]
234 : ( $line =~ /ccode/ ) ? @$filters[5]
235 : ( $line =~ /location/ ) ? @$filters[6]
236 : ( $line =~ /sort1/ ) ? @$filters[9]
237 : ( $line =~ /sort2/ ) ? @$filters[10]
238 : ( $line =~ /homebranch/) ? @$filters[11]
239 : ( $line =~ /holdingbranch/) ? @$filters[12]
242 if ( $line =~ /ccode/ or $line =~ /location/ or $line =~ /homebranch/ or $line =~ /holdingbranch/ ) {
243 $linesource = 'items';
247 $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
249 ( $column =~ /datetime/ ) ? @$filters[0]
250 : ( $column =~ /category/ ) ? @$filters[2]
251 : ( $column =~ /itemtype/ ) ? @$filters[3]
252 : ( $column =~ /^branch/ ) ? @$filters[4]
253 : ( $column =~ /ccode/ ) ? @$filters[5]
254 : ( $column =~ /location/ ) ? @$filters[6]
255 : ( $column =~ /sort1/ ) ? @$filters[9]
256 : ( $column =~ /sort1/ ) ? @$filters[10]
257 : ( $column =~ /homebranch/) ? @$filters[11]
258 : ( $column =~ /holdingbranch/) ? @$filters[12]
261 if ( $column =~ /ccode/ or $column =~ /location/ or $column =~ /homebranch/ or $column =~ /holdingbranch/ ) {
262 $colsource = 'items';
266 if ($line =~ /datetime/) {
267 # by Day, Month or Year (1,2,3 respectively)
268 $linefield = ($dsp == 1) ? " dayname($line)" :
269 ($dsp == 2) ? "monthname($line)" :
270 ($dsp == 3) ? " Year($line)" :
271 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
275 my $lineorder = ($linefield =~ /dayname/) ? "weekday($line)" :
276 ($linefield =~ /^month/ ) ? " month($line)" : $linefield;
278 my $strsth = "SELECT distinctrow $linefield FROM statistics, ";
279 # get stats on items if ccode or location, otherwise borrowers.
280 $strsth .= ($linesource eq 'items' ) ?
281 " items WHERE (statistics.itemnumber=items.itemnumber) " :
282 " borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
283 $strsth .= " AND $line is not null ";
285 if ($line =~ /datetime/) {
286 if ($linefilter[1] and ($linefilter[0])) {
287 $strsth .= " AND $line between ? AND ? ";
288 } elsif ($linefilter[1]) {
289 $strsth .= " AND $line < ? ";
290 } elsif ($linefilter[0]) {
291 $strsth .= " AND $line > ? ";
293 $strsth .= " AND type ='".$type."' " if $type;
294 $strsth .= " AND dayname(datetime) ='". $daysel ."' " if $daysel;
295 $strsth .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
296 } elsif ($linefilter[0]) {
297 $linefilter[0] =~ s/\*/%/g;
298 $strsth .= " AND $line LIKE ? ";
300 $strsth .=" group by $linefield order by $lineorder ";
301 $debug and warn $strsth;
302 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth};
303 my $sth = $dbh->prepare( $strsth );
304 if ((@linefilter) and ($linefilter[1])){
305 $sth->execute($linefilter[0],$linefilter[1]);
306 } elsif ($linefilter[0]) {
307 $sth->execute($linefilter[0]);
312 while (my ($celvalue) = $sth->fetchrow) {
313 my %cell = (rowtitle => $celvalue, totalrow => 0); # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display
314 $cell{rowtitle_display} =
315 ($line =~ /ccode/ ) ? $ccodes->{$celvalue} :
316 ($line =~ /location/) ? $locations->{$celvalue} :
317 ($line =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
318 $celvalue; # default fallback
319 if ($line =~ /sort1/) {
321 ($celvalue eq $_->{authorised_value}) or next;
322 $cell{rowtitle_display} = $_->{lib} and last;
324 } elsif ($line =~ /sort2/) {
326 ($celvalue eq $_->{authorised_value}) or next;
327 $cell{rowtitle_display} = $_->{lib} and last;
329 } elsif ($line =~ /category/) {
330 foreach (@$categoryloop) {
331 ($celvalue eq $_->{categorycode}) or next;
332 $cell{rowtitle_display} = $_->{description} and last;
335 push @loopline, \%cell;
341 if ($column =~ /datetime/) {
342 #Display by Day, Month or Year (1,2,3 respectively)
343 $colfield = ($dsp == 1) ? " dayname($column)" :
344 ($dsp == 2) ? "monthname($column)" :
345 ($dsp == 3) ? " Year($column)" :
346 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
350 $colorder = ($colfield =~ /dayname/) ? "weekday($column)" :
351 ($colfield =~ /^month/ ) ? " month($column)" : $colfield;
352 my $strsth2 = "SELECT distinctrow $colfield FROM statistics, ";
353 # get stats on items if ccode or location, otherwise borrowers.
354 $strsth2 .= ($colsource eq 'items' ) ?
355 "items WHERE (statistics.itemnumber=items.itemnumber) " :
356 "borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
357 $strsth2 .= " AND $column IS NOT NULL ";
359 if ($column =~ /datetime/){
360 if (($colfilter[1]) and ($colfilter[0])){
361 $strsth2 .= " AND $column BETWEEN ? AND ? " ;
362 } elsif ($colfilter[1]) {
363 $strsth2 .= " AND $column < ? " ;
364 } elsif ($colfilter[0]) {
365 $strsth2 .= " AND $column > ? " ;
367 $strsth2 .= " AND type ='". $type ."' " if $type;
368 $strsth2 .= " AND dayname(datetime) ='". $daysel ."' " if $daysel;
369 $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
370 } elsif ($colfilter[0]) {
371 $colfilter[0] =~ s/\*/%/g;
372 $strsth2 .= " AND $column LIKE ? " ;
374 $strsth2 .=" GROUP BY $colfield ORDER BY $colorder ";
376 my $sth2 = $dbh->prepare($strsth2);
377 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth2};
378 if ((@colfilter) and ($colfilter[1])){
379 $sth2->execute($colfilter[0], $colfilter[1]);
380 } elsif ($colfilter[0]) {
381 $sth2->execute($colfilter[0]);
386 while (my ($celvalue) = $sth2->fetchrow) {
387 my %cell = (coltitle => $celvalue); # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display
388 $cell{coltitle_display} =
389 ($column =~ /ccode/ ) ? $ccodes->{$celvalue} :
390 ($column =~ /location/) ? $locations->{$celvalue} :
391 ($column =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
392 $celvalue; # default fallback
393 if ($column =~ /sort1/) {
395 ($celvalue eq $_->{authorised_value}) or next;
396 $cell{coltitle_display} = $_->{lib} and last;
398 } elsif ($column =~ /sort2/) {
400 ($celvalue eq $_->{authorised_value}) or next;
401 $cell{coltitle_display} = $_->{lib} and last;
403 } elsif ($column =~ /category/) {
404 foreach (@$categoryloop) {
405 ($celvalue eq $_->{categorycode}) or next;
406 $cell{coltitle_display} = $_->{description} and last;
409 push @loopcol, \%cell;
412 #Initialization of cell values.....
414 foreach my $row (@loopline) {
415 foreach my $col (@loopcol) {
416 $debug and warn " init table : $row->{rowtitle} ( $row->{rowtitle_display} ) / $col->{coltitle} ( $col->{coltitle_display} ) ";
417 $table{$row->{rowtitle}}->{$col->{coltitle}} = 0;
419 $table{$row->{rowtitle}}->{totalrow} = 0;
422 # preparing calculation
423 my $strcalc = "SELECT $linefield, $colfield, ";
424 $strcalc .= ($process == 1) ? " COUNT(*) " :
425 ($process == 2) ? "(COUNT(DISTINCT borrowers.borrowernumber))" :
426 ($process == 3) ? "(COUNT(DISTINCT statistics.itemnumber))" : '';
428 my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
429 $rqbookcount->execute;
430 my ($bookcount) = $rqbookcount->fetchrow;
431 $strcalc .= "100*(COUNT(DISTINCT statistics.itemnumber))/ $bookcount " ;
435 LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber
437 $strcalc .= "LEFT JOIN items ON statistics.itemnumber=items.itemnumber "
438 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or ($colsource eq 'items')
439 ||@$filters[5]||@$filters[6]||@$filters[7]||@$filters[8]);
441 $strcalc .= "WHERE 1=1 ";
442 @$filters = map {defined($_) and s/\*/%/g; $_} @$filters;
443 $strcalc .= " AND statistics.datetime > '" . @$filters[0] ."'" if (@$filters[0] );
444 $strcalc .= " AND statistics.datetime < '" . @$filters[1] ."'" if (@$filters[1] );
445 $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] ."'" if (@$filters[2] );
446 $strcalc .= " AND statistics.itemtype LIKE '" . @$filters[3] ."'" if (@$filters[3] );
447 $strcalc .= " AND statistics.branch LIKE '" . @$filters[4] ."'" if (@$filters[4] );
448 $strcalc .= " AND items.ccode LIKE '" . @$filters[5] ."'" if (@$filters[5] );
449 $strcalc .= " AND items.location LIKE '" . @$filters[6] ."'" if (@$filters[6] );
450 $strcalc .= " AND items.itemcallnumber >='" . @$filters[7] ."'" if (@$filters[7] );
451 $strcalc .= " AND items.itemcallnumber <'" . @$filters[8] ."'" if (@$filters[8] );
452 $strcalc .= " AND borrowers.sort1 LIKE '" . @$filters[9] ."'" if (@$filters[9] );
453 $strcalc .= " AND borrowers.sort2 LIKE '" . @$filters[10]."'" if (@$filters[10]);
454 $strcalc .= " AND dayname(datetime) LIKE '" . $daysel ."'" if ($daysel );
455 $strcalc .= " AND monthname(datetime) LIKE '" . $monthsel ."'" if ($monthsel);
456 $strcalc .= " AND statistics.type LIKE '" . $type ."'" if ($type );
458 $strcalc .= " GROUP BY $linefield, $colfield order by $lineorder,$colorder";
459 ($debug) and warn $strcalc;
460 my $dbcalc = $dbh->prepare($strcalc);
461 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
463 my ($emptycol,$emptyrow);
464 while (my ($row, $col, $value) = $dbcalc->fetchrow) {
465 ($debug) and warn "filling table $row / $col / $value ";
466 unless (defined $col) {
470 unless (defined $row) {
474 $table{$row}->{$col} += $value;
475 $table{$row}->{totalrow} += $value;
476 $grantotal += $value;
478 push @loopcol, {coltitle => "NULL", coltitle_display => 'NULL'} if ($emptycol);
479 push @loopline,{rowtitle => "NULL", rowtitle_display => 'NULL'} if ($emptyrow);
481 foreach my $row (@loopline) {
483 #@loopcol ensures the order for columns is common with column titles
484 # and the number matches the number of columns
485 foreach my $col (@loopcol) {
486 my $value = $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
487 push @loopcell, {value => $value};
489 my $rowtitle = ($row->{rowtitle} eq "NULL") ? "zzEMPTY" : $row->{rowtitle};
491 'rowtitle_display' => $row->{rowtitle_display},
492 'rowtitle' => $rowtitle,
493 'loopcell' => \@loopcell,
494 'totalrow' => $table{$rowtitle}->{totalrow}
497 for my $col ( @loopcol ) {
499 foreach my $row (@looprow) {
500 $total += $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
501 $debug and warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
503 push @loopfooter, {'totalcol' => $total};
506 # the header of the table
507 $globalline{loopfilter}=\@loopfilter;
508 # the core of the table
509 $globalline{looprow} = \@looprow;
510 $globalline{loopcol} = \@loopcol;
511 # # the foot (totals by borrower type)
512 $globalline{loopfooter} = \@loopfooter;
513 $globalline{total} = $grantotal;
514 $globalline{line} = $line;
515 $globalline{column} = $column;
516 return [(\%globalline)];
519 sub null_to_zzempty ($) {
521 defined($string) or return 'zzEMPTY';
522 ($string eq "NULL") and return 'zzEMPTY';
523 return $string; # else return the valid value