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