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