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