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