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