fix for bug 2543: report output by tabulation a bit too literal
[koha.git] / reports / catalogue_stats.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 with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA  02111-1307 USA
20
21 use strict;
22 use C4::Auth;
23 use CGI;
24 use C4::Context;
25 use C4::Branch; # GetBranches
26 use C4::Output;
27 use C4::Koha;
28 use C4::Reports;
29 use C4::Circulation;
30
31 =head1 NAME
32
33 plugin that shows a stats on borrowers
34
35 =head1 DESCRIPTION
36
37 =over 2
38
39 =cut
40
41 our $debug = 0;
42 my $input = new CGI;
43 my $fullreportname = "reports/catalogue_stats.tmpl";
44 my $do_it       = $input->param('do_it');
45 my $line        = $input->param("Line");
46 my $column      = $input->param("Column");
47 my @filters     = $input->param("Filter");
48 my $deweydigits = $input->param("deweydigits");
49 my $lccndigits  = $input->param("lccndigits");
50 my $cotedigits  = $input->param("cotedigits");
51 my $output      = $input->param("output");
52 my $basename    = $input->param("basename");
53 my $mime        = $input->param("MIME");
54 our $sep     = $input->param("sep");
55 $sep = "\t" if ($sep eq 'tabulation');
56
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 => 1},
63                                 debug => 1,
64                                 });
65 $template->param(do_it => $do_it);
66 if ($do_it) {
67         my $results = calculate($line, $column, $deweydigits, $lccndigits, $cotedigits, \@filters);
68         if ($output eq "screen"){
69                 $template->param(mainloop => $results);
70                 output_html_with_http_headers $input, $cookie, $template->output;
71                 exit(1);
72         } else {
73                 print $input->header(-type => 'application/vnd.sun.xml.calc',
74                                      -encoding    => 'utf-8',
75                                                          -attachment=>"$basename.csv",
76                                                          -name=>"$basename.csv" );
77                 my $cols  = @$results[0]->{loopcol};
78                 my $lines = @$results[0]->{looprow};
79                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
80                 foreach my $col ( @$cols ) {
81                         print $col->{coltitle}.$sep;
82                 }
83                 print "Total\n";
84                 foreach my $line ( @$lines ) {
85                         my $x = $line->{loopcell};
86                         print $line->{rowtitle}.$sep;
87                         foreach my $cell (@$x) {
88                                 print $cell->{value}.$sep;
89                         }
90                         print $line->{totalrow};
91                         print "\n";
92                 }
93                 print "TOTAL";
94                 $cols = @$results[0]->{loopfooter};
95                 foreach my $col ( @$cols ) {
96                         print $sep.$col->{totalcol};
97                 }
98                 print $sep.@$results[0]->{total};
99                 exit(1);
100         }
101 } else {
102         my $dbh = C4::Context->dbh;
103         my @values;
104         my %labels;
105         my $count=0;
106         my $req;
107         my @select;
108         # FIXME: no such field "dewey"
109         # $req = $dbh->prepare("select count(dewey) from biblioitems ");
110         # $req->execute;
111         my $hasdewey = 0;
112
113 # (rch) biblioitems.lccn is mapped to lccn MARC21 010$a in default framework.
114 # This is not the LC Classification.  It's the Control Number.
115 # So I'm just going to remove this bit.  Call Number is handled in itemcallnumber.
116 #
117         my $haslccn = 0;
118 #       $req = $dbh->prepare( "select count(lccn) from biblioitems ");
119 #       $req->execute;
120 #       my $hlghtlccn;
121 #       while (my ($value) =$req->fetchrow) {
122 #               $hlghtlccn = !($hasdewey);
123 #               $haslccn =1 if (($value>2) and (! $haslccn));
124 #               $count++ if (($value) and (! $haslccn));
125 #               push @select, $value;
126 #       }
127 #       my $CGIlccn=CGI::scrolling_list( -name     => 'Filter',
128 #                               -id => 'Filter',
129 #                               -values   => \@select,
130 #                               -size     => 1,
131 #                               -multiple => 0 );
132
133 # No need to test for data here.  If you don't have itemcallnumbers, you probably know it.
134 # FIXME: Hardcoding to 5 chars on itemcallnum. 
135 #
136          my $hascote = 1;
137          my $highcote = 5;
138         
139         $req = $dbh->prepare("select itemtype, description from itemtypes order by description");
140         $req->execute;
141         my $CGIitemtype = $req->fetchall_arrayref({});
142
143         my $authvals = GetKohaAuthorisedValues("items.ccode");
144         my @authvals;
145         foreach (keys %$authvals) {
146                 push @authvals, { code => $_, description => $authvals->{$_} };
147         }
148         
149
150         my $branches=GetBranches();
151         my @branchloop;
152         foreach (keys %$branches) {
153                 my $thisbranch = ''; # FIXME: populate $thisbranch to preselect one
154                 my %row = (branchcode => $_,
155                         selected => ($thisbranch eq $_ ? 1 : 0),
156                         branchname => $branches->{$_}->{'branchname'},
157                 );
158                 push @branchloop, \%row;
159         }
160
161         my $locations = GetKohaAuthorisedValues("items.location");
162         my @locations;
163         foreach (sort keys %$locations) {
164                 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
165         }
166         
167         my @mime  = ( map { +{type =>$_} } (split /[;:]/,C4::Context->preference("MIME")) );
168         
169         $template->param(hasdewey=>$hasdewey,
170                                         haslccn   => $haslccn,
171                                         hascote   => $hascote,
172                                         CGIItemType => $CGIitemtype,
173                                         CGIBranch    => \@branchloop,
174                                         locationloop => \@locations,
175                                         authvals     => \@authvals,
176                                         CGIextChoice => \@mime,
177                                         CGIsepChoice => GetDelimiterChoices,
178                                         );
179
180 }
181 output_html_with_http_headers $input, $cookie, $template->output;
182
183 ## End of Main Body
184
185
186 sub calculate {
187         my ($line, $column, $deweydigits, $lccndigits, $cotedigits, $filters) = @_;
188         my @mainloop;
189         my @loopfooter;
190         my @loopcol;
191         my @loopline;
192         my @looprow;
193         my %globalline;
194         my $grantotal =0;
195 # extract parameters
196         my $dbh = C4::Context->dbh;
197
198 # Filters
199 # Checking filters
200 #
201         my @loopfilter;
202         for (my $i=0;$i<=12;$i++) {
203                 my %cell;
204                 if ( @$filters[$i] ) {
205                         if ((($i==1) or ($i==3) or ($i==5) or ($i==9)) and (@$filters[$i-1])) {
206                                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
207                         }
208                         $cell{filter} .= @$filters[$i];
209                         $cell{crit} .=
210                                 ($i== 0) ? "Dewey Classification From" :
211                                 ($i== 1) ? "Dewey Classification To"   :
212                                 ($i== 2) ? "Lccn Classification From"  :
213                                 ($i== 3) ? "Lccn Classification To"    :
214                                 ($i== 4) ? "Item CallNumber From"  :
215                                 ($i== 5) ? "Item CallNumber To"    :
216                                 ($i== 6) ? "Item type"             :
217                                 ($i== 7) ? "Publisher"                 :
218                                 ($i== 8) ? "Publication year From"     :
219                                 ($i== 9) ? "Publication year To"       :
220                                 ($i==10) ? "Library :"                  :
221                                 ($i==11) ? "Shelving Location :"                :
222                                 ($i==12) ? "Collection Code :"            : '';
223                         push @loopfilter, \%cell;
224                 }
225         }
226         
227 #       warn map {"filtres $_\n"} @filters[0..3];
228
229         my @linefilter;
230         $linefilter[0] = @$filters[0] if ($line =~ /dewey/ )  ;
231         $linefilter[1] = @$filters[1] if ($line =~ /dewey/ )  ;
232         $linefilter[0] = @$filters[2] if ($line =~ /lccn/ )  ;
233         $linefilter[1] = @$filters[3] if ($line =~ /lccn/ )  ;
234         $linefilter[0] = @$filters[4] if ($line =~ /items\.itemcallnumber/ )  ;
235         $linefilter[1] = @$filters[5] if ($line =~ /items\.itemcallnumber/ )  ;
236         $linefilter[0] = @$filters[6] if ($line =~ /itemtype/ )  ;
237         $linefilter[0] = @$filters[7] if ($line =~ /publishercode/ ) ;
238         $linefilter[0] = @$filters[8] if ($line =~ /publicationyear/ ) ;
239         $linefilter[1] = @$filters[9] if ($line =~ /publicationyear/ ) ;
240         $linefilter[0] = @$filters[10] if ($line =~ /items\.homebranch/ ) ;
241         $linefilter[0] = @$filters[11] if ($line =~ /items\.location/ ) ;
242         $linefilter[0] = @$filters[12] if ($line =~ /items\.ccode/ ) ;
243
244         my @colfilter ;
245         $colfilter[0] = @$filters[0] if ($column =~ /dewey/ )  ;
246         $colfilter[1] = @$filters[1] if ($column =~ /dewey/ )  ;
247         $colfilter[0] = @$filters[2] if ($column =~ /lccn/ )  ;
248         $colfilter[1] = @$filters[3] if ($column =~ /lccn/ )  ;
249         $colfilter[0] = @$filters[4] if ($column =~ /items\.itemcallnumber/ )  ;
250         $colfilter[1] = @$filters[5] if ($column =~ /items\.itemcallnumber/ )  ;
251         $colfilter[0] = @$filters[6] if ($column =~ /itemtype/ )  ;
252         $colfilter[0] = @$filters[7] if ($column =~ /publishercode/ ) ;
253         $colfilter[0] = @$filters[8] if ($column =~ /publicationyear/ ) ;
254         $colfilter[1] = @$filters[9] if ($column =~ /publicationyear/ ) ;
255         $colfilter[0] = @$filters[10] if ($column =~ /items\.homebranch/ ) ;
256         $colfilter[0] = @$filters[11] if ($column =~ /items\.location/ ) ;
257         $colfilter[0] = @$filters[12] if ($column =~ /items\.ccode/ ) ;
258
259 # 1st, loop rows.
260         my $linefield;
261         if (($line =~/dewey/)  and ($deweydigits)) {
262                 $linefield .="left($line,$deweydigits)";
263         } elsif (($line=~/lccn/) and ($lccndigits)) {
264                 $linefield .="left($line,$lccndigits)";
265         } elsif (($line=~/items.itemcallnumber/) and ($cotedigits)) {
266                 $linefield .="left($line,$cotedigits)";
267         }else {
268                 $linefield .= $line;
269         }
270
271         my $strsth;
272         $strsth .= "select distinctrow $linefield from biblioitems left join items on (items.biblioitemnumber = biblioitems.biblioitemnumber) where $line is not null ";
273         if ( @linefilter ) {
274                 if ($linefilter[1]){
275                         $strsth .= " and $line >= ? " ;
276                         $strsth .= " and $line <= ? " ;
277                 } elsif ($linefilter[0]) {
278                         $linefilter[0] =~ s/\*/%/g;
279                         $strsth .= " and $line LIKE ? " ;
280                 }
281         }
282         $strsth .=" order by $linefield";
283         $debug and print STDERR "catalogue_stats SQL: $strsth\n";
284         
285         my $sth = $dbh->prepare( $strsth );
286         if (( @linefilter ) and ($linefilter[1])){
287                 $sth->execute($linefilter[0],$linefilter[1]);
288         } elsif ($linefilter[0]) {
289                 $sth->execute($linefilter[0]);
290         } else {
291                 $sth->execute;
292         }
293         while ( my ($celvalue) = $sth->fetchrow) {
294                 my %cell;
295                 if ($celvalue) {
296                         $cell{rowtitle} = $celvalue;
297 #               } else {
298 #                       $cell{rowtitle} = "";
299                 }
300                 $cell{totalrow} = 0;
301                 push @loopline, \%cell;
302         }
303
304 # 2nd, loop cols.
305         my $colfield;
306         if (($column =~/dewey/)  and ($deweydigits)) {
307                 $colfield = "left($column,$deweydigits)";
308         }elsif (($column=~/lccn/) and ($lccndigits)) {
309                 $colfield = "left($column,$lccndigits)";
310         }elsif (($column=~/itemcallnumber/) and ($cotedigits)) {
311                 $colfield = "left($column,$cotedigits)";
312         }else {
313                 $colfield = $column;
314         }
315         
316         my $strsth2 = "
317         SELECT distinctrow $colfield
318         FROM   biblioitems
319         LEFT JOIN items
320                 ON (items.biblioitemnumber = biblioitems.biblioitemnumber)
321         WHERE  $column IS NOT NULL ";
322         if (( @colfilter ) and ($colfilter[1])) {
323                 $strsth2 .= " and $column> ? and $column< ?";
324         }elsif ($colfilter[0]){
325                 $colfilter[0] =~ s/\*/%/g;
326                 $strsth2 .= " and $column LIKE ? ";
327         } 
328         $strsth2 .= " order by $colfield";
329         $debug and print STDERR "SQL: $strsth2";
330         my $sth2 = $dbh->prepare( $strsth2 );
331         if ((@colfilter) and ($colfilter[1])) {
332                 $sth2->execute($colfilter[0],$colfilter[1]);
333         } elsif ($colfilter[0]){
334                 $sth2->execute($colfilter[0]);
335         } else {
336                 $sth2->execute;
337         }
338         while (my ($celvalue) = $sth2->fetchrow) {
339                 my %cell;
340                 my %ft;
341                 if ($celvalue) {
342                         $cell{coltitle} = $celvalue;
343 #               } else {
344 #                       $cell{coltitle} = "";
345                 }
346                 $ft{totalcol} = 0;
347                 push @loopcol, \%cell;
348         }
349         
350         my $i=0;
351         my @totalcol;
352         my $hilighted=-1;
353         
354         #Initialization of cell values.....
355         my %table;
356 #       warn "init table";
357         foreach my $row ( @loopline ) {
358                 foreach my $col ( @loopcol ) {
359 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
360                         $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
361                 }
362                 $table{$row->{rowtitle}}->{totalrow}=0;
363         }
364
365 # preparing calculation
366         my $strcalc .= "SELECT $linefield, $colfield, count(*) FROM biblioitems LEFT JOIN  items ON (items.biblioitemnumber = biblioitems.biblioitemnumber) WHERE 1";
367         if (@$filters[0]){
368                 @$filters[0]=~ s/\*/%/g;
369                 $strcalc .= " AND dewey >" . @$filters[0];
370         }
371         if (@$filters[1]){
372                 @$filters[1]=~ s/\*/%/g ;
373                 $strcalc .= " AND dewey <" . @$filters[1];
374         }
375         if (@$filters[2]){
376                 @$filters[2]=~ s/\*/%/g ;
377                 $strcalc .= " AND lccn >" . @$filters[2];
378         }
379         if (@$filters[3]){
380                 @$filters[3]=~ s/\*/%/g;
381                 $strcalc .= " AND lccn <" . @$filters[3];
382         }
383         if (@$filters[4]){
384                 @$filters[4]=~ s/\*/%/g ;
385                 $strcalc .= " AND items.itemcallnumber >=" . $dbh->quote(@$filters[4]);
386         }
387         
388         if (@$filters[5]){
389                 @$filters[5]=~ s/\*/%/g;
390                 $strcalc .= " AND items.itemcallnumber <=" . $dbh->quote(@$filters[5]);
391         }
392         
393         if (@$filters[6]){
394                 @$filters[6]=~ s/\*/%/g;
395                 $strcalc .= " AND " . 
396                         (C4::Context::preference('Item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype')
397                         . " LIKE '" . @$filters[6] ."'";
398         }
399         
400         if (@$filters[7]){
401                 @$filters[7]=~ s/\*/%/g;
402                 @$filters[7].="%" unless @$filters[7]=~/%/;
403                 $strcalc .= " AND biblioitems.publishercode LIKE \"" . @$filters[7] ."\"";
404         }
405         if (@$filters[8]){
406                 @$filters[8]=~ s/\*/%/g;
407                 $strcalc .= " AND publicationyear >" . @$filters[8];
408         }
409         if (@$filters[9]){
410                 @$filters[9]=~ s/\*/%/g;
411                 $strcalc .= " AND publicationyear <" . @$filters[9];
412         }
413         if (@$filters[10]){
414                 @$filters[10]=~ s/\*/%/g;
415                 $strcalc .= " AND items.homebranch LIKE '" . @$filters[10] ."'";
416         }
417         if (@$filters[11]){
418                 @$filters[11]=~ s/\*/%/g;
419                 $strcalc .= " AND items.location LIKE '" . @$filters[11] ."'";
420         }
421         if (@$filters[12]){
422                 @$filters[12]=~ s/\*/%/g;
423                 $strcalc .= " AND items.ccode  LIKE '" . @$filters[12] ."'";
424         }
425         
426         $strcalc .= " group by $linefield, $colfield order by $linefield,$colfield";
427         $debug and warn "SQL: $strcalc";
428         my $dbcalc = $dbh->prepare($strcalc);
429         $dbcalc->execute;
430 #       warn "filling table";
431         
432         my $emptycol; 
433         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
434 #               warn "filling table $row / $col / $value ";
435                 $emptycol = 1    if (!defined($col));
436                 $col = "zzEMPTY" if (!defined($col));
437                 $row = "zzEMPTY" if (!defined($row));
438                 
439                 $table{$row}->{$col}+=$value;
440                 $table{$row}->{totalrow}+=$value;
441                 $grantotal += $value;
442         }
443
444 #       my %cell = {rowtitle => 'zzROWEMPTY'};
445 #       push @loopline,\%cell;
446 #       undef %cell;
447 #       my %cell;
448 #       %cell = {coltitle => "zzEMPTY"};
449         push @loopcol,{coltitle => "NULL"} if ($emptycol);
450         
451         foreach my $row ( sort keys %table ) {
452                 my @loopcell;
453                 #@loopcol ensures the order for columns is common with column titles
454                 # and the number matches the number of columns
455                 foreach my $col ( @loopcol ) {
456                         my $value =$table{$row}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
457                         push @loopcell, {value => $value  } ;
458                 }
459                 push @looprow,{ 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
460                                                 'loopcell' => \@loopcell,
461                                                 'hilighted' => ($hilighted *= -1 > 0),
462                                                 'totalrow' => $table{$row}->{totalrow}
463                                         };
464         }
465         
466 #       warn "footer processing";
467         foreach my $col ( @loopcol ) {
468                 my $total=0;
469                 foreach my $row ( @looprow ) {
470                         $total += $table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
471 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
472                 }
473 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
474                 push @loopfooter, {'totalcol' => $total};
475         }
476                         
477
478         # the header of the table
479         $globalline{loopfilter}=\@loopfilter;
480         # the core of the table
481         $globalline{looprow} = \@looprow;
482         $globalline{loopcol} = \@loopcol;
483 #       # the foot (totals by borrower type)
484         $globalline{loopfooter} = \@loopfooter;
485         $globalline{total}= $grantotal;
486         $globalline{line} = $line;
487         $globalline{column} = $column;
488         push @mainloop,\%globalline;
489         return \@mainloop;
490 }
491
492 1;