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