Bug 29955: Move populate_order_with_prices to Koha namespace
[koha-ffzg.git] / reports / issues_avg_stats.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
17 #
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>.
20
21 use Modern::Perl;
22 use C4::Auth qw( get_template_and_user );
23 use CGI qw ( -utf8 );
24 use C4::Context;
25 use C4::Output qw( output_html_with_http_headers );
26 use C4::Reports qw( GetDelimiterChoices );
27 use Koha::ItemTypes;
28 use Koha::Patron::Categories;
29 use Date::Calc qw( Delta_Days );
30
31 =head1 NAME
32
33 plugin that shows a stats on borrowers
34
35 =head1 DESCRIPTION
36
37 =cut
38
39 my $input = CGI->new;
40 my $do_it=$input->param('do_it');
41 my $fullreportname = "reports/issues_avg_stats.tt";
42 my $line = $input->param("Line");
43 my $column = $input->param("Column");
44 my @filters = $input->multi_param("Filter");
45
46 my $podsp = $input->param("IssueDisplay");
47 my $rodsp = $input->param("ReturnDisplay");
48 my $calc = $input->param("Cellvalue");
49 my $output = $input->param("output");
50 my $basename = $input->param("basename");
51
52 #warn "calcul : ".$calc;
53 my ($template, $borrowernumber, $cookie)
54     = get_template_and_user({template_name => $fullreportname,
55                 query => $input,
56                 type => "intranet",
57                 flagsrequired => {reports => '*'},
58                     });
59 our $sep     = $input->param("sep");
60 $sep = "\t" if ($sep eq 'tabulation');
61 $template->param(do_it => $do_it,
62     );
63 if ($do_it) {
64 # Displaying results
65     my $results = calculate($line, $column, $rodsp, $podsp, $calc, \@filters);
66     if ($output eq "screen"){
67 # Printing results to screen
68         $template->param(mainloop => $results);
69         output_html_with_http_headers $input, $cookie, $template->output;
70         exit;
71     } else {
72 # Printing to a csv file
73         print $input->header(-type => 'application/vnd.sun.xml.calc',
74                                     -encoding    => 'utf-8',
75             -attachment=>"$basename.csv",
76             -filename=>"$basename.csv" );
77         my $cols = @$results[0]->{loopcol};
78         my $lines = @$results[0]->{looprow};
79 # header top-right
80         print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
81 # Other header
82         foreach my $col ( @$cols ) {
83             print $col->{coltitle}.$sep;
84         }
85         print "Total\n";
86 # Table
87         foreach my $line ( @$lines ) {
88             my $x = $line->{loopcell};
89             print $line->{rowtitle}.$sep;
90             foreach my $cell (@$x) {
91                 print $cell->{value}.$sep;
92             }
93             print $line->{totalrow};
94             print "\n";
95         }
96 # footer
97         print "TOTAL";
98         $cols = @$results[0]->{loopfooter};
99         foreach my $col ( @$cols ) {
100             print $sep.$col->{totalcol};
101         }
102         print $sep.@$results[0]->{total};
103         exit;
104     }
105 # Displaying choices
106 } else {
107     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']});
108
109     my $itemtypes = Koha::ItemTypes->search_with_localization;
110
111     my $dbh = C4::Context->dbh;
112     my $req = $dbh->prepare("select distinctrow sort1 from borrowers where sort1 is not null order by sort1");
113     $req->execute;
114     my @selects1;
115     my $hassort1;
116     while (my ($value) =$req->fetchrow) {
117         $hassort1 =1 if ($value);
118         push @selects1, $value;
119     }
120     my $Sort1 = {
121         values   => \@selects1,
122     };
123     
124     $req = $dbh->prepare("select distinctrow sort2 from borrowers where sort2 is not null order by sort2");
125     $req->execute;
126     my @selects2;
127     my $hassort2;
128     my $hglghtsort2;
129     while (my ($value) =$req->fetchrow) {
130         $hassort2 =1 if ($value);
131         $hglghtsort2= !($hassort1);
132         push @selects2, $value;
133     }
134     my $Sort2 = {
135         values   => \@selects2,
136     };
137     
138     my $CGIsepChoice=GetDelimiterChoices;
139     
140     $template->param(
141                     patron_categories => $patron_categories,
142                     itemtypes    => $itemtypes,
143                     hassort1     => $hassort1,
144                     hassort2     => $hassort2,
145                     HlghtSort2   => $hglghtsort2,
146                     Sort1        => $Sort1,
147                     Sort2        => $Sort2,
148                     CGIsepChoice => $CGIsepChoice
149                     );
150 output_html_with_http_headers $input, $cookie, $template->output;
151 }
152
153
154
155
156 sub calculate {
157     my ($line, $column, $rodsp, $podsp, $process, $filters) = @_;
158     my @mainloop;
159     my @loopfooter;
160     my @loopcol;
161     my @loopline;
162     my @looprow;
163     my %globalline;
164     my $grantotal =0;
165     my $itype = C4::Context->preference('item-level_itypes') ? "items.itype" : "biblioitems.itemtype";
166 # extract parameters
167     my $dbh = C4::Context->dbh;
168
169 # Filters
170 # Checking filters
171 #
172     my @loopfilter;
173     for (my $i=0;$i<=6;$i++) {
174         my %cell;
175         if ( @$filters[$i] ) {
176             if (($i==1) and (@$filters[$i-1])) {
177                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
178             }
179             $cell{filter} .= @$filters[$i];
180             $cell{crit} .="Issue From" if ($i==0);
181             $cell{crit} .="Issue To" if ($i==1);
182             $cell{crit} .="Issue Month" if ($i==2);
183             $cell{crit} .="Issue Day" if ($i==3);
184             $cell{crit} .="Return From" if ($i==4);
185             $cell{crit} .="Return To" if ($i==5);
186             $cell{crit} .="Return Month" if ($i==6);
187             $cell{crit} .="Return Day" if ($i==7);
188             $cell{crit} .="Borrower Cat" if ($i==8);
189             $cell{crit} .="Doc Type" if ($i==9);
190             $cell{crit} .="Branch" if ($i==10);
191             $cell{crit} .="Sort1" if ($i==11);
192             $cell{crit} .="Sort2" if ($i==12);
193             push @loopfilter, \%cell;
194         }
195     }
196     push @loopfilter,{crit=>"Issue Display",filter=>$rodsp} if ($rodsp);
197     push @loopfilter,{crit=>"Return Display",filter=>$podsp} if ($podsp);
198
199     
200     
201     my @linefilter;
202 #       warn "filtres ".@filters[0];
203 #       warn "filtres ".@filters[1];
204 #       warn "filtres ".@filters[2];
205 #       warn "filtres ".@filters[3];
206     $line = "old_issues.".$line if ($line=~/branchcode/) or ($line=~/timestamp/);
207     if ( $line=~/itemtype/ ) { $line = $itype; }
208     $linefilter[0] = @$filters[0] if ($line =~ /timestamp/ )  ;
209     $linefilter[1] = @$filters[1] if ($line =~ /timestamp/ )  ;
210     $linefilter[2] = @$filters[2] if ($line =~ /timestamp/ )  ;
211     $linefilter[3] = @$filters[3] if ($line =~ /timestamp/ )  ;
212     $linefilter[0] = @$filters[4] if ($line =~ /returndate/ )  ;
213     $linefilter[1] = @$filters[5] if ($line =~ /returndate/ )  ;
214     $linefilter[2] = @$filters[6] if ($line =~ /returndate/ )  ;
215     $linefilter[3] = @$filters[7] if ($line =~ /returndate/ )  ;
216     $linefilter[0] = @$filters[8] if ($line =~ /category/ )  ;
217     $linefilter[0] = @$filters[9] if ($line eq $itype);
218     $linefilter[0] = @$filters[10] if ($line =~ /branch/ )  ;
219     $linefilter[0] = @$filters[11] if ($line =~ /sort1/ ) ;
220     $linefilter[0] = @$filters[12] if ($line =~ /sort2/ ) ;
221
222     $column = "old_issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/));
223     if ( $column=~/itemtype/ ) { $column = $itype; }
224     my @colfilter ;
225     $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ )  ;
226     $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ )  ;
227     $colfilter[2] = @$filters[2] if ($column =~ /timestamp/ )  ;
228     $colfilter[3] = @$filters[3] if ($column =~ /timestamp/ )  ;
229     $colfilter[0] = @$filters[4] if ($column =~ /returndate/ )  ;
230     $colfilter[1] = @$filters[5] if ($column =~ /returndate/ )  ;
231     $colfilter[2] = @$filters[6] if ($column =~ /returndate/ )  ;
232     $colfilter[3] = @$filters[7] if ($column =~ /returndate/ )  ;
233     $colfilter[0] = @$filters[8] if ($column =~ /category/ )  ;
234     $colfilter[0] = @$filters[9] if ($column eq $itype);
235     $colfilter[0] = @$filters[10] if ($column =~ /branch/ )  ;
236     $colfilter[0] = @$filters[11] if ($column =~ /sort1/ ) ;
237     $colfilter[0] = @$filters[12] if ($column =~ /sort2/ ) ;
238                                             
239 # 1st, loop rows.                             
240     my $linefield;
241     my $lineorder;                               
242     if ((($line =~/timestamp/) and ($podsp == 1)) or  (($line =~/returndate/) and ($rodsp == 1))) {
243         #Display by day
244         $linefield .="dayname($line)";  
245         $lineorder .="weekday($line)";  
246     } elsif ((($line =~/timestamp/) and ($podsp == 2)) or  (($line =~/returndate/) and ($rodsp == 2))) {
247         #Display by Month
248         $linefield .="monthname($line)";  
249         $lineorder .="month($line)";  
250     } elsif ((($line =~/timestamp/) and ($podsp == 3)) or  (($line =~/returndate/) and ($rodsp == 3))) {
251         #Display by Year
252         $linefield .="Year($line)";
253         $lineorder .= $line;  
254     } elsif (($line=~/timestamp/) or ($line=~/returndate/)){
255         $linefield .= "date_format(\'$line\',\"%Y-%m-%d\")";
256         $lineorder .= $line;  
257     } else {
258         $linefield .= $line;
259         $lineorder .= $line;  
260     }  
261     
262     my $strsth;
263     $strsth .= "select distinctrow $linefield 
264                 FROM `old_issues` 
265                 LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber
266                 LEFT JOIN items ON old_issues.itemnumber=items.itemnumber
267                 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber) 
268                 WHERE 1";
269     
270     if (($line=~/timestamp/) or ($line=~/returndate/)){
271         if ($linefilter[1] and ($linefilter[0])){
272             $strsth .= " AND $line BETWEEN '$linefilter[0]' AND '$linefilter[1]' " ;
273         } elsif ($linefilter[1]) {
274                 $strsth .= " AND $line < \'$linefilter[1]\' " ;
275         } elsif ($linefilter[0]) {
276             $strsth .= " AND $line > \'$linefilter[0]\' " ;
277         }
278         if ($linefilter[2]){
279             $strsth .= " AND dayname($line) = '$linefilter[2]' " ;
280         }
281         if ($linefilter[3]){
282             $strsth .= " AND monthname($line) = '$linefilter[3]' " ;
283         }
284     } elsif ($linefilter[0]) {
285         $linefilter[0] =~ s/\*/%/g;
286         $strsth .= " AND $line LIKE '$linefilter[0]' " ;
287     }
288     $strsth .=" GROUP BY $linefield";
289     $strsth .=" ORDER BY $lineorder";
290    
291     my $sth = $dbh->prepare( $strsth );
292     $sth->execute;
293
294     while ( my ($celvalue) = $sth->fetchrow) {
295         my %cell;
296         if ($celvalue) {
297             $cell{rowtitle} = $celvalue;
298         } else {
299             $cell{rowtitle} = "";
300         }
301         $cell{totalrow} = 0;
302         push @loopline, \%cell;
303     }
304
305 # 2nd, loop cols.
306     my $colfield;
307     my $colorder;                               
308     if ((($column =~/timestamp/) and ($podsp == 1)) or  (($column =~/returndate/) and ($rodsp == 1))) {
309         #Display by day
310         $colfield .="dayname($column)";  
311         $colorder .="weekday($column)";
312     } elsif ((($column =~/timestamp/) and ($podsp == 2)) or  (($column =~/returndate/) and ($rodsp == 2))) {
313         #Display by Month
314         $colfield .="monthname($column)";  
315         $colorder .="month($column)";  
316     } elsif ((($column =~/timestamp/) and ($podsp == 3)) or  (($column =~/returndate/) and ($rodsp == 3))) {
317         #Display by Year
318         $colfield .="Year($column)";
319         $colorder .= $column;
320     } elsif (($column=~/timestamp/) or ($column=~/returndate/)){
321         $colfield .= 'date_format( '."'".$column."'". ', "%Y-%m-%d")';
322         $colorder .= $column;
323     } else {
324         $colfield .= $column;
325         $colorder .= $column;
326     }  
327
328     my $strsth2;
329     $strsth2 .= "SELECT distinctrow $colfield 
330                   FROM `old_issues`
331                   LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber
332                   LEFT JOIN items  ON items.itemnumber=old_issues.itemnumber  
333                   LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber) 
334                   WHERE 1";
335     
336     if (($column=~/timestamp/) or ($column=~/returndate/)){
337         if ($colfilter[1] and ($colfilter[0])){
338             $strsth2 .= " AND $column BETWEEN '$colfilter[0]' AND '$colfilter[1]' " ;
339         } elsif ($colfilter[1]) {
340                 $strsth2 .= " AND $column < '$colfilter[1]' " ;
341         } elsif ($colfilter[0]) {
342             $strsth2 .= " AND $column > '$colfilter[0]' " ;
343         }
344         if ($colfilter[2]){
345             $strsth2 .= " AND dayname($column) = '$colfilter[2]' " ;
346         }
347         if ($colfilter[3]){
348             $strsth2 .= " AND monthname($column) = '$colfilter[3]' " ;
349         }
350     } elsif ($colfilter[0]) {
351         $colfilter[0] =~ s/\*/%/g;
352         $strsth2 .= " AND $column LIKE '$colfilter[0]' " ;
353     }
354     $strsth2 .=" GROUP BY $colfield";
355     $strsth2 .=" ORDER BY $colorder";
356     
357     my $sth2 = $dbh->prepare( $strsth2 );
358
359     $sth2->execute;
360
361     while (my ($celvalue) = $sth2->fetchrow) {
362         my %cell;
363         my %ft;
364 #               warn "coltitle :".$celvalue;
365         $cell{coltitle} = $celvalue;
366         $ft{totalcol} = 0;
367         push @loopcol, \%cell;
368     }
369 #       warn "fin des titres colonnes";
370
371     my $i=0;
372     my $hilighted=-1;
373     
374     #Initialization of cell values.....
375     my %table;
376     my %wgttable;
377     my %cnttable;
378     
379 #       warn "init table";
380     foreach my $row ( @loopline ) {
381         foreach my $col ( @loopcol ) {
382 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
383             $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
384         }
385         $table{$row->{rowtitle}}->{totalrow}=0;
386     }
387
388 # preparing calculation
389     my $strcalc ;
390     
391 # Processing average loanperiods
392     $strcalc .= "SELECT $linefield, $colfield, ";
393     $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";
394
395     @$filters[0]=~ s/\*/%/g if (@$filters[0]);
396     $strcalc .= " AND old_issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
397     @$filters[1]=~ s/\*/%/g if (@$filters[1]);
398     $strcalc .= " AND old_issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] );
399     @$filters[4]=~ s/\*/%/g if (@$filters[4]);
400     $strcalc .= " AND old_issues.returndate > '" . @$filters[4] ."'" if ( @$filters[4] );
401     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
402     $strcalc .= " AND old_issues.returndate < '" . @$filters[5] ."'" if ( @$filters[5] );
403     @$filters[8]=~ s/\*/%/g if (@$filters[8]);
404     $strcalc .= " AND borrowers.categorycode like '" . @$filters[8] ."'" if ( @$filters[8] );
405     @$filters[9]=~ s/\*/%/g if (@$filters[9]);
406     $strcalc .= " AND $itype like '" . @$filters[9] ."'" if ( @$filters[9] );
407     @$filters[10]=~ s/\*/%/g if (@$filters[10]);
408     $strcalc .= " AND old_issues.branchcode like '" . @$filters[10] ."'" if ( @$filters[10] );
409     @$filters[11]=~ s/\*/%/g if (@$filters[11]);
410     $strcalc .= " AND borrowers.sort1 like '" . @$filters[11] ."'" if ( @$filters[11] );
411     @$filters[12]=~ s/\*/%/g if (@$filters[12]);
412     $strcalc .= " AND borrowers.sort2 like '" . @$filters[12] ."'" if ( @$filters[12] );
413     $strcalc .= " AND dayname(timestamp) like '" . @$filters[2]."'" if (@$filters[2]);
414     $strcalc .= " AND monthname(timestamp) like '" . @$filters[3] ."'" if ( @$filters[3] );
415     $strcalc .= " AND dayname(returndate) like '" . @$filters[5]."'" if (@$filters[5]);
416     $strcalc .= " AND monthname(returndate) like '" . @$filters[6] ."'" if ( @$filters[6] );
417     
418     $strcalc .= " group by  $linefield, $colfield, issuedate, returndate order by $linefield, $colfield";
419     
420     my $dbcalc = $dbh->prepare($strcalc);
421     $dbcalc->execute;
422 #       warn "filling table";
423     my $issues_count=0;
424     my $loanlength; 
425     my $emptycol;
426
427     while (my  @data = $dbcalc->fetchrow) {
428         my ($row, $col, $issuedate, $returndate, $weight)=@data;
429 #               warn "filling table $row / $col / $issuedate / $returndate /$weight";
430         $emptycol=1 if (!defined($col));
431         $col = "zzEMPTY" if (!defined($col));
432         $row = "zzEMPTY" if (!defined($row));
433     #  DateCalc returns => 0:0:WK:DD:HH:MM:SS   the weeks, days, hours, minutes,
434     #  and seconds between the two
435         $loanlength = Delta_Days(split(/-/,$issuedate),split (/-/,$returndate)) ;
436     #           warn "512 Same row and col DateCalc returns :$loanlength with return ". $returndate ."issue ". $issuedate ."weight : ". $weight;
437     #           warn "513 row :".$row." column :".$col;
438         $table{$row}->{$col}+=$weight*$loanlength;
439     #           $table{$row}->{totalrow}+=$weight*$loanlength;
440         $cnttable{$row}->{$col}= 1;
441         $wgttable{$row}->{$col}+=$weight;
442     }
443     
444     push @loopcol,{coltitle => "NULL"} if ($emptycol);
445     
446     foreach my $row ( sort keys %table ) {
447         my @loopcell;
448     #@loopcol ensures the order for columns is common with column titles
449     # and the number matches the number of columns
450         my $colcount=0;
451         foreach my $col ( @loopcol ) {
452             my $value;
453             if ($table{$row}->{
454                     (        ( $col->{coltitle} eq 'NULL' )
455                           or ( $col->{coltitle} eq q{} )
456                       ) ? 'zzEMPTY' : $col->{coltitle}
457                 }
458               ) {
459                 $value = $table{$row}->{
460                     (        ( $col->{coltitle} eq 'NULL' )
461                           or ( $col->{coltitle} eq q{} )
462                       ) ? 'zzEMPTY' : $col->{coltitle}
463                   } / $wgttable{$row}->{
464                     (        ( $col->{coltitle} eq 'NULL' )
465                           or ( $col->{coltitle} eq q{} )
466                       ) ? 'zzEMPTY' : $col->{coltitle}
467                   };
468             }
469             $table{$row}->{(($col->{coltitle} eq "NULL")or ($col->{coltitle} eq ""))?"zzEMPTY":$col->{coltitle}} = $value;
470             $table{$row}->{totalrow}+=$value;
471             #warn "row : $row col:$col  $cnttable{$row}->{(($col->{coltitle} eq \"NULL\")or ($col->{coltitle} eq \"\"))?\"zzEMPTY\":$col->{coltitle}}";
472             $colcount+=$cnttable{$row}->{(($col->{coltitle} eq "NULL")or ($col->{coltitle} eq ""))?"zzEMPTY":$col->{coltitle}};
473             push @loopcell, {value => ($value)?sprintf("%.2f",$value):0  } ;
474         }
475         #warn "row : $row colcount:$colcount";
476         my $total;
477         if ( $colcount > 0 ) {
478             $total = $table{$row}->{totalrow} / $colcount;
479         }
480         push @looprow,
481           { 'rowtitle' => ( $row eq "zzEMPTY" ) ? "NULL" : $row,
482             'loopcell' => \@loopcell,
483             'hilighted' => ( $hilighted > 0 ),
484             'totalrow'  => ($total) ? sprintf( "%.2f", $total ) : 0
485           };
486         $hilighted = -$hilighted;
487     }
488 #       
489 # #     warn "footer processing";
490     foreach my $col ( @loopcol ) {
491         my $total=0;
492         my $nbrow=0;
493         foreach my $row ( @looprow ) {
494             $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}};
495             $nbrow +=$cnttable{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};;
496 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
497         }
498 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
499         $total = $total/$nbrow if ($nbrow);
500         push @loopfooter, {'totalcol' => ($total)?sprintf("%.2f",$total):0};
501     
502     }
503             
504
505     # the header of the table
506     $globalline{loopfilter}=\@loopfilter;
507     # the core of the table
508     $globalline{looprow} = \@looprow;
509     $globalline{loopcol} = \@loopcol;
510 #       # the foot (totals by borrower type)
511     $globalline{loopfooter} = \@loopfooter;
512     $globalline{total}= $grantotal;
513     $globalline{line} = $line;
514     $globalline{column} = $column;
515     push @mainloop,\%globalline;
516     return \@mainloop;
517
518 }
519
520 1;