Merge branch 'bug_9105' into 3.12-master
[koha.git] / reports / cat_issues_top.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 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.
12 #
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.
16 #
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.
20
21 use strict;
22 #use warnings; FIXME - Bug 2505
23 use C4::Auth;
24 use CGI;
25 use C4::Context;
26 use C4::Branch; # GetBranches
27 use C4::Output;
28 use C4::Koha;
29 use C4::Circulation;
30 use C4::Reports;
31 use C4::Dates qw/format_date format_date_in_iso/;
32 use C4::Members;
33
34 =head1 NAME
35
36 plugin that shows a stats on borrowers
37
38 =head1 DESCRIPTION
39
40 =over 2
41
42 =cut
43
44 my $input = new CGI;
45 my $do_it=$input->param('do_it');
46 my $fullreportname = "reports/cat_issues_top.tmpl";
47 my $limit = $input->param("Limit");
48 my $column = $input->param("Criteria");
49 my @filters = $input->param("Filter");
50 $filters[0]=format_date_in_iso($filters[0]);
51 $filters[1]=format_date_in_iso($filters[1]);
52 $filters[2]=format_date_in_iso($filters[2]);
53 $filters[3]=format_date_in_iso($filters[3]);
54 my $output = $input->param("output");
55 my $basename = $input->param("basename");
56 #warn "calcul : ".$calc;
57 my ($template, $borrowernumber, $cookie)
58     = get_template_and_user({template_name => $fullreportname,
59                 query => $input,
60                 type => "intranet",
61                 authnotrequired => 0,
62                 flagsrequired => { reports => '*'},
63                 debug => 1,
64                 });
65 our $sep     = $input->param("sep");
66 $sep = "\t" if ($sep eq 'tabulation');
67 $template->param(do_it => $do_it,
68         );
69 if ($do_it) {
70 # Displaying results
71     my $results = calculate($limit, $column, \@filters);
72     if ($output eq "screen"){
73 # Printing results to screen
74         $template->param(mainloop => $results,
75                         limit => $limit);
76         output_html_with_http_headers $input, $cookie, $template->output;
77         exit;
78     } else {
79 # Printing to a csv file
80         print $input->header(-type => 'application/vnd.sun.xml.calc',
81                             -encoding    => 'utf-8',
82                             -attachment=>"$basename.csv",
83                             -filename=>"$basename.csv" );
84         my $cols = @$results[0]->{loopcol};
85         my $lines = @$results[0]->{looprow};
86 # header top-right
87         print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
88 # Other header
89         foreach my $col ( @$cols ) {
90             print $col->{coltitle}.$sep;
91         }
92         print "Total\n";
93 # Table
94         foreach my $line ( @$lines ) {
95             my $x = $line->{loopcell};
96             print $line->{rowtitle}.$sep;
97             foreach my $cell (@$x) {
98                 print $cell->{value}.$sep;
99             }
100             print $line->{totalrow};
101             print "\n";
102         }
103 # footer
104         print "TOTAL";
105         $cols = @$results[0]->{loopfooter};
106         foreach my $col ( @$cols ) {
107             print $sep.$col->{totalcol};
108         }
109         print $sep.@$results[0]->{total};
110         exit;
111     }
112 # Displaying choices
113 } else {
114     my $dbh = C4::Context->dbh;
115     my @values;
116     my %labels;
117     my %select;
118     my $req;
119     
120     my $CGIextChoice=CGI::scrolling_list(
121                 -name     => 'MIME',
122                 -id       => 'MIME',
123                 -values   => ['CSV'], # FIXME translation
124                 -size     => 1,
125                 -multiple => 0 );
126     
127     my $CGIsepChoice=GetDelimiterChoices;
128
129     #doctype
130     my $itemtypes = GetItemTypes;
131     my @itemtypeloop;
132     foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'}} keys %$itemtypes) {
133             my %row =(value => $thisitemtype,
134                       description => $itemtypes->{$thisitemtype}->{'description'},
135                             );
136             push @itemtypeloop, \%row;
137     }
138     
139     #borcat
140     my ($codes,$labels) = GetborCatFromCatType(undef,undef);
141     my @borcatloop;
142     foreach my $thisborcat (sort {$labels->{$a} cmp $labels->{$b}} keys %$labels) {
143             my %row =(value => $thisborcat,
144                       description => $labels->{$thisborcat},
145                             );
146             push @borcatloop, \%row;
147     }
148     
149     #Day
150     #Month
151     $template->param(
152                     CGIextChoice => $CGIextChoice,
153                     CGIsepChoice => $CGIsepChoice,
154                     branchloop => GetBranchesLoop(C4::Context->userenv->{'branch'}),
155                     itemtypeloop =>\@itemtypeloop,
156                     borcatloop =>\@borcatloop,
157                     );
158 output_html_with_http_headers $input, $cookie, $template->output;
159 }
160
161
162
163
164 sub calculate {
165     my ($line, $column, $filters) = @_;
166     my @mainloop;
167     my @loopfooter;
168     my @loopcol;
169     my @loopline;
170     my @looprow;
171     my %globalline;
172     my $grantotal =0;
173 # extract parameters
174     my $dbh = C4::Context->dbh;
175
176 # Filters
177 # Checking filters
178 #
179     my @loopfilter;
180     for (my $i=0;$i<=6;$i++) {
181         my %cell;
182         if ( @$filters[$i] ) {
183             if (($i==1) and (@$filters[$i-1])) {
184                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
185             }
186             # format the dates filters, otherwise just fill as is
187             if ($i>=2) {
188                 $cell{filter} .= @$filters[$i];
189             } else {
190                 $cell{filter} .= format_date(@$filters[$i]);
191             }            $cell{crit} .="Issue From" if ($i==0);
192             $cell{crit} .="Issue To" if ($i==1);
193             $cell{crit} .="Return From" if ($i==2);
194             $cell{crit} .="Return To" if ($i==3);
195             $cell{crit} .="Branch" if ($i==4);
196             $cell{crit} .="Doc Type" if ($i==5);
197             $cell{crit} .="Bor Cat" if ($i==6);
198             $cell{crit} .="Day" if ($i==7);
199             $cell{crit} .="Month" if ($i==8);
200             $cell{crit} .="Year" if ($i==9);
201             push @loopfilter, \%cell;
202         }
203     }
204     my $colfield;
205     my $colorder;
206     if ($column){
207         $column = "old_issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/));
208         if($column=~/itemtype/){
209             $column = C4::Context->preference('item-level_itypes') ? "items.itype": "biblioitems.itemtype";
210         }
211         $column = "borrowers.".$column if $column=~/categorycode/;
212         my @colfilter ;
213         $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ )  ;
214         $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ )  ;
215         $colfilter[0] = @$filters[2] if ($column =~ /returndate/ )  ;
216         $colfilter[1] = @$filters[3] if ($column =~ /returndate/ )  ;
217         $colfilter[0] = @$filters[4] if ($column =~ /branch/ )  ;
218         $colfilter[0] = @$filters[5] if ($column =~ /itemtype/ )  ;
219         $colfilter[0] = @$filters[6] if ($column =~ /category/ )  ;
220     #   $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
221         $colfilter[0] = @$filters[7] if ($column =~ /timestamp/ ) ;
222         $colfilter[0] = @$filters[8] if ($column =~ /timestamp/ ) ;
223         $colfilter[0] = @$filters[9] if ($column =~ /timestamp/ ) ;
224     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
225                                                 
226     # loop cols.
227         if ($column eq "Day") {
228             #Display by day
229             $column = "old_issues.timestamp";
230             $colfield .="dayname($column)";  
231             $colorder .="weekday($column)";
232         } elsif ($column eq "Month") {
233             #Display by Month
234             $column = "old_issues.timestamp";
235             $colfield .="monthname($column)";  
236             $colorder .="month($column)";  
237         } elsif ($column eq "Year") {
238             #Display by Year
239             $column = "old_issues.timestamp";
240             $colfield .="Year($column)";
241             $colorder .= $column;
242         } else {
243             $colfield .= $column;
244             $colorder .= $column;
245         }  
246         
247         my $strsth2;
248         $strsth2 .= "SELECT distinctrow $colfield 
249                      FROM `old_issues` 
250                      LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber 
251                      LEFT JOIN items ON old_issues.itemnumber=items.itemnumber 
252                      LEFT JOIN biblioitems  ON biblioitems.biblioitemnumber=items.biblioitemnumber 
253                      WHERE 1";
254         if (($column=~/timestamp/) or ($column=~/returndate/)){
255             if ($colfilter[1] and ($colfilter[0])){
256                 $strsth2 .= " and $column between '$colfilter[0]' and '$colfilter[1]' " ;
257             } elsif ($colfilter[1]) {
258                     $strsth2 .= " and $column < '$colfilter[1]' " ;
259             } elsif ($colfilter[0]) {
260                 $strsth2 .= " and $column > '$colfilter[0]' " ;
261             }
262         } elsif ($colfilter[0]) {
263             $colfilter[0] =~ s/\*/%/g;
264             $strsth2 .= " and $column LIKE '$colfilter[0]' " ;
265         }
266         $strsth2 .=" group by $colfield";
267         $strsth2 .=" order by $colorder";
268         
269         my $sth2 = $dbh->prepare( $strsth2 );
270         if (( @colfilter ) and ($colfilter[1])){
271             $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'");
272         } elsif ($colfilter[0]) {
273             $sth2->execute($colfilter[0]);
274         } else {
275             $sth2->execute;
276         }
277         
278     
279         while (my ($celvalue) = $sth2->fetchrow) {
280             my %cell;
281             $cell{coltitle} = ($celvalue?$celvalue:"NULL");
282             push @loopcol, \%cell;
283         }
284     #   warn "fin des titres colonnes";
285     }
286     
287     my $i=0;
288 #       my @totalcol;
289     my $hilighted=-1;
290     
291     #Initialization of cell values.....
292     my @table;
293     
294 #       warn "init table";
295     for (my $i=1;$i<=$line;$i++) {
296         foreach my $col ( @loopcol ) {
297 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
298             $table[$i]->{($col->{coltitle})?$col->{coltitle}:"total"}->{'name'}=0;
299         }
300     }
301
302
303 # preparing calculation
304     my $strcalc ;
305     
306 # Processing average loanperiods
307     $strcalc .= "SELECT DISTINCT biblio.title, COUNT(biblio.biblionumber) AS RANK, biblio.biblionumber AS ID";
308     $strcalc .= " , $colfield " if ($colfield);
309     $strcalc .= " FROM `old_issues` 
310                   LEFT JOIN items USING(itemnumber) 
311                   LEFT JOIN biblio USING(biblionumber) 
312                   LEFT JOIN biblioitems USING(biblionumber)
313                   LEFT JOIN borrowers USING(borrowernumber)
314                   WHERE 1";
315
316     @$filters[0]=~ s/\*/%/g if (@$filters[0]);
317     $strcalc .= " AND old_issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
318     @$filters[1]=~ s/\*/%/g if (@$filters[1]);
319     $strcalc .= " AND old_issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] );
320     @$filters[2]=~ s/\*/%/g if (@$filters[2]);
321     $strcalc .= " AND old_issues.returndate > '" . @$filters[2] ."'" if ( @$filters[2] );
322     @$filters[3]=~ s/\*/%/g if (@$filters[3]);
323     $strcalc .= " AND old_issues.returndate < '" . @$filters[3] ."'" if ( @$filters[3] );
324     @$filters[4]=~ s/\*/%/g if (@$filters[4]);
325     $strcalc .= " AND old_issues.branchcode like '" . @$filters[4] ."'" if ( @$filters[4] );
326     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
327     if ( @$filters[5] ){
328         if(C4::Context->preference('item-level_itypes') ){
329             $strcalc .= " AND items.itype like "
330         }else{
331             $strcalc .= " AND biblioitems.itemtype like "
332         } 
333         $strcalc .= "'" . @$filters[5] ."'" ;
334     }
335     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
336     $strcalc .= " AND borrowers.categorycode like '" . @$filters[6] ."'" if ( @$filters[6] );
337     @$filters[7]=~ s/\*/%/g if (@$filters[7]);
338     $strcalc .= " AND dayname(old_issues.timestamp) like '" . @$filters[7]."'" if (@$filters[7]);
339     @$filters[8]=~ s/\*/%/g if (@$filters[8]);
340     $strcalc .= " AND monthname(old_issues.timestamp) like '" . @$filters[8]."'" if (@$filters[8]);
341     @$filters[9]=~ s/\*/%/g if (@$filters[9]);
342     $strcalc .= " AND year(old_issues.timestamp) like '" . @$filters[9] ."'" if ( @$filters[9] );
343     
344     $strcalc .= " group by biblio.biblionumber";
345     $strcalc .= ", $colfield" if ($column);
346     $strcalc .= " order by RANK DESC";
347     $strcalc .= ", $colfield " if ($colfield);
348     
349     my $dbcalc = $dbh->prepare($strcalc);
350     $dbcalc->execute;
351     my $previous_col;
352     my %indice;
353     while (my  @data = $dbcalc->fetchrow) {
354         my ($row, $rank, $id, $col )=@data;
355         $col = "zzEMPTY" if (!defined($col));
356         $indice{$col}=1 if (not($indice{$col}));
357         $table[$indice{$col}]->{$col}->{'name'}=$row;
358         $table[$indice{$col}]->{$col}->{'count'}=$rank;
359         $table[$indice{$col}]->{$col}->{'link'}=$id;
360         $indice{$col}++;
361     }
362     
363     push @loopcol,{coltitle => "Global"} if not($column);
364     
365     for ($i=1; $i<=$line;$i++) {
366         my @loopcell;
367         #@loopcol ensures the order for columns is common with column titles
368         # and the number matches the number of columns
369         my $colcount=0;
370         foreach my $col ( @loopcol ) {
371             my $value;
372             my $count=0;
373             my $link;
374             if (@loopcol){
375                 $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'name'};
376                 $count =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'count'};
377                 $link =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'link'};
378             } else {
379                 $value =$table[$i]->{"zzEMPTY"}->{'name'};
380                 $count =$table[$i]->{"zzEMPTY"}->{'count'};
381                 $link =$table[$i]->{"zzEMPTY"}->{'link'};
382             }
383             push @loopcell, {value => $value, count =>$count, reference => $link} ;
384         }
385         #my $total = $table[$i]->{totalrow}/$colcount if ($colcount>0);
386         push @looprow,{ 'rowtitle' => $i ,
387                         'loopcell' => \@loopcell,
388                         'hilighted' => ($hilighted >0),
389                     };
390         $hilighted = -$hilighted;
391     }
392 #       
393             
394
395     # the header of the table
396     $globalline{loopfilter}=\@loopfilter;
397     # the core of the table
398     $globalline{looprow} = \@looprow;
399     $globalline{loopcol} = \@loopcol;
400 #       # the foot (totals by borrower type)
401     $globalline{loopfooter} = \@loopfooter;
402     $globalline{total}= $grantotal;
403     $globalline{line} = $line;
404     $globalline{column} = $column;
405     push @mainloop,\%globalline;
406     return \@mainloop;
407 }
408
409 1;