Bug 7268: Fixing failing tests for translatable templates
[koha.git] / reports / issues_stats.pl
blob2f8a7e359f011c9355f75a48147e2d1fa73e7c97
1 #!/usr/bin/perl
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
11 # version.
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.
21 use strict;
22 #use warnings; FIXME - Bug 2505
24 use CGI;
25 use Date::Manip;
27 use C4::Auth;
28 use C4::Debug;
29 use C4::Context;
30 use C4::Branch; # GetBranches
31 use C4::Koha;
32 use C4::Output;
33 use C4::Circulation;
34 use C4::Reports;
35 use C4::Dates qw/format_date format_date_in_iso/;
36 use C4::Members;
38 =head1 NAME
40 plugin that shows circulation stats
42 =head1 DESCRIPTION
44 =over 2
46 =cut
48 # my $debug = 1; # override for now.
49 my $input = new CGI;
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,
66 query => $input,
67 type => "intranet",
68 authnotrequired => 0,
69 flagsrequired => {reports => '*'},
70 debug => 0,
71 });
72 our $sep = $input->param("sep");
73 $sep = "\t" if ($sep eq 'tabulation');
74 $template->param(do_it => $do_it,
75 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
78 my $itemtypes = GetItemTypes();
79 my $categoryloop = GetBorrowercategoryList;
81 my $ccodes = GetKohaAuthorisedValues("items.ccode");
82 my $locations = GetKohaAuthorisedValues("items.location");
84 my $Bsort1 = GetAuthorisedValues("Bsort1");
85 my $Bsort2 = GetAuthorisedValues("Bsort2");
86 my ($hassort1,$hassort2);
87 $hassort1=1 if $Bsort1;
88 $hassort2=1 if $Bsort2;
91 if ($do_it) {
92 # Displaying results
93 my $results = calculate($line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters);
94 if ($output eq "screen"){
95 # Printing results to screen
96 $template->param(mainloop => $results);
97 output_html_with_http_headers $input, $cookie, $template->output;
98 } else {
99 # Printing to a csv file
100 print $input->header(-type => 'application/vnd.sun.xml.calc',
101 -encoding => 'utf-8',
102 -attachment=>"$basename.csv",
103 -filename=>"$basename.csv" );
104 my $cols = @$results[0]->{loopcol};
105 my $lines = @$results[0]->{looprow};
106 # header top-right
107 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
108 # Other header
109 foreach my $col ( @$cols ) {
110 print $col->{coltitle}.$sep;
112 print "Total\n";
113 # Table
114 foreach my $line ( @$lines ) {
115 my $x = $line->{loopcell};
116 print $line->{rowtitle}.$sep;
117 print map {$_->{value}.$sep} @$x;
118 print $line->{totalrow}, "\n";
120 # footer
121 print "TOTAL";
122 $cols = @$results[0]->{loopfooter};
123 print map {$sep.$_->{totalcol}} @$cols;
124 print $sep.@$results[0]->{total};
126 exit(1); # exit either way after $do_it
129 my $dbh = C4::Context->dbh;
130 my @values;
131 my %labels;
132 my %select;
134 # create itemtype arrayref for <select>.
135 my @itemtypeloop;
136 for my $itype ( sort {$itemtypes->{$a}->{description} cmp $itemtypes->{$b}->{description}} keys(%$itemtypes)) {
137 push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{description} } ;
140 # location list
141 my @locations;
142 foreach (sort keys %$locations) {
143 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
146 my @ccodes;
147 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
148 push @ccodes, { code => $_, description => $ccodes->{$_} };
151 my $CGIextChoice=CGI::scrolling_list(
152 -name => 'MIME',
153 -id => 'MIME',
154 -values => ['CSV'], # FIXME translation
155 -size => 1,
156 -multiple => 0 );
158 my $CGIsepChoice=GetDelimiterChoices;
160 $template->param(
161 categoryloop => $categoryloop,
162 itemtypeloop => \@itemtypeloop,
163 locationloop => \@locations,
164 ccodeloop => \@ccodes,
165 branchloop => GetBranchesLoop(C4::Context->userenv->{'branch'}),
166 hassort1=> $hassort1,
167 hassort2=> $hassort2,
168 Bsort1 => $Bsort1,
169 Bsort2 => $Bsort2,
170 CGIextChoice => $CGIextChoice,
171 CGIsepChoice => $CGIsepChoice,
173 output_html_with_http_headers $input, $cookie, $template->output;
175 sub calculate {
176 my ($line, $column, $dsp, $type,$daysel,$monthsel ,$process, $filters) = @_;
177 my @loopfooter;
178 my @loopcol;
179 my @loopline;
180 my @looprow;
181 my %globalline;
182 my $grantotal =0;
183 # extract parameters
184 my $dbh = C4::Context->dbh;
186 # Filters
187 # Checking filters
189 my @loopfilter;
190 for (my $i=0;$i<=12;$i++) {
191 my %cell;
192 (@$filters[$i]) or next;
193 if (($i==1) and (@$filters[$i-1])) {
194 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
196 # format the dates filters, otherwise just fill as is
197 if ($i>=2) {
198 $cell{filter} = @$filters[$i];
199 } else {
200 $cell{filter} = format_date(@$filters[$i]);
202 $cell{crit} =
203 ( $i == 0 ) ? "Period From"
204 : ( $i == 1 ) ? "Period To"
205 : ( $i == 2 ) ? "Patron Category ="
206 : ( $i == 3 ) ? "Item Type ="
207 : ( $i == 4 ) ? "Library ="
208 : ( $i == 5 ) ? "Collection ="
209 : ( $i == 6 ) ? "Location ="
210 : ( $i == 7 ) ? "Item callnumber >="
211 : ( $i == 8 ) ? "Item callnumber <"
212 : ( $i == 9 ) ? "sort1 ="
213 : ( $i == 10 ) ? "sort2 ="
214 : ( $i == 11 ) ? "Home library ="
215 : ( $i == 12 )? "Holding library ="
216 : "UNKNOWN FILTER ($i)";
218 # FIXME - no translation mechanism !
219 push @loopfilter, \%cell;
221 push @loopfilter,{crit=>"Event", filter=>$type };
222 push @loopfilter,{crit=>"Display by", filter=>$dsp } if ($dsp);
223 push @loopfilter,{crit=>"Select Day", filter=>$daysel } if ($daysel);
224 push @loopfilter,{crit=>"Select Month",filter=>$monthsel} if ($monthsel);
226 my @linefilter;
227 $debug and warn "filtres ". join "|", @filters;
228 my ($colsource, $linesource);
229 $linefilter[1] = @$filters[1] if ($line =~ /datetime/);
230 $linefilter[0] =
231 ( $line =~ /datetime/ ) ? @$filters[0]
232 : ( $line =~ /category/ ) ? @$filters[2]
233 : ( $line =~ /itemtype/ ) ? @$filters[3]
234 : ( $line =~ /^branch/ ) ? @$filters[4]
235 : ( $line =~ /ccode/ ) ? @$filters[5]
236 : ( $line =~ /location/ ) ? @$filters[6]
237 : ( $line =~ /sort1/ ) ? @$filters[9]
238 : ( $line =~ /sort2/ ) ? @$filters[10]
239 : ( $line =~ /homebranch/) ? @$filters[11]
240 : ( $line =~ /holdingbranch/) ? @$filters[12]
241 : undef;
243 if ( $line =~ /ccode/ or $line =~ /location/ or $line =~ /homebranch/ or $line =~ /holdingbranch/ ) {
244 $linesource = 'items';
247 my @colfilter;
248 $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
249 $colfilter[0] =
250 ( $column =~ /datetime/ ) ? @$filters[0]
251 : ( $column =~ /category/ ) ? @$filters[2]
252 : ( $column =~ /itemtype/ ) ? @$filters[3]
253 : ( $column =~ /^branch/ ) ? @$filters[4]
254 : ( $column =~ /ccode/ ) ? @$filters[5]
255 : ( $column =~ /location/ ) ? @$filters[6]
256 : ( $column =~ /sort1/ ) ? @$filters[9]
257 : ( $column =~ /sort1/ ) ? @$filters[10]
258 : ( $column =~ /homebranch/) ? @$filters[11]
259 : ( $column =~ /holdingbranch/) ? @$filters[12]
260 : undef;
262 if ( $column =~ /ccode/ or $column =~ /location/ or $column =~ /homebranch/ or $column =~ /holdingbranch/ ) {
263 $colsource = 'items';
265 # 1st, loop rows.
266 my $linefield;
267 if ($line =~ /datetime/) {
268 # by Day, Month or Year (1,2,3 respectively)
269 $linefield = ($dsp == 1) ? " dayname($line)" :
270 ($dsp == 2) ? "monthname($line)" :
271 ($dsp == 3) ? " Year($line)" :
272 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
273 } else {
274 $linefield = $line;
276 my $lineorder = ($linefield =~ /dayname/) ? "weekday($line)" :
277 ($linefield =~ /^month/ ) ? " month($line)" : $linefield;
279 my $strsth = "SELECT distinctrow $linefield FROM statistics, ";
280 # get stats on items if ccode or location, otherwise borrowers.
281 $strsth .= ($linesource eq 'items' ) ?
282 " items WHERE (statistics.itemnumber=items.itemnumber) " :
283 " borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
284 $strsth .= " AND $line is not null ";
286 if ($line =~ /datetime/) {
287 if ($linefilter[1] and ($linefilter[0])) {
288 $strsth .= " AND $line between ? AND ? ";
289 } elsif ($linefilter[1]) {
290 $strsth .= " AND $line < ? ";
291 } elsif ($linefilter[0]) {
292 $strsth .= " AND $line > ? ";
294 $strsth .= " AND type ='".$type."' " if $type;
295 $strsth .= " AND dayname(datetime) ='". $daysel ."' " if $daysel;
296 $strsth .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
297 } elsif ($linefilter[0]) {
298 $linefilter[0] =~ s/\*/%/g;
299 $strsth .= " AND $line LIKE ? ";
301 $strsth .=" group by $linefield order by $lineorder ";
302 $debug and warn $strsth;
303 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth};
304 my $sth = $dbh->prepare( $strsth );
305 if ((@linefilter) and ($linefilter[1])){
306 $sth->execute($linefilter[0],$linefilter[1]);
307 } elsif ($linefilter[0]) {
308 $sth->execute($linefilter[0]);
309 } else {
310 $sth->execute;
313 while (my ($celvalue) = $sth->fetchrow) {
314 my %cell = (rowtitle => $celvalue, totalrow => 0); # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display
315 $cell{rowtitle_display} =
316 ($line =~ /ccode/ ) ? $ccodes->{$celvalue} :
317 ($line =~ /location/) ? $locations->{$celvalue} :
318 ($line =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
319 $celvalue; # default fallback
320 if ($line =~ /sort1/) {
321 foreach (@$Bsort1) {
322 ($celvalue eq $_->{authorised_value}) or next;
323 $cell{rowtitle_display} = $_->{lib} and last;
325 } elsif ($line =~ /sort2/) {
326 foreach (@$Bsort2) {
327 ($celvalue eq $_->{authorised_value}) or next;
328 $cell{rowtitle_display} = $_->{lib} and last;
330 } elsif ($line =~ /category/) {
331 foreach (@$categoryloop) {
332 ($celvalue eq $_->{categorycode}) or next;
333 $cell{rowtitle_display} = $_->{description} and last;
336 push @loopline, \%cell;
339 # 2nd, loop cols.
340 my $colfield;
341 my $colorder;
342 if ($column =~ /datetime/) {
343 #Display by Day, Month or Year (1,2,3 respectively)
344 $colfield = ($dsp == 1) ? " dayname($column)" :
345 ($dsp == 2) ? "monthname($column)" :
346 ($dsp == 3) ? " Year($column)" :
347 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
348 } else {
349 $colfield = $column;
351 $colorder = ($colfield =~ /dayname/) ? "weekday($column)" :
352 ($colfield =~ /^month/ ) ? " month($column)" : $colfield;
353 my $strsth2 = "SELECT distinctrow $colfield FROM statistics, ";
354 # get stats on items if ccode or location, otherwise borrowers.
355 $strsth2 .= ($colsource eq 'items' ) ?
356 "items WHERE (statistics.itemnumber=items.itemnumber) " :
357 "borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
358 $strsth2 .= " AND $column IS NOT NULL ";
360 if ($column =~ /datetime/){
361 if (($colfilter[1]) and ($colfilter[0])){
362 $strsth2 .= " AND $column BETWEEN ? AND ? " ;
363 } elsif ($colfilter[1]) {
364 $strsth2 .= " AND $column < ? " ;
365 } elsif ($colfilter[0]) {
366 $strsth2 .= " AND $column > ? " ;
368 $strsth2 .= " AND type ='". $type ."' " if $type;
369 $strsth2 .= " AND dayname(datetime) ='". $daysel ."' " if $daysel;
370 $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
371 } elsif ($colfilter[0]) {
372 $colfilter[0] =~ s/\*/%/g;
373 $strsth2 .= " AND $column LIKE ? " ;
375 $strsth2 .=" GROUP BY $colfield ORDER BY $colorder ";
377 my $sth2 = $dbh->prepare($strsth2);
378 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth2};
379 if ((@colfilter) and ($colfilter[1])){
380 $sth2->execute($colfilter[0], $colfilter[1]);
381 } elsif ($colfilter[0]) {
382 $sth2->execute($colfilter[0]);
383 } else {
384 $sth2->execute;
387 while (my ($celvalue) = $sth2->fetchrow) {
388 my %cell = (coltitle => $celvalue); # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display
389 $cell{coltitle_display} =
390 ($column =~ /ccode/ ) ? $ccodes->{$celvalue} :
391 ($column =~ /location/) ? $locations->{$celvalue} :
392 ($column =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
393 $celvalue; # default fallback
394 if ($column =~ /sort1/) {
395 foreach (@$Bsort1) {
396 ($celvalue eq $_->{authorised_value}) or next;
397 $cell{coltitle_display} = $_->{lib} and last;
399 } elsif ($column =~ /sort2/) {
400 foreach (@$Bsort2) {
401 ($celvalue eq $_->{authorised_value}) or next;
402 $cell{coltitle_display} = $_->{lib} and last;
404 } elsif ($column =~ /category/) {
405 foreach (@$categoryloop) {
406 ($celvalue eq $_->{categorycode}) or next;
407 $cell{coltitle_display} = $_->{description} and last;
410 push @loopcol, \%cell;
413 #Initialization of cell values.....
414 my %table;
415 foreach my $row (@loopline) {
416 foreach my $col (@loopcol) {
417 $debug and warn " init table : $row->{rowtitle} ( $row->{rowtitle_display} ) / $col->{coltitle} ( $col->{coltitle_display} ) ";
418 $table{$row->{rowtitle}}->{$col->{coltitle}} = 0;
420 $table{$row->{rowtitle}}->{totalrow} = 0;
423 # preparing calculation
424 my $strcalc = "SELECT $linefield, $colfield, ";
425 $strcalc .= ($process == 1) ? " COUNT(*) " :
426 ($process == 2) ? "(COUNT(DISTINCT borrowers.borrowernumber))" :
427 ($process == 3) ? "(COUNT(DISTINCT statistics.itemnumber))" : '';
428 if ($process == 4) {
429 my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
430 $rqbookcount->execute;
431 my ($bookcount) = $rqbookcount->fetchrow;
432 $strcalc .= "100*(COUNT(DISTINCT statistics.itemnumber))/ $bookcount " ;
434 $strcalc .= "
435 FROM statistics
436 LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber
438 $strcalc .= "LEFT JOIN items ON statistics.itemnumber=items.itemnumber "
439 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or ($colsource eq 'items')
440 ||@$filters[5]||@$filters[6]||@$filters[7]||@$filters[8]);
442 $strcalc .= "WHERE 1=1 ";
443 @$filters = map {defined($_) and s/\*/%/g; $_} @$filters;
444 $strcalc .= " AND statistics.datetime > '" . @$filters[0] ."'" if (@$filters[0] );
445 $strcalc .= " AND statistics.datetime < '" . @$filters[1] ."'" if (@$filters[1] );
446 $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] ."'" if (@$filters[2] );
447 $strcalc .= " AND statistics.itemtype LIKE '" . @$filters[3] ."'" if (@$filters[3] );
448 $strcalc .= " AND statistics.branch LIKE '" . @$filters[4] ."'" if (@$filters[4] );
449 $strcalc .= " AND items.ccode LIKE '" . @$filters[5] ."'" if (@$filters[5] );
450 $strcalc .= " AND items.location LIKE '" . @$filters[6] ."'" if (@$filters[6] );
451 $strcalc .= " AND items.itemcallnumber >='" . @$filters[7] ."'" if (@$filters[7] );
452 $strcalc .= " AND items.itemcallnumber <'" . @$filters[8] ."'" if (@$filters[8] );
453 $strcalc .= " AND borrowers.sort1 LIKE '" . @$filters[9] ."'" if (@$filters[9] );
454 $strcalc .= " AND borrowers.sort2 LIKE '" . @$filters[10]."'" if (@$filters[10]);
455 $strcalc .= " AND dayname(datetime) LIKE '" . $daysel ."'" if ($daysel );
456 $strcalc .= " AND monthname(datetime) LIKE '" . $monthsel ."'" if ($monthsel);
457 $strcalc .= " AND statistics.type LIKE '" . $type ."'" if ($type );
459 $strcalc .= " GROUP BY $linefield, $colfield order by $lineorder,$colorder";
460 ($debug) and warn $strcalc;
461 my $dbcalc = $dbh->prepare($strcalc);
462 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
463 $dbcalc->execute;
464 my ($emptycol,$emptyrow);
465 while (my ($row, $col, $value) = $dbcalc->fetchrow) {
466 ($debug) and warn "filling table $row / $col / $value ";
467 unless (defined $col) {
468 $emptycol = 1;
469 $col = "zzEMPTY" ;
471 unless (defined $row) {
472 $emptyrow = 1;
473 $row = "zzEMPTY";
475 $table{$row}->{$col} += $value;
476 $table{$row}->{totalrow} += $value;
477 $grantotal += $value;
479 push @loopcol, {coltitle => "NULL", coltitle_display => 'NULL'} if ($emptycol);
480 push @loopline,{rowtitle => "NULL", rowtitle_display => 'NULL'} if ($emptyrow);
482 foreach my $row (@loopline) {
483 my @loopcell;
484 #@loopcol ensures the order for columns is common with column titles
485 # and the number matches the number of columns
486 foreach my $col (@loopcol) {
487 my $value = $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
488 push @loopcell, {value => $value};
490 my $rowtitle = ($row->{rowtitle} eq "NULL") ? "zzEMPTY" : $row->{rowtitle};
491 push @looprow, {
492 'rowtitle_display' => $row->{rowtitle_display},
493 'rowtitle' => $rowtitle,
494 'loopcell' => \@loopcell,
495 'totalrow' => $table{$rowtitle}->{totalrow}
498 for my $col ( @loopcol ) {
499 my $total = 0;
500 foreach my $row (@looprow) {
501 $total += $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
502 $debug and warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
504 push @loopfooter, {'totalcol' => $total};
507 # the header of the table
508 $globalline{loopfilter}=\@loopfilter;
509 # the core of the table
510 $globalline{looprow} = \@looprow;
511 $globalline{loopcol} = \@loopcol;
512 # # the foot (totals by borrower type)
513 $globalline{loopfooter} = \@loopfooter;
514 $globalline{total} = $grantotal;
515 $globalline{line} = $line;
516 $globalline{column} = $column;
517 return [(\%globalline)];
520 sub null_to_zzempty ($) {
521 my $string = shift;
522 defined($string) or return 'zzEMPTY';
523 ($string eq "NULL") and return 'zzEMPTY';
524 return $string; # else return the valid value