(bug #2854) add the possibility to make a fuzzy search on the barcode
[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     my $barcodelike   = @$filters[13];
196     my $barcodefilter = @$filters[14];
197     my $not;
198     
199 # extract parameters
200         my $dbh = C4::Context->dbh;
201
202 # if barcodefilter is empty set as %
203 if($barcodefilter){
204     # Check if barcodefilter is "like" or "not like"
205     if(!$barcodelike){
206         $not = "not";
207     }
208     # Change * to %
209     $barcodefilter =~ s/\*/%/g;
210 }else{
211     $barcodefilter = "%";
212 }
213
214 # Filters
215 # Checking filters
216 #
217         my @loopfilter;
218         for (my $i=0;$i<=12;$i++) {
219                 my %cell;
220                 if ( @$filters[$i] ) {
221                         if ((($i==1) or ($i==3) or ($i==5) or ($i==9)) and (@$filters[$i-1])) {
222                                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
223                         }
224                         $cell{filter} .= @$filters[$i];
225                         $cell{crit} .=
226                                 ($i== 0) ? "Dewey Classification From" :
227                                 ($i== 1) ? "Dewey Classification To"   :
228                                 ($i== 2) ? "Lccn Classification From"  :
229                                 ($i== 3) ? "Lccn Classification To"    :
230                                 ($i== 4) ? "Item CallNumber From"  :
231                                 ($i== 5) ? "Item CallNumber To"    :
232                                 ($i== 6) ? "Item type"             :
233                                 ($i== 7) ? "Publisher"                 :
234                                 ($i== 8) ? "Publication year From"     :
235                                 ($i== 9) ? "Publication year To"       :
236                                 ($i==10) ? "Library :"                  :
237                                 ($i==11) ? "Shelving Location :"                :
238                                 ($i==12) ? "Collection Code :"            : '';
239                         push @loopfilter, \%cell;
240                 }
241         }
242         
243 #       warn map {"filtres $_\n"} @filters[0..3];
244
245         my @linefilter;
246         $linefilter[0] = @$filters[0] if ($line =~ /dewey/ )  ;
247         $linefilter[1] = @$filters[1] if ($line =~ /dewey/ )  ;
248         $linefilter[0] = @$filters[2] if ($line =~ /lccn/ )  ;
249         $linefilter[1] = @$filters[3] if ($line =~ /lccn/ )  ;
250         $linefilter[0] = @$filters[4] if ($line =~ /items\.itemcallnumber/ )  ;
251         $linefilter[1] = @$filters[5] if ($line =~ /items\.itemcallnumber/ )  ;
252         $linefilter[0] = @$filters[6] if ($line =~ /itemtype/ )  ;
253         $linefilter[0] = @$filters[7] if ($line =~ /publishercode/ ) ;
254         $linefilter[0] = @$filters[8] if ($line =~ /publicationyear/ ) ;
255         $linefilter[1] = @$filters[9] if ($line =~ /publicationyear/ ) ;
256         $linefilter[0] = @$filters[10] if ($line =~ /items\.homebranch/ ) ;
257         $linefilter[0] = @$filters[11] if ($line =~ /items\.location/ ) ;
258         $linefilter[0] = @$filters[12] if ($line =~ /items\.ccode/ ) ;
259
260         my @colfilter ;
261         $colfilter[0] = @$filters[0] if ($column =~ /dewey/ )  ;
262         $colfilter[1] = @$filters[1] if ($column =~ /dewey/ )  ;
263         $colfilter[0] = @$filters[2] if ($column =~ /lccn/ )  ;
264         $colfilter[1] = @$filters[3] if ($column =~ /lccn/ )  ;
265         $colfilter[0] = @$filters[4] if ($column =~ /items\.itemcallnumber/ )  ;
266         $colfilter[1] = @$filters[5] if ($column =~ /items\.itemcallnumber/ )  ;
267         $colfilter[0] = @$filters[6] if ($column =~ /itemtype/ )  ;
268         $colfilter[0] = @$filters[7] if ($column =~ /publishercode/ ) ;
269         $colfilter[0] = @$filters[8] if ($column =~ /publicationyear/ ) ;
270         $colfilter[1] = @$filters[9] if ($column =~ /publicationyear/ ) ;
271         $colfilter[0] = @$filters[10] if ($column =~ /items\.homebranch/ ) ;
272         $colfilter[0] = @$filters[11] if ($column =~ /items\.location/ ) ;
273         $colfilter[0] = @$filters[12] if ($column =~ /items\.ccode/ ) ;
274
275 # 1st, loop rows.
276         my $linefield;
277         if (($line =~/dewey/)  and ($deweydigits)) {
278                 $linefield .="left($line,$deweydigits)";
279         } elsif (($line=~/lccn/) and ($lccndigits)) {
280                 $linefield .="left($line,$lccndigits)";
281         } elsif (($line=~/items.itemcallnumber/) and ($cotedigits)) {
282                 $linefield .="left($line,$cotedigits)";
283         }else {
284                 $linefield .= $line;
285         }
286
287         my $strsth;
288         $strsth .= "select distinctrow $linefield from biblioitems left join items on (items.biblioitemnumber = biblioitems.biblioitemnumber) where barcode $not LIKE ? AND $line is not null ";
289         if ( @linefilter ) {
290                 if ($linefilter[1]){
291                         $strsth .= " and $line >= ? " ;
292                         $strsth .= " and $line <= ? " ;
293                 } elsif ($linefilter[0]) {
294                         $linefilter[0] =~ s/\*/%/g;
295                         $strsth .= " and $line LIKE ? " ;
296                 }
297         }
298         $strsth .=" order by $linefield";
299         $debug and print STDERR "catalogue_stats SQL: $strsth\n";
300         
301         my $sth = $dbh->prepare( $strsth );
302         if (( @linefilter ) and ($linefilter[1])){
303                 $sth->execute($barcodefilter,$linefilter[0],$linefilter[1]);
304         } elsif ($barcodefilter,$linefilter[0]) {
305                 $sth->execute($barcodefilter,$linefilter[0]);
306         } else {
307                 $sth->execute($barcodefilter);
308         }
309         while ( my ($celvalue) = $sth->fetchrow) {
310                 my %cell;
311                 if ($celvalue) {
312                         $cell{rowtitle} = $celvalue;
313 #               } else {
314 #                       $cell{rowtitle} = "";
315                 }
316                 $cell{totalrow} = 0;
317                 push @loopline, \%cell;
318         }
319
320 # 2nd, loop cols.
321         my $colfield;
322         if (($column =~/dewey/)  and ($deweydigits)) {
323                 $colfield = "left($column,$deweydigits)";
324         }elsif (($column=~/lccn/) and ($lccndigits)) {
325                 $colfield = "left($column,$lccndigits)";
326         }elsif (($column=~/itemcallnumber/) and ($cotedigits)) {
327                 $colfield = "left($column,$cotedigits)";
328         }else {
329                 $colfield = $column;
330         }
331         
332         my $strsth2 = "
333         SELECT distinctrow $colfield
334         FROM   biblioitems
335         LEFT JOIN items
336                 ON (items.biblioitemnumber = biblioitems.biblioitemnumber)
337         WHERE  barcode $not LIKE ? AND $column IS NOT NULL ";
338         if (( @colfilter ) and ($colfilter[1])) {
339                 $strsth2 .= " and $column> ? and $column< ?";
340         }elsif ($colfilter[0]){
341                 $colfilter[0] =~ s/\*/%/g;
342                 $strsth2 .= " and $column LIKE ? ";
343         } 
344         $strsth2 .= " order by $colfield";
345         $debug and print STDERR "SQL: $strsth2";
346         my $sth2 = $dbh->prepare( $strsth2 );
347         if ((@colfilter) and ($colfilter[1])) {
348                 $sth2->execute($barcodefilter,$colfilter[0],$colfilter[1]);
349         } elsif ($colfilter[0]){
350                 $sth2->execute($barcodefilter,$colfilter[0]);
351         } else {
352                 $sth2->execute($barcodefilter);
353         }
354         while (my ($celvalue) = $sth2->fetchrow) {
355                 my %cell;
356                 my %ft;
357                 if ($celvalue) {
358                         $cell{coltitle} = $celvalue;
359 #               } else {
360 #                       $cell{coltitle} = "";
361                 }
362                 $ft{totalcol} = 0;
363                 push @loopcol, \%cell;
364         }
365         
366         my $i=0;
367         my @totalcol;
368         my $hilighted=-1;
369         
370         #Initialization of cell values.....
371         my %table;
372 #       warn "init table";
373         foreach my $row ( @loopline ) {
374                 foreach my $col ( @loopcol ) {
375 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
376                         $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
377                 }
378                 $table{$row->{rowtitle}}->{totalrow}=0;
379         }
380
381 # preparing calculation
382         my $strcalc .= "SELECT $linefield, $colfield, count(*) FROM biblioitems LEFT JOIN  items ON (items.biblioitemnumber = biblioitems.biblioitemnumber) WHERE 1 AND barcode $not like ? ";
383         if (@$filters[0]){
384                 @$filters[0]=~ s/\*/%/g;
385                 $strcalc .= " AND dewey >" . @$filters[0];
386         }
387         if (@$filters[1]){
388                 @$filters[1]=~ s/\*/%/g ;
389                 $strcalc .= " AND dewey <" . @$filters[1];
390         }
391         if (@$filters[2]){
392                 @$filters[2]=~ s/\*/%/g ;
393                 $strcalc .= " AND lccn >" . @$filters[2];
394         }
395         if (@$filters[3]){
396                 @$filters[3]=~ s/\*/%/g;
397                 $strcalc .= " AND lccn <" . @$filters[3];
398         }
399         if (@$filters[4]){
400                 @$filters[4]=~ s/\*/%/g ;
401                 $strcalc .= " AND items.itemcallnumber >=" . $dbh->quote(@$filters[4]);
402         }
403         
404         if (@$filters[5]){
405                 @$filters[5]=~ s/\*/%/g;
406                 $strcalc .= " AND items.itemcallnumber <=" . $dbh->quote(@$filters[5]);
407         }
408         
409         if (@$filters[6]){
410                 @$filters[6]=~ s/\*/%/g;
411                 $strcalc .= " AND " . 
412                         (C4::Context::preference('Item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype')
413                         . " LIKE '" . @$filters[6] ."'";
414         }
415         
416         if (@$filters[7]){
417                 @$filters[7]=~ s/\*/%/g;
418                 @$filters[7].="%" unless @$filters[7]=~/%/;
419                 $strcalc .= " AND biblioitems.publishercode LIKE \"" . @$filters[7] ."\"";
420         }
421         if (@$filters[8]){
422                 @$filters[8]=~ s/\*/%/g;
423                 $strcalc .= " AND publicationyear >" . @$filters[8];
424         }
425         if (@$filters[9]){
426                 @$filters[9]=~ s/\*/%/g;
427                 $strcalc .= " AND publicationyear <" . @$filters[9];
428         }
429         if (@$filters[10]){
430                 @$filters[10]=~ s/\*/%/g;
431                 $strcalc .= " AND items.homebranch LIKE '" . @$filters[10] ."'";
432         }
433         if (@$filters[11]){
434                 @$filters[11]=~ s/\*/%/g;
435                 $strcalc .= " AND items.location LIKE '" . @$filters[11] ."'";
436         }
437         if (@$filters[12]){
438                 @$filters[12]=~ s/\*/%/g;
439                 $strcalc .= " AND items.ccode  LIKE '" . @$filters[12] ."'";
440         }
441         
442         $strcalc .= " group by $linefield, $colfield order by $linefield,$colfield";
443         $debug and warn "SQL: $strcalc";
444         my $dbcalc = $dbh->prepare($strcalc);
445         $dbcalc->execute($barcodefilter);
446 #       warn "filling table";
447         
448         my $emptycol; 
449         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
450 #               warn "filling table $row / $col / $value ";
451                 $emptycol = 1    if (!defined($col));
452                 $col = "zzEMPTY" if (!defined($col));
453                 $row = "zzEMPTY" if (!defined($row));
454                 
455                 $table{$row}->{$col}+=$value;
456                 $table{$row}->{totalrow}+=$value;
457                 $grantotal += $value;
458         }
459
460 #       my %cell = {rowtitle => 'zzROWEMPTY'};
461 #       push @loopline,\%cell;
462 #       undef %cell;
463 #       my %cell;
464 #       %cell = {coltitle => "zzEMPTY"};
465         push @loopcol,{coltitle => "NULL"} if ($emptycol);
466         
467         foreach my $row ( sort keys %table ) {
468                 my @loopcell;
469                 #@loopcol ensures the order for columns is common with column titles
470                 # and the number matches the number of columns
471                 foreach my $col ( @loopcol ) {
472                         my $value =$table{$row}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
473                         push @loopcell, {value => $value  } ;
474                 }
475                 push @looprow,{ 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
476                                                 'loopcell' => \@loopcell,
477                                                 'hilighted' => ($hilighted *= -1 > 0),
478                                                 'totalrow' => $table{$row}->{totalrow}
479                                         };
480         }
481         
482 #       warn "footer processing";
483         foreach my $col ( @loopcol ) {
484                 my $total=0;
485                 foreach my $row ( @looprow ) {
486                         $total += $table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
487 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
488                 }
489 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
490                 push @loopfooter, {'totalcol' => $total};
491         }
492                         
493
494         # the header of the table
495         $globalline{loopfilter}=\@loopfilter;
496         # the core of the table
497         $globalline{looprow} = \@looprow;
498         $globalline{loopcol} = \@loopcol;
499 #       # the foot (totals by borrower type)
500         $globalline{loopfooter} = \@loopfooter;
501         $globalline{total}= $grantotal;
502         $globalline{line} = $line;
503         $globalline{column} = $column;
504         push @mainloop,\%globalline;
505         return \@mainloop;
506 }
507
508 1;