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