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 with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA 02111-1307 USA
29 use C4::Branch; # GetBranches
33 use C4::Dates qw/format_date format_date_in_iso/;
38 plugin that shows circulation stats
46 # my $debug = 1; # override for now.
48 my $fullreportname = "reports/issues_stats.tmpl";
49 my $do_it = $input->param('do_it');
50 my $line = $input->param("Line");
51 my $column = $input->param("Column");
52 my @filters = $input->param("Filter");
53 $filters[0]=format_date_in_iso($filters[0]);
54 $filters[1]=format_date_in_iso($filters[1]);
55 my $podsp = $input->param("DisplayBy");
56 my $type = $input->param("PeriodTypeSel");
57 my $daysel = $input->param("PeriodDaySel");
58 my $monthsel = $input->param("PeriodMonthSel");
59 my $calc = $input->param("Cellvalue");
60 my $output = $input->param("output");
61 my $basename = $input->param("basename");
62 my $mime = $input->param("MIME");
63 my $del = $input->param("sep");
64 my ($template, $borrowernumber, $cookie) = get_template_and_user({
65 template_name => $fullreportname,
69 flagsrequired => {reports => 1},
72 $template->param(do_it => $do_it,
73 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
76 my $itemtypes = GetItemTypes();
77 my $categoryloop = GetBorrowercategoryList;
79 my $ccodes = GetKohaAuthorisedValues("items.ccode");
80 my $locations = GetKohaAuthorisedValues("items.location");
82 my $Bsort1 = GetAuthorisedValues("Bsort1");
83 my $Bsort2 = GetAuthorisedValues("Bsort2");
84 my ($hassort1,$hassort2);
85 $hassort1=1 if $Bsort1;
86 $hassort2=1 if $Bsort2;
91 my $results = calculate($line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters);
92 if ($output eq "screen"){
93 # Printing results to screen
94 $template->param(mainloop => $results);
95 output_html_with_http_headers $input, $cookie, $template->output;
97 # Printing to a csv file
98 print $input->header(-type => 'application/vnd.sun.xml.calc',
100 -attachment=>"$basename.csv",
101 -filename=>"$basename.csv" );
102 my $cols = @$results[0]->{loopcol};
103 my $lines = @$results[0]->{looprow};
104 my $sep = C4::Context->preference("delimiter");
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(1); # exit either way after $do_it
128 my $dbh = C4::Context->dbh;
133 # create itemtype arrayref for <select>.
135 for my $itype ( keys(%$itemtypes)) {
136 push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{description} } ;
139 my $branches=GetBranches();
141 foreach (keys %$branches) {
142 my $thisbranch = ''; # FIXME
145 selected => ($thisbranch eq $_ ? 1 : 0),
146 code => $branches->{$_}->{'branchcode'},
147 description => $branches->{$_}->{'branchname'},
149 push @branchloop, \%row;
154 foreach (sort keys %$locations) {
155 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
159 foreach (keys %$ccodes) {
160 push @ccodes, { code => $_, description => $ccodes->{$_} };
164 my @mime = (C4::Context->preference("MIME"));
166 my $CGIextChoice=CGI::scrolling_list(
173 my @dels = ( C4::Context->preference("delimiter") );
174 my $CGIsepChoice=CGI::scrolling_list(
182 categoryloop => $categoryloop,
183 itemtypeloop => \@itemtypeloop,
184 locationloop => \@locations,
185 ccodeloop => \@ccodes,
186 branchloop => \@branchloop,
187 hassort1=> $hassort1,
188 hassort2=> $hassort2,
191 CGIextChoice => $CGIextChoice,
192 CGIsepChoice => $CGIsepChoice,
194 output_html_with_http_headers $input, $cookie, $template->output;
197 my ($line, $column, $dsp, $type,$daysel,$monthsel ,$process, $filters) = @_;
205 my $dbh = C4::Context->dbh;
211 for (my $i=0;$i<=10;$i++) {
213 (@$filters[$i]) or next;
214 if (($i==1) and (@$filters[$i-1])) {
215 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
217 # format the dates filters, otherwise just fill as is
219 $cell{filter} = @$filters[$i];
221 $cell{filter} = format_date(@$filters[$i]);
224 ($i==0) ? "Period From" :
225 ($i==1) ? "Period To" :
226 ($i==2) ? "Patron Category =" :
227 ($i==3) ? "Item Type =" :
228 ($i==4) ? "Library =" :
229 ($i==5) ? "Collection =" :
230 ($i==6) ? "Location =" :
231 ($i==7) ? "Item callnumber >=" :
232 ($i==8) ? "Item callnumber <" :
233 ($i==9) ? "sort1 =" :
234 ($i==10)? "sort2 =" : "UNKNOWN FILTER ($i)";
235 # FIXME - no translation mechanism !
236 push @loopfilter, \%cell;
238 push @loopfilter,{crit=>"Event", filter=>$type };
239 push @loopfilter,{crit=>"Display by", filter=>$dsp } if ($dsp);
240 push @loopfilter,{crit=>"Select Day", filter=>$daysel } if ($daysel);
241 push @loopfilter,{crit=>"Select Month",filter=>$monthsel} if ($monthsel);
244 $debug and warn "filtres ". join "|", @filters;
245 my ($colsource, $linesource);
246 $linefilter[1] = @$filters[1] if ($line =~ /datetime/);
247 $linefilter[0] = ($line =~ /datetime/) ? @$filters[0] :
248 ($line =~ /category/) ? @$filters[2] :
249 ($line =~ /itemtype/) ? @$filters[3] :
250 ($line =~ /branch/ ) ? @$filters[4] :
251 ($line =~ /ccode/ ) ? @$filters[5] :
252 ($line =~ /location/) ? @$filters[6] :
253 ($line =~ /sort1/ ) ? @$filters[9] :
254 ($line =~ /sort2/ ) ? @$filters[10] : undef ;
255 if ($line =~ /ccode/ or $line =~ /location/) {
256 $linesource = 'items';
260 $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
261 $colfilter[0] = ($column =~ /datetime/) ? @$filters[0] :
262 ($column =~ /category/) ? @$filters[2] :
263 ($column =~ /itemtype/) ? @$filters[3] :
264 ($column =~ /branch/ ) ? @$filters[4] :
265 ($column =~ /ccode/ ) ? @$filters[5] :
266 ($column =~ /location/) ? @$filters[6] :
267 ($column =~ /sort1/ ) ? @$filters[9] :
268 ($column =~ /sort1/ ) ? @$filters[10] : undef ;
269 if ($column =~ /ccode/ or $column =~ /location/) {
270 $colsource = 'items';
274 if ($line =~ /datetime/) {
275 # by Day, Month or Year (1,2,3 respectively)
276 $linefield = ($dsp == 1) ? " dayname($line)" :
277 ($dsp == 2) ? "monthname($line)" :
278 ($dsp == 3) ? " Year($line)" :
279 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
283 my $lineorder = ($linefield =~ /dayname/) ? "weekday($line)" :
284 ($linefield =~ /^month/ ) ? " month($line)" : $linefield;
286 my $strsth = "SELECT distinctrow $linefield FROM statistics, ";
287 # get stats on items if ccode or location, otherwise borrowers.
288 $strsth .= ($linesource eq 'items' ) ?
289 " items WHERE (statistics.itemnumber=items.itemnumber) " :
290 " borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
291 $strsth .= " AND $line is not null ";
293 if ($line =~ /datetime/) {
294 if ($linefilter[1] and ($linefilter[0])) {
295 $strsth .= " AND $line between ? AND ? ";
296 } elsif ($linefilter[1]) {
297 $strsth .= " AND $line < ? ";
298 } elsif ($linefilter[0]) {
299 $strsth .= " AND $line > ? ";
301 $strsth .= " AND type ='".$type."' " if $type;
302 $strsth .= " AND dayname(datetime) ='". $daysel ."' " if $daysel;
303 $strsth .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
304 } elsif ($linefilter[0]) {
305 $linefilter[0] =~ s/\*/%/g;
306 $strsth .= " AND $line LIKE ? ";
308 $strsth .=" group by $linefield order by $lineorder ";
309 $debug and warn $strsth;
310 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth};
311 my $sth = $dbh->prepare( $strsth );
312 if ((@linefilter) and ($linefilter[1])){
313 $sth->execute($linefilter[0],$linefilter[1]);
314 } elsif ($linefilter[0]) {
315 $sth->execute($linefilter[0]);
320 while (my ($celvalue) = $sth->fetchrow) {
321 my %cell = (rowtitle => $celvalue, totalrow => 0); # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display
322 $cell{rowtitle_display} =
323 ($line =~ /ccode/ ) ? $ccodes->{$celvalue} :
324 ($line =~ /location/) ? $locations->{$celvalue} :
325 ($line =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
326 $celvalue; # default fallback
327 if ($line =~ /sort1/) {
329 ($celvalue eq $_->{authorised_value}) or next;
330 $cell{rowtitle_display} = $_->{lib} and last;
332 } elsif ($line =~ /sort2/) {
334 ($celvalue eq $_->{authorised_value}) or next;
335 $cell{rowtitle_display} = $_->{lib} and last;
337 } elsif ($line =~ /category/) {
338 foreach (@$categoryloop) {
339 ($celvalue eq $_->{categorycode}) or next;
340 $cell{rowtitle_display} = $_->{description} and last;
343 push @loopline, \%cell;
349 if ($column =~ /datetime/) {
350 #Display by Day, Month or Year (1,2,3 respectively)
351 $colfield = ($dsp == 1) ? " dayname($column)" :
352 ($dsp == 2) ? "monthname($column)" :
353 ($dsp == 3) ? " Year($column)" :
354 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
358 $colorder = ($colfield =~ /dayname/) ? "weekday($line)" :
359 ($colfield =~ /^month/ ) ? " month($line)" : $colfield;
360 my $strsth2 = "SELECT distinctrow $colfield FROM statistics, ";
361 # get stats on items if ccode or location, otherwise borrowers.
362 $strsth2 .= ($colsource eq 'items' ) ?
363 "items WHERE (statistics.itemnumber=items.itemnumber) " :
364 "borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
365 $strsth2 .= " AND $column IS NOT NULL ";
367 if ($column =~ /datetime/){
368 if (($colfilter[1]) and ($colfilter[0])){
369 $strsth2 .= " AND $column BETWEEN ? AND ? " ;
370 } elsif ($colfilter[1]) {
371 $strsth2 .= " AND $column < ? " ;
372 } elsif ($colfilter[0]) {
373 $strsth2 .= " AND $column > ? " ;
375 $strsth2 .= " AND type ='". $type ."' " if $type;
376 $strsth2 .= " AND dayname(datetime) ='". $daysel ."' " if $daysel;
377 $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
378 } elsif ($colfilter[0]) {
379 $colfilter[0] =~ s/\*/%/g;
380 $strsth2 .= " AND $column LIKE ? " ;
382 $strsth2 .=" GROUP BY $colfield ORDER BY $colorder ";
384 my $sth2 = $dbh->prepare($strsth2);
385 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth2};
386 if ((@colfilter) and ($colfilter[1])){
387 $sth2->execute($colfilter[0], $colfilter[1]);
388 } elsif ($colfilter[0]) {
389 $sth2->execute($colfilter[0]);
394 while (my ($celvalue) = $sth2->fetchrow) {
395 my %cell = (coltitle => $celvalue); # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display
396 $cell{coltitle_display} =
397 ($column =~ /ccode/ ) ? $ccodes->{$celvalue} :
398 ($column =~ /location/) ? $locations->{$celvalue} :
399 ($column =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
400 $celvalue; # default fallback
401 if ($column =~ /sort1/) {
403 ($celvalue eq $_->{authorised_value}) or next;
404 $cell{coltitle_display} = $_->{lib} and last;
406 } elsif ($column =~ /sort2/) {
408 ($celvalue eq $_->{authorised_value}) or next;
409 $cell{coltitle_display} = $_->{lib} and last;
411 } elsif ($column =~ /category/) {
412 foreach (@$categoryloop) {
413 ($celvalue eq $_->{categorycode}) or next;
414 $cell{coltitle_display} = $_->{description} and last;
417 push @loopcol, \%cell;
420 #Initialization of cell values.....
422 foreach my $row (@loopline) {
423 foreach my $col (@loopcol) {
424 $debug and warn " init table : $row->{rowtitle} ( $row->{rowtitle_display} ) / $col->{coltitle} ( $col->{coltitle_display} ) ";
425 $table{$row->{rowtitle}}->{$col->{coltitle}} = 0;
427 $table{$row->{rowtitle}}->{totalrow} = 0;
430 # preparing calculation
431 my $strcalc = "SELECT $linefield, $colfield, ";
432 $strcalc .= ($process == 1) ? " COUNT(*) " :
433 ($process == 2) ? "(COUNT(DISTINCT borrowers.borrowernumber))" :
434 ($process == 3) ? "(COUNT(DISTINCT issues.itemnumber))" : '';
436 my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
437 $rqbookcount->execute;
438 my ($bookcount) = $rqbookcount->fetchrow;
439 $strcalc .= "100*(COUNT(DISTINCT issues.itemnumber))/ $bookcount " ;
443 LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber
445 $strcalc .= "LEFT JOIN items ON statistics.itemnumber=items.itemnumber " if (($colsource eq 'items')||@$filters[5]||@$filters[6]||@$filters[7]||@$filters[8]);
447 $strcalc .= "WHERE 1=1 ";
448 @$filters = map {defined($_) and s/\*/%/g; $_} @$filters;
449 $strcalc .= " AND statistics.datetime > '" . @$filters[0] ."'" if (@$filters[0] );
450 $strcalc .= " AND statistics.datetime < '" . @$filters[1] ."'" if (@$filters[1] );
451 $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] ."'" if (@$filters[2] );
452 $strcalc .= " AND statistics.itemtype LIKE '" . @$filters[3] ."'" if (@$filters[3] );
453 $strcalc .= " AND statistics.branch LIKE '" . @$filters[4] ."'" if (@$filters[4] );
454 $strcalc .= " AND items.ccode LIKE '" . @$filters[5] ."'" if (@$filters[5] );
455 $strcalc .= " AND items.location LIKE '" . @$filters[6] ."'" if (@$filters[6] );
456 $strcalc .= " AND items.itemcallnumber >='" . @$filters[7] ."'" if (@$filters[7] );
457 $strcalc .= " AND items.itemcallnumber <'" . @$filters[8] ."'" if (@$filters[8] );
458 $strcalc .= " AND borrowers.sort1 LIKE '" . @$filters[9] ."'" if (@$filters[9] );
459 $strcalc .= " AND borrowers.sort2 LIKE '" . @$filters[10]."'" if (@$filters[10]);
460 $strcalc .= " AND dayname(datetime) LIKE '" . $daysel ."'" if ($daysel );
461 $strcalc .= " AND monthname(datetime) LIKE '" . $monthsel ."'" if ($monthsel);
462 $strcalc .= " AND statistics.type LIKE '" . $type ."'" if ($type );
464 $strcalc .= " GROUP BY $linefield, $colfield order by $lineorder,$colorder";
465 ($debug) and warn $strcalc;
466 my $dbcalc = $dbh->prepare($strcalc);
467 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
469 my ($emptycol,$emptyrow);
470 while (my ($row, $col, $value) = $dbcalc->fetchrow) {
471 ($debug) and warn "filling table $row / $col / $value ";
472 unless (defined $col) {
476 unless (defined $row) {
480 $table{$row}->{$col} += $value;
481 $table{$row}->{totalrow} += $value;
482 $grantotal += $value;
484 push @loopcol, {coltitle => "NULL", coltitle_display => 'NULL'} if ($emptycol);
485 push @loopline,{rowtitle => "NULL", rowtitle_display => 'NULL'} if ($emptyrow);
487 foreach my $row (@loopline) {
489 #@loopcol ensures the order for columns is common with column titles
490 # and the number matches the number of columns
491 foreach my $col (@loopcol) {
492 my $value = $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
493 push @loopcell, {value => $value};
495 my $rowtitle = ($row->{rowtitle} eq "NULL") ? "zzEMPTY" : $row->{rowtitle};
497 'rowtitle_display' => $row->{rowtitle_display},
498 'rowtitle' => $rowtitle,
499 'loopcell' => \@loopcell,
500 'totalrow' => $table{$rowtitle}->{totalrow}
503 for my $col ( @loopcol ) {
505 foreach my $row (@looprow) {
506 $total += $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
507 $debug and warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
509 push @loopfooter, {'totalcol' => $total};
512 # the header of the table
513 $globalline{loopfilter}=\@loopfilter;
514 # the core of the table
515 $globalline{looprow} = \@looprow;
516 $globalline{loopcol} = \@loopcol;
517 # # the foot (totals by borrower type)
518 $globalline{loopfooter} = \@loopfooter;
519 $globalline{total} = $grantotal;
520 $globalline{line} = $line;
521 $globalline{column} = $column;
522 return [(\%globalline)];
525 sub null_to_zzempty ($) {
527 defined($string) or return 'zzEMPTY';
528 ($string eq "NULL") and return 'zzEMPTY';
529 return $string; # else return the valid value