Bug 25548: Remove Apache rewrite directives that trigger redirects
[koha.git] / reports / issues_avg_stats.pl
blobca074b5dfdb33e1d0797e15be69a624aa43bf8b5
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
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 use Modern::Perl;
22 use C4::Auth;
23 use CGI qw ( -utf8 );
24 use C4::Context;
25 use C4::Output;
26 use C4::Koha;
27 use C4::Circulation;
28 use C4::Reports;
29 use Koha::DateUtils;
30 use Koha::ItemTypes;
31 use Koha::Patron::Categories;
32 use Date::Calc qw(Delta_Days);
34 =head1 NAME
36 plugin that shows a stats on borrowers
38 =head1 DESCRIPTION
40 =cut
42 my $input = CGI->new;
43 my $do_it=$input->param('do_it');
44 my $fullreportname = "reports/issues_avg_stats.tt";
45 my $line = $input->param("Line");
46 my $column = $input->param("Column");
47 my @filters = $input->multi_param("Filter");
48 $filters[0] = eval { output_pref( { dt => dt_from_string( $filters[0]), dateonly => 1, dateformat => 'iso' } ); }
49 if ( $filters[0] );
50 $filters[1] = eval { output_pref( { dt => dt_from_string( $filters[1]), dateonly => 1, dateformat => 'iso' } ); }
51 if ( $filters[1] );
52 $filters[2] = eval { output_pref( { dt => dt_from_string( $filters[2]), dateonly => 1, dateformat => 'iso' } ); }
53 if ( $filters[2] );
54 $filters[3] = eval { output_pref( { dt => dt_from_string( $filters[3]), dateonly => 1, dateformat => 'iso' } ); }
55 if ( $filters[3] );
58 my $podsp = $input->param("IssueDisplay");
59 my $rodsp = $input->param("ReturnDisplay");
60 my $calc = $input->param("Cellvalue");
61 my $output = $input->param("output");
62 my $basename = $input->param("basename");
64 #warn "calcul : ".$calc;
65 my ($template, $borrowernumber, $cookie)
66 = get_template_and_user({template_name => $fullreportname,
67 query => $input,
68 type => "intranet",
69 flagsrequired => {reports => '*'},
70 debug => 1,
71 });
72 our $sep = $input->param("sep");
73 $sep = "\t" if ($sep eq 'tabulation');
74 $template->param(do_it => $do_it,
76 if ($do_it) {
77 # Displaying results
78 my $results = calculate($line, $column, $rodsp, $podsp, $calc, \@filters);
79 if ($output eq "screen"){
80 # Printing results to screen
81 $template->param(mainloop => $results);
82 output_html_with_http_headers $input, $cookie, $template->output;
83 exit;
84 } else {
85 # Printing to a csv file
86 print $input->header(-type => 'application/vnd.sun.xml.calc',
87 -encoding => 'utf-8',
88 -attachment=>"$basename.csv",
89 -filename=>"$basename.csv" );
90 my $cols = @$results[0]->{loopcol};
91 my $lines = @$results[0]->{looprow};
92 # header top-right
93 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
94 # Other header
95 foreach my $col ( @$cols ) {
96 print $col->{coltitle}.$sep;
98 print "Total\n";
99 # Table
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};
107 print "\n";
109 # footer
110 print "TOTAL";
111 $cols = @$results[0]->{loopfooter};
112 foreach my $col ( @$cols ) {
113 print $sep.$col->{totalcol};
115 print $sep.@$results[0]->{total};
116 exit;
118 # Displaying choices
119 } else {
120 my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']});
122 my $itemtypes = Koha::ItemTypes->search_with_localization;
124 my $dbh = C4::Context->dbh;
125 my $req = $dbh->prepare("select distinctrow sort1 from borrowers where sort1 is not null order by sort1");
126 $req->execute;
127 my @selects1;
128 my $hassort1;
129 while (my ($value) =$req->fetchrow) {
130 $hassort1 =1 if ($value);
131 push @selects1, $value;
133 my $Sort1 = {
134 values => \@selects1,
137 $req = $dbh->prepare("select distinctrow sort2 from borrowers where sort2 is not null order by sort2");
138 $req->execute;
139 my @selects2;
140 my $hassort2;
141 my $hglghtsort2;
142 while (my ($value) =$req->fetchrow) {
143 $hassort2 =1 if ($value);
144 $hglghtsort2= !($hassort1);
145 push @selects2, $value;
147 my $Sort2 = {
148 values => \@selects2,
151 my $CGIsepChoice=GetDelimiterChoices;
153 $template->param(
154 patron_categories => $patron_categories,
155 itemtypes => $itemtypes,
156 hassort1 => $hassort1,
157 hassort2 => $hassort2,
158 HlghtSort2 => $hglghtsort2,
159 Sort1 => $Sort1,
160 Sort2 => $Sort2,
161 CGIsepChoice => $CGIsepChoice
163 output_html_with_http_headers $input, $cookie, $template->output;
169 sub calculate {
170 my ($line, $column, $rodsp, $podsp, $process, $filters) = @_;
171 my @mainloop;
172 my @loopfooter;
173 my @loopcol;
174 my @loopline;
175 my @looprow;
176 my %globalline;
177 my $grantotal =0;
178 my $itype = C4::Context->preference('item-level_itypes') ? "items.itype" : "biblioitems.itemtype";
179 # extract parameters
180 my $dbh = C4::Context->dbh;
182 # Filters
183 # Checking filters
185 my @loopfilter;
186 for (my $i=0;$i<=6;$i++) {
187 my %cell;
188 if ( @$filters[$i] ) {
189 if (($i==1) and (@$filters[$i-1])) {
190 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
192 # format the dates filters, otherwise just fill as is
193 if ($i>=4) {
194 $cell{filter} .= @$filters[$i];
195 } else {
196 $cell{filter} .= eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
197 if ( @$filters[$i] );
199 $cell{crit} .="Issue From" if ($i==0);
200 $cell{crit} .="Issue To" if ($i==1);
201 $cell{crit} .="Issue Month" if ($i==2);
202 $cell{crit} .="Issue Day" if ($i==3);
203 $cell{crit} .="Return From" if ($i==4);
204 $cell{crit} .="Return To" if ($i==5);
205 $cell{crit} .="Return Month" if ($i==6);
206 $cell{crit} .="Return Day" if ($i==7);
207 $cell{crit} .="Borrower Cat" if ($i==8);
208 $cell{crit} .="Doc Type" if ($i==9);
209 $cell{crit} .="Branch" if ($i==10);
210 $cell{crit} .="Sort1" if ($i==11);
211 $cell{crit} .="Sort2" if ($i==12);
212 push @loopfilter, \%cell;
215 push @loopfilter,{crit=>"Issue Display",filter=>$rodsp} if ($rodsp);
216 push @loopfilter,{crit=>"Return Display",filter=>$podsp} if ($podsp);
220 my @linefilter;
221 # warn "filtres ".@filters[0];
222 # warn "filtres ".@filters[1];
223 # warn "filtres ".@filters[2];
224 # warn "filtres ".@filters[3];
225 $line = "old_issues.".$line if ($line=~/branchcode/) or ($line=~/timestamp/);
226 if ( $line=~/itemtype/ ) { $line = $itype; }
227 $linefilter[0] = @$filters[0] if ($line =~ /timestamp/ ) ;
228 $linefilter[1] = @$filters[1] if ($line =~ /timestamp/ ) ;
229 $linefilter[2] = @$filters[2] if ($line =~ /timestamp/ ) ;
230 $linefilter[3] = @$filters[3] if ($line =~ /timestamp/ ) ;
231 $linefilter[0] = @$filters[4] if ($line =~ /returndate/ ) ;
232 $linefilter[1] = @$filters[5] if ($line =~ /returndate/ ) ;
233 $linefilter[2] = @$filters[6] if ($line =~ /returndate/ ) ;
234 $linefilter[3] = @$filters[7] if ($line =~ /returndate/ ) ;
235 $linefilter[0] = @$filters[8] if ($line =~ /category/ ) ;
236 $linefilter[0] = @$filters[9] if ($line eq $itype);
237 $linefilter[0] = @$filters[10] if ($line =~ /branch/ ) ;
238 $linefilter[0] = @$filters[11] if ($line =~ /sort1/ ) ;
239 $linefilter[0] = @$filters[12] if ($line =~ /sort2/ ) ;
241 $column = "old_issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/));
242 if ( $column=~/itemtype/ ) { $column = $itype; }
243 my @colfilter ;
244 $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ ) ;
245 $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ ) ;
246 $colfilter[2] = @$filters[2] if ($column =~ /timestamp/ ) ;
247 $colfilter[3] = @$filters[3] if ($column =~ /timestamp/ ) ;
248 $colfilter[0] = @$filters[4] if ($column =~ /returndate/ ) ;
249 $colfilter[1] = @$filters[5] if ($column =~ /returndate/ ) ;
250 $colfilter[2] = @$filters[6] if ($column =~ /returndate/ ) ;
251 $colfilter[3] = @$filters[7] if ($column =~ /returndate/ ) ;
252 $colfilter[0] = @$filters[8] if ($column =~ /category/ ) ;
253 $colfilter[0] = @$filters[9] if ($column eq $itype);
254 $colfilter[0] = @$filters[10] if ($column =~ /branch/ ) ;
255 $colfilter[0] = @$filters[11] if ($column =~ /sort1/ ) ;
256 $colfilter[0] = @$filters[12] if ($column =~ /sort2/ ) ;
258 # 1st, loop rows.
259 my $linefield;
260 my $lineorder;
261 if ((($line =~/timestamp/) and ($podsp == 1)) or (($line =~/returndate/) and ($rodsp == 1))) {
262 #Display by day
263 $linefield .="dayname($line)";
264 $lineorder .="weekday($line)";
265 } elsif ((($line =~/timestamp/) and ($podsp == 2)) or (($line =~/returndate/) and ($rodsp == 2))) {
266 #Display by Month
267 $linefield .="monthname($line)";
268 $lineorder .="month($line)";
269 } elsif ((($line =~/timestamp/) and ($podsp == 3)) or (($line =~/returndate/) and ($rodsp == 3))) {
270 #Display by Year
271 $linefield .="Year($line)";
272 $lineorder .= $line;
273 } elsif (($line=~/timestamp/) or ($line=~/returndate/)){
274 $linefield .= "date_format(\'$line\',\"%Y-%m-%d\")";
275 $lineorder .= $line;
276 } else {
277 $linefield .= $line;
278 $lineorder .= $line;
281 my $strsth;
282 $strsth .= "select distinctrow $linefield
283 FROM `old_issues`
284 LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber
285 LEFT JOIN items ON old_issues.itemnumber=items.itemnumber
286 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
287 WHERE 1";
289 if (($line=~/timestamp/) or ($line=~/returndate/)){
290 if ($linefilter[1] and ($linefilter[0])){
291 $strsth .= " AND $line BETWEEN '$linefilter[0]' AND '$linefilter[1]' " ;
292 } elsif ($linefilter[1]) {
293 $strsth .= " AND $line < \'$linefilter[1]\' " ;
294 } elsif ($linefilter[0]) {
295 $strsth .= " AND $line > \'$linefilter[0]\' " ;
297 if ($linefilter[2]){
298 $strsth .= " AND dayname($line) = '$linefilter[2]' " ;
300 if ($linefilter[3]){
301 $strsth .= " AND monthname($line) = '$linefilter[3]' " ;
303 } elsif ($linefilter[0]) {
304 $linefilter[0] =~ s/\*/%/g;
305 $strsth .= " AND $line LIKE '$linefilter[0]' " ;
307 $strsth .=" GROUP BY $linefield";
308 $strsth .=" ORDER BY $lineorder";
310 my $sth = $dbh->prepare( $strsth );
311 $sth->execute;
313 while ( my ($celvalue) = $sth->fetchrow) {
314 my %cell;
315 if ($celvalue) {
316 $cell{rowtitle} = $celvalue;
317 } else {
318 $cell{rowtitle} = "";
320 $cell{totalrow} = 0;
321 push @loopline, \%cell;
324 # 2nd, loop cols.
325 my $colfield;
326 my $colorder;
327 if ((($column =~/timestamp/) and ($podsp == 1)) or (($column =~/returndate/) and ($rodsp == 1))) {
328 #Display by day
329 $colfield .="dayname($column)";
330 $colorder .="weekday($column)";
331 } elsif ((($column =~/timestamp/) and ($podsp == 2)) or (($column =~/returndate/) and ($rodsp == 2))) {
332 #Display by Month
333 $colfield .="monthname($column)";
334 $colorder .="month($column)";
335 } elsif ((($column =~/timestamp/) and ($podsp == 3)) or (($column =~/returndate/) and ($rodsp == 3))) {
336 #Display by Year
337 $colfield .="Year($column)";
338 $colorder .= $column;
339 } elsif (($column=~/timestamp/) or ($column=~/returndate/)){
340 $colfield .= 'date_format( '."'".$column."'". ', "%Y-%m-%d")';
341 $colorder .= $column;
342 } else {
343 $colfield .= $column;
344 $colorder .= $column;
347 my $strsth2;
348 $strsth2 .= "SELECT distinctrow $colfield
349 FROM `old_issues`
350 LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber
351 LEFT JOIN items ON items.itemnumber=old_issues.itemnumber
352 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
353 WHERE 1";
355 if (($column=~/timestamp/) or ($column=~/returndate/)){
356 if ($colfilter[1] and ($colfilter[0])){
357 $strsth2 .= " AND $column BETWEEN '$colfilter[0]' AND '$colfilter[1]' " ;
358 } elsif ($colfilter[1]) {
359 $strsth2 .= " AND $column < '$colfilter[1]' " ;
360 } elsif ($colfilter[0]) {
361 $strsth2 .= " AND $column > '$colfilter[0]' " ;
363 if ($colfilter[2]){
364 $strsth2 .= " AND dayname($column) = '$colfilter[2]' " ;
366 if ($colfilter[3]){
367 $strsth2 .= " AND monthname($column) = '$colfilter[3]' " ;
369 } elsif ($colfilter[0]) {
370 $colfilter[0] =~ s/\*/%/g;
371 $strsth2 .= " AND $column LIKE '$colfilter[0]' " ;
373 $strsth2 .=" GROUP BY $colfield";
374 $strsth2 .=" ORDER BY $colorder";
376 my $sth2 = $dbh->prepare( $strsth2 );
378 $sth2->execute;
380 while (my ($celvalue) = $sth2->fetchrow) {
381 my %cell;
382 my %ft;
383 # warn "coltitle :".$celvalue;
384 $cell{coltitle} = $celvalue;
385 $ft{totalcol} = 0;
386 push @loopcol, \%cell;
388 # warn "fin des titres colonnes";
390 my $i=0;
391 my $hilighted=-1;
393 #Initialization of cell values.....
394 my %table;
395 my %wgttable;
396 my %cnttable;
398 # warn "init table";
399 foreach my $row ( @loopline ) {
400 foreach my $col ( @loopcol ) {
401 # warn " init table : $row->{rowtitle} / $col->{coltitle} ";
402 $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
404 $table{$row->{rowtitle}}->{totalrow}=0;
407 # preparing calculation
408 my $strcalc ;
410 # Processing average loanperiods
411 $strcalc .= "SELECT $linefield, $colfield, ";
412 $strcalc .= " issuedate, returndate, COUNT(*) FROM `old_issues`,borrowers,biblioitems LEFT JOIN items ON (biblioitems.biblioitemnumber=items.biblioitemnumber) WHERE old_issues.itemnumber=items.itemnumber AND old_issues.borrowernumber=borrowers.borrowernumber";
414 @$filters[0]=~ s/\*/%/g if (@$filters[0]);
415 $strcalc .= " AND old_issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
416 @$filters[1]=~ s/\*/%/g if (@$filters[1]);
417 $strcalc .= " AND old_issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] );
418 @$filters[4]=~ s/\*/%/g if (@$filters[4]);
419 $strcalc .= " AND old_issues.returndate > '" . @$filters[4] ."'" if ( @$filters[4] );
420 @$filters[5]=~ s/\*/%/g if (@$filters[5]);
421 $strcalc .= " AND old_issues.returndate < '" . @$filters[5] ."'" if ( @$filters[5] );
422 @$filters[8]=~ s/\*/%/g if (@$filters[8]);
423 $strcalc .= " AND borrowers.categorycode like '" . @$filters[8] ."'" if ( @$filters[8] );
424 @$filters[9]=~ s/\*/%/g if (@$filters[9]);
425 $strcalc .= " AND $itype like '" . @$filters[9] ."'" if ( @$filters[9] );
426 @$filters[10]=~ s/\*/%/g if (@$filters[10]);
427 $strcalc .= " AND old_issues.branchcode like '" . @$filters[10] ."'" if ( @$filters[10] );
428 @$filters[11]=~ s/\*/%/g if (@$filters[11]);
429 $strcalc .= " AND borrowers.sort1 like '" . @$filters[11] ."'" if ( @$filters[11] );
430 @$filters[12]=~ s/\*/%/g if (@$filters[12]);
431 $strcalc .= " AND borrowers.sort2 like '" . @$filters[12] ."'" if ( @$filters[12] );
432 $strcalc .= " AND dayname(timestamp) like '" . @$filters[2]."'" if (@$filters[2]);
433 $strcalc .= " AND monthname(timestamp) like '" . @$filters[3] ."'" if ( @$filters[3] );
434 $strcalc .= " AND dayname(returndate) like '" . @$filters[5]."'" if (@$filters[5]);
435 $strcalc .= " AND monthname(returndate) like '" . @$filters[6] ."'" if ( @$filters[6] );
437 $strcalc .= " group by $linefield, $colfield, issuedate, returndate order by $linefield, $colfield";
439 my $dbcalc = $dbh->prepare($strcalc);
440 $dbcalc->execute;
441 # warn "filling table";
442 my $issues_count=0;
443 my $loanlength;
444 my $emptycol;
446 while (my @data = $dbcalc->fetchrow) {
447 my ($row, $col, $issuedate, $returndate, $weight)=@data;
448 # warn "filling table $row / $col / $issuedate / $returndate /$weight";
449 $emptycol=1 if (!defined($col));
450 $col = "zzEMPTY" if (!defined($col));
451 $row = "zzEMPTY" if (!defined($row));
452 # fill returndate to avoid an error with date calc (needed for all non returned issues)
453 $returndate= join '-',Date::Calc::Today if $returndate eq '0000-00-00';
454 # DateCalc returns => 0:0:WK:DD:HH:MM:SS the weeks, days, hours, minutes,
455 # and seconds between the two
456 $loanlength = Delta_Days(split(/-/,$issuedate),split (/-/,$returndate)) ;
457 # warn "512 Same row and col DateCalc returns :$loanlength with return ". $returndate ."issue ". $issuedate ."weight : ". $weight;
458 # warn "513 row :".$row." column :".$col;
459 $table{$row}->{$col}+=$weight*$loanlength;
460 # $table{$row}->{totalrow}+=$weight*$loanlength;
461 $cnttable{$row}->{$col}= 1;
462 $wgttable{$row}->{$col}+=$weight;
465 push @loopcol,{coltitle => "NULL"} if ($emptycol);
467 foreach my $row ( sort keys %table ) {
468 my @loopcell;
469 #@loopcol ensures the order for columns is common with column titles
470 # and the number matches the number of columns
471 my $colcount=0;
472 foreach my $col ( @loopcol ) {
473 my $value;
474 if ($table{$row}->{
475 ( ( $col->{coltitle} eq 'NULL' )
476 or ( $col->{coltitle} eq q{} )
477 ) ? 'zzEMPTY' : $col->{coltitle}
480 $value = $table{$row}->{
481 ( ( $col->{coltitle} eq 'NULL' )
482 or ( $col->{coltitle} eq q{} )
483 ) ? 'zzEMPTY' : $col->{coltitle}
484 } / $wgttable{$row}->{
485 ( ( $col->{coltitle} eq 'NULL' )
486 or ( $col->{coltitle} eq q{} )
487 ) ? 'zzEMPTY' : $col->{coltitle}
490 $table{$row}->{(($col->{coltitle} eq "NULL")or ($col->{coltitle} eq ""))?"zzEMPTY":$col->{coltitle}} = $value;
491 $table{$row}->{totalrow}+=$value;
492 #warn "row : $row col:$col $cnttable{$row}->{(($col->{coltitle} eq \"NULL\")or ($col->{coltitle} eq \"\"))?\"zzEMPTY\":$col->{coltitle}}";
493 $colcount+=$cnttable{$row}->{(($col->{coltitle} eq "NULL")or ($col->{coltitle} eq ""))?"zzEMPTY":$col->{coltitle}};
494 push @loopcell, {value => ($value)?sprintf("%.2f",$value):0 } ;
496 #warn "row : $row colcount:$colcount";
497 my $total;
498 if ( $colcount > 0 ) {
499 $total = $table{$row}->{totalrow} / $colcount;
501 push @looprow,
502 { 'rowtitle' => ( $row eq "zzEMPTY" ) ? "NULL" : $row,
503 'loopcell' => \@loopcell,
504 'hilighted' => ( $hilighted > 0 ),
505 'totalrow' => ($total) ? sprintf( "%.2f", $total ) : 0
507 $hilighted = -$hilighted;
510 # # warn "footer processing";
511 foreach my $col ( @loopcol ) {
512 my $total=0;
513 my $nbrow=0;
514 foreach my $row ( @looprow ) {
515 $total += $cnttable{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}}*$table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
516 $nbrow +=$cnttable{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};;
517 # warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
519 # warn "summ for column ".$col->{coltitle}." = ".$total;
520 $total = $total/$nbrow if ($nbrow);
521 push @loopfooter, {'totalcol' => ($total)?sprintf("%.2f",$total):0};
526 # the header of the table
527 $globalline{loopfilter}=\@loopfilter;
528 # the core of the table
529 $globalline{looprow} = \@looprow;
530 $globalline{loopcol} = \@loopcol;
531 # # the foot (totals by borrower type)
532 $globalline{loopfooter} = \@loopfooter;
533 $globalline{total}= $grantotal;
534 $globalline{line} = $line;
535 $globalline{column} = $column;
536 push @mainloop,\%globalline;
537 return \@mainloop;