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