Staff interface .po file updates
[koha.git] / reports / issues_stats.pl
blobf932a6f1f83145be09f37bda9a699184c11f6ed5
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<=10;$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 =" : "UNKNOWN FILTER ($i)";
214 # FIXME - no translation mechanism !
215 push @loopfilter, \%cell;
217 push @loopfilter,{crit=>"Event", filter=>$type };
218 push @loopfilter,{crit=>"Display by", filter=>$dsp } if ($dsp);
219 push @loopfilter,{crit=>"Select Day", filter=>$daysel } if ($daysel);
220 push @loopfilter,{crit=>"Select Month",filter=>$monthsel} if ($monthsel);
222 my @linefilter;
223 $debug and warn "filtres ". join "|", @filters;
224 my ($colsource, $linesource);
225 $linefilter[1] = @$filters[1] if ($line =~ /datetime/);
226 $linefilter[0] = ($line =~ /datetime/) ? @$filters[0] :
227 ($line =~ /category/) ? @$filters[2] :
228 ($line =~ /itemtype/) ? @$filters[3] :
229 ($line =~ /branch/ ) ? @$filters[4] :
230 ($line =~ /ccode/ ) ? @$filters[5] :
231 ($line =~ /location/) ? @$filters[6] :
232 ($line =~ /sort1/ ) ? @$filters[9] :
233 ($line =~ /sort2/ ) ? @$filters[10] : undef ;
234 if ($line =~ /ccode/ or $line =~ /location/) {
235 $linesource = 'items';
238 my @colfilter;
239 $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
240 $colfilter[0] = ($column =~ /datetime/) ? @$filters[0] :
241 ($column =~ /category/) ? @$filters[2] :
242 ($column =~ /itemtype/) ? @$filters[3] :
243 ($column =~ /branch/ ) ? @$filters[4] :
244 ($column =~ /ccode/ ) ? @$filters[5] :
245 ($column =~ /location/) ? @$filters[6] :
246 ($column =~ /sort1/ ) ? @$filters[9] :
247 ($column =~ /sort1/ ) ? @$filters[10] : undef ;
248 if ($column =~ /ccode/ or $column =~ /location/) {
249 $colsource = 'items';
251 # 1st, loop rows.
252 my $linefield;
253 if ($line =~ /datetime/) {
254 # by Day, Month or Year (1,2,3 respectively)
255 $linefield = ($dsp == 1) ? " dayname($line)" :
256 ($dsp == 2) ? "monthname($line)" :
257 ($dsp == 3) ? " Year($line)" :
258 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
259 } else {
260 $linefield = $line;
262 my $lineorder = ($linefield =~ /dayname/) ? "weekday($line)" :
263 ($linefield =~ /^month/ ) ? " month($line)" : $linefield;
265 my $strsth = "SELECT distinctrow $linefield FROM statistics, ";
266 # get stats on items if ccode or location, otherwise borrowers.
267 $strsth .= ($linesource eq 'items' ) ?
268 " items WHERE (statistics.itemnumber=items.itemnumber) " :
269 " borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
270 $strsth .= " AND $line is not null ";
272 if ($line =~ /datetime/) {
273 if ($linefilter[1] and ($linefilter[0])) {
274 $strsth .= " AND $line between ? AND ? ";
275 } elsif ($linefilter[1]) {
276 $strsth .= " AND $line < ? ";
277 } elsif ($linefilter[0]) {
278 $strsth .= " AND $line > ? ";
280 $strsth .= " AND type ='".$type."' " if $type;
281 $strsth .= " AND dayname(datetime) ='". $daysel ."' " if $daysel;
282 $strsth .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
283 } elsif ($linefilter[0]) {
284 $linefilter[0] =~ s/\*/%/g;
285 $strsth .= " AND $line LIKE ? ";
287 $strsth .=" group by $linefield order by $lineorder ";
288 $debug and warn $strsth;
289 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth};
290 my $sth = $dbh->prepare( $strsth );
291 if ((@linefilter) and ($linefilter[1])){
292 $sth->execute($linefilter[0],$linefilter[1]);
293 } elsif ($linefilter[0]) {
294 $sth->execute($linefilter[0]);
295 } else {
296 $sth->execute;
299 while (my ($celvalue) = $sth->fetchrow) {
300 my %cell = (rowtitle => $celvalue, totalrow => 0); # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display
301 $cell{rowtitle_display} =
302 ($line =~ /ccode/ ) ? $ccodes->{$celvalue} :
303 ($line =~ /location/) ? $locations->{$celvalue} :
304 ($line =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
305 $celvalue; # default fallback
306 if ($line =~ /sort1/) {
307 foreach (@$Bsort1) {
308 ($celvalue eq $_->{authorised_value}) or next;
309 $cell{rowtitle_display} = $_->{lib} and last;
311 } elsif ($line =~ /sort2/) {
312 foreach (@$Bsort2) {
313 ($celvalue eq $_->{authorised_value}) or next;
314 $cell{rowtitle_display} = $_->{lib} and last;
316 } elsif ($line =~ /category/) {
317 foreach (@$categoryloop) {
318 ($celvalue eq $_->{categorycode}) or next;
319 $cell{rowtitle_display} = $_->{description} and last;
322 push @loopline, \%cell;
325 # 2nd, loop cols.
326 my $colfield;
327 my $colorder;
328 if ($column =~ /datetime/) {
329 #Display by Day, Month or Year (1,2,3 respectively)
330 $colfield = ($dsp == 1) ? " dayname($column)" :
331 ($dsp == 2) ? "monthname($column)" :
332 ($dsp == 3) ? " Year($column)" :
333 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
334 } else {
335 $colfield = $column;
337 $colorder = ($colfield =~ /dayname/) ? "weekday($column)" :
338 ($colfield =~ /^month/ ) ? " month($column)" : $colfield;
339 my $strsth2 = "SELECT distinctrow $colfield FROM statistics, ";
340 # get stats on items if ccode or location, otherwise borrowers.
341 $strsth2 .= ($colsource eq 'items' ) ?
342 "items WHERE (statistics.itemnumber=items.itemnumber) " :
343 "borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
344 $strsth2 .= " AND $column IS NOT NULL ";
346 if ($column =~ /datetime/){
347 if (($colfilter[1]) and ($colfilter[0])){
348 $strsth2 .= " AND $column BETWEEN ? AND ? " ;
349 } elsif ($colfilter[1]) {
350 $strsth2 .= " AND $column < ? " ;
351 } elsif ($colfilter[0]) {
352 $strsth2 .= " AND $column > ? " ;
354 $strsth2 .= " AND type ='". $type ."' " if $type;
355 $strsth2 .= " AND dayname(datetime) ='". $daysel ."' " if $daysel;
356 $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
357 } elsif ($colfilter[0]) {
358 $colfilter[0] =~ s/\*/%/g;
359 $strsth2 .= " AND $column LIKE ? " ;
361 $strsth2 .=" GROUP BY $colfield ORDER BY $colorder ";
363 my $sth2 = $dbh->prepare($strsth2);
364 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth2};
365 if ((@colfilter) and ($colfilter[1])){
366 $sth2->execute($colfilter[0], $colfilter[1]);
367 } elsif ($colfilter[0]) {
368 $sth2->execute($colfilter[0]);
369 } else {
370 $sth2->execute;
373 while (my ($celvalue) = $sth2->fetchrow) {
374 my %cell = (coltitle => $celvalue); # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display
375 $cell{coltitle_display} =
376 ($column =~ /ccode/ ) ? $ccodes->{$celvalue} :
377 ($column =~ /location/) ? $locations->{$celvalue} :
378 ($column =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
379 $celvalue; # default fallback
380 if ($column =~ /sort1/) {
381 foreach (@$Bsort1) {
382 ($celvalue eq $_->{authorised_value}) or next;
383 $cell{coltitle_display} = $_->{lib} and last;
385 } elsif ($column =~ /sort2/) {
386 foreach (@$Bsort2) {
387 ($celvalue eq $_->{authorised_value}) or next;
388 $cell{coltitle_display} = $_->{lib} and last;
390 } elsif ($column =~ /category/) {
391 foreach (@$categoryloop) {
392 ($celvalue eq $_->{categorycode}) or next;
393 $cell{coltitle_display} = $_->{description} and last;
396 push @loopcol, \%cell;
399 #Initialization of cell values.....
400 my %table;
401 foreach my $row (@loopline) {
402 foreach my $col (@loopcol) {
403 $debug and warn " init table : $row->{rowtitle} ( $row->{rowtitle_display} ) / $col->{coltitle} ( $col->{coltitle_display} ) ";
404 $table{$row->{rowtitle}}->{$col->{coltitle}} = 0;
406 $table{$row->{rowtitle}}->{totalrow} = 0;
409 # preparing calculation
410 my $strcalc = "SELECT $linefield, $colfield, ";
411 $strcalc .= ($process == 1) ? " COUNT(*) " :
412 ($process == 2) ? "(COUNT(DISTINCT borrowers.borrowernumber))" :
413 ($process == 3) ? "(COUNT(DISTINCT statistics.itemnumber))" : '';
414 if ($process == 4) {
415 my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
416 $rqbookcount->execute;
417 my ($bookcount) = $rqbookcount->fetchrow;
418 $strcalc .= "100*(COUNT(DISTINCT statistics.itemnumber))/ $bookcount " ;
420 $strcalc .= "
421 FROM statistics
422 LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber
424 $strcalc .= "LEFT JOIN items ON statistics.itemnumber=items.itemnumber "
425 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or ($colsource eq 'items')
426 ||@$filters[5]||@$filters[6]||@$filters[7]||@$filters[8]);
428 $strcalc .= "WHERE 1=1 ";
429 @$filters = map {defined($_) and s/\*/%/g; $_} @$filters;
430 $strcalc .= " AND statistics.datetime > '" . @$filters[0] ."'" if (@$filters[0] );
431 $strcalc .= " AND statistics.datetime < '" . @$filters[1] ."'" if (@$filters[1] );
432 $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] ."'" if (@$filters[2] );
433 $strcalc .= " AND statistics.itemtype LIKE '" . @$filters[3] ."'" if (@$filters[3] );
434 $strcalc .= " AND statistics.branch LIKE '" . @$filters[4] ."'" if (@$filters[4] );
435 $strcalc .= " AND items.ccode LIKE '" . @$filters[5] ."'" if (@$filters[5] );
436 $strcalc .= " AND items.location LIKE '" . @$filters[6] ."'" if (@$filters[6] );
437 $strcalc .= " AND items.itemcallnumber >='" . @$filters[7] ."'" if (@$filters[7] );
438 $strcalc .= " AND items.itemcallnumber <'" . @$filters[8] ."'" if (@$filters[8] );
439 $strcalc .= " AND borrowers.sort1 LIKE '" . @$filters[9] ."'" if (@$filters[9] );
440 $strcalc .= " AND borrowers.sort2 LIKE '" . @$filters[10]."'" if (@$filters[10]);
441 $strcalc .= " AND dayname(datetime) LIKE '" . $daysel ."'" if ($daysel );
442 $strcalc .= " AND monthname(datetime) LIKE '" . $monthsel ."'" if ($monthsel);
443 $strcalc .= " AND statistics.type LIKE '" . $type ."'" if ($type );
445 $strcalc .= " GROUP BY $linefield, $colfield order by $lineorder,$colorder";
446 ($debug) and warn $strcalc;
447 my $dbcalc = $dbh->prepare($strcalc);
448 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
449 $dbcalc->execute;
450 my ($emptycol,$emptyrow);
451 while (my ($row, $col, $value) = $dbcalc->fetchrow) {
452 ($debug) and warn "filling table $row / $col / $value ";
453 unless (defined $col) {
454 $emptycol = 1;
455 $col = "zzEMPTY" ;
457 unless (defined $row) {
458 $emptyrow = 1;
459 $row = "zzEMPTY";
461 $table{$row}->{$col} += $value;
462 $table{$row}->{totalrow} += $value;
463 $grantotal += $value;
465 push @loopcol, {coltitle => "NULL", coltitle_display => 'NULL'} if ($emptycol);
466 push @loopline,{rowtitle => "NULL", rowtitle_display => 'NULL'} if ($emptyrow);
468 foreach my $row (@loopline) {
469 my @loopcell;
470 #@loopcol ensures the order for columns is common with column titles
471 # and the number matches the number of columns
472 foreach my $col (@loopcol) {
473 my $value = $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
474 push @loopcell, {value => $value};
476 my $rowtitle = ($row->{rowtitle} eq "NULL") ? "zzEMPTY" : $row->{rowtitle};
477 push @looprow, {
478 'rowtitle_display' => $row->{rowtitle_display},
479 'rowtitle' => $rowtitle,
480 'loopcell' => \@loopcell,
481 'totalrow' => $table{$rowtitle}->{totalrow}
484 for my $col ( @loopcol ) {
485 my $total = 0;
486 foreach my $row (@looprow) {
487 $total += $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
488 $debug and warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
490 push @loopfooter, {'totalcol' => $total};
493 # the header of the table
494 $globalline{loopfilter}=\@loopfilter;
495 # the core of the table
496 $globalline{looprow} = \@looprow;
497 $globalline{loopcol} = \@loopcol;
498 # # the foot (totals by borrower type)
499 $globalline{loopfooter} = \@loopfooter;
500 $globalline{total} = $grantotal;
501 $globalline{line} = $line;
502 $globalline{column} = $column;
503 return [(\%globalline)];
506 sub null_to_zzempty ($) {
507 my $string = shift;
508 defined($string) or return 'zzEMPTY';
509 ($string eq "NULL") and return 'zzEMPTY';
510 return $string; # else return the valid value