Merge commit 'koha-biblibre/master' into bl-acq
[koha.git] / reports / issues_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
23 use CGI;
24 use Date::Manip;
25
26 use C4::Auth;
27 use C4::Debug;
28 use C4::Context;
29 use C4::Branch; # GetBranches
30 use C4::Koha;
31 use C4::Output;
32 use C4::Circulation;
33 use C4::Reports;
34 use C4::Dates qw/format_date format_date_in_iso/;
35 use C4::Members;
36
37 =head1 NAME
38
39 plugin that shows circulation stats
40
41 =head1 DESCRIPTION
42
43 =over 2
44
45 =cut
46
47 # my $debug = 1;        # override for now.
48 my $input = new CGI;
49 my $fullreportname = "reports/issues_stats.tmpl";
50 my $do_it    = $input->param('do_it');
51 my $line     = $input->param("Line");
52 my $column   = $input->param("Column");
53 my @filters  = $input->param("Filter");
54 $filters[0]=format_date_in_iso($filters[0]);
55 $filters[1]=format_date_in_iso($filters[1]);
56 my $podsp    = $input->param("DisplayBy");
57 my $type     = $input->param("PeriodTypeSel");
58 my $daysel   = $input->param("PeriodDaySel");
59 my $monthsel = $input->param("PeriodMonthSel");
60 my $calc     = $input->param("Cellvalue");
61 my $output   = $input->param("output");
62 my $basename = $input->param("basename");
63 my $mime     = $input->param("MIME");
64 my ($template, $borrowernumber, $cookie) = get_template_and_user({
65         template_name => $fullreportname,
66         query => $input,
67         type => "intranet",
68         authnotrequired => 0,
69         flagsrequired => {reports => '*'},
70         debug => 0,
71 });
72 our $sep     = $input->param("sep");
73 $sep = "\t" if ($sep eq 'tabulation');
74 $template->param(do_it => $do_it,
75         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
76 );
77
78 my $itemtypes = GetItemTypes();
79 my $categoryloop = GetBorrowercategoryList;
80
81 my $ccodes    = GetKohaAuthorisedValues("items.ccode");
82 my $locations = GetKohaAuthorisedValues("items.location");
83
84 my $Bsort1 = GetAuthorisedValues("Bsort1");
85 my $Bsort2 = GetAuthorisedValues("Bsort2");
86 my ($hassort1,$hassort2);
87 $hassort1=1 if $Bsort1;
88 $hassort2=1 if $Bsort2;
89
90
91 if ($do_it) {
92 # Displaying results
93         my $results = calculate($line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters);
94         if ($output eq "screen"){
95 # Printing results to screen
96                 $template->param(mainloop => $results);
97                 output_html_with_http_headers $input, $cookie, $template->output;
98         } else {
99 # Printing to a csv file
100         print $input->header(-type => 'application/vnd.sun.xml.calc',
101                             -encoding    => 'utf-8',
102                             -attachment=>"$basename.csv",
103                             -filename=>"$basename.csv" );
104                 my $cols  = @$results[0]->{loopcol};
105                 my $lines = @$results[0]->{looprow};
106 # header top-right
107                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
108 # Other header
109                 foreach my $col ( @$cols ) {
110                         print $col->{coltitle}.$sep;
111                 }
112                 print "Total\n";
113 # Table
114                 foreach my $line ( @$lines ) {
115                         my $x = $line->{loopcell};
116                         print $line->{rowtitle}.$sep;
117                         print map {$_->{value}.$sep} @$x;
118                         print $line->{totalrow}, "\n";
119                 }
120 # footer
121         print "TOTAL";
122         $cols = @$results[0]->{loopfooter};
123                 print map {$sep.$_->{totalcol}} @$cols;
124         print $sep.@$results[0]->{total};
125         }
126         exit(1); # exit either way after $do_it
127 }
128
129 my $dbh = C4::Context->dbh;
130 my @values;
131 my %labels;
132 my %select;
133
134 # create itemtype arrayref for <select>.
135 my @itemtypeloop;
136 for my $itype ( sort {$itemtypes->{$a}->{description} cmp $itemtypes->{$b}->{description}} keys(%$itemtypes)) {
137         push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{description} } ;
138 }
139
140     # location list
141 my @locations;
142 foreach (sort keys %$locations) {
143         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
144 }
145     
146 my @ccodes;
147 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
148         push @ccodes, { code => $_, description => $ccodes->{$_} };
149 }
150
151 # various
152 my @mime = (C4::Context->preference("MIME"));
153
154 my $CGIextChoice=CGI::scrolling_list(
155         -name     => 'MIME',
156         -id       => 'MIME',
157         -values   => \@mime,
158         -size     => 1,
159         -multiple => 0 );
160     
161 my $CGIsepChoice=GetDelimiterChoices;
162  
163 $template->param(
164         categoryloop => $categoryloop,
165         itemtypeloop => \@itemtypeloop,
166         locationloop => \@locations,
167            ccodeloop => \@ccodes,
168           branchloop => GetBranchesLoop(C4::Context->userenv->{'branch'}),
169         hassort1=> $hassort1,
170         hassort2=> $hassort2,
171         Bsort1 => $Bsort1,
172         Bsort2 => $Bsort2,
173         CGIextChoice => $CGIextChoice,
174         CGIsepChoice => $CGIsepChoice,
175 );
176 output_html_with_http_headers $input, $cookie, $template->output;
177
178 sub calculate {
179         my ($line, $column, $dsp, $type,$daysel,$monthsel ,$process, $filters) = @_;
180         my @loopfooter;
181         my @loopcol;
182         my @loopline;
183         my @looprow;
184         my %globalline;
185         my $grantotal =0;
186 # extract parameters
187         my $dbh = C4::Context->dbh;
188
189 # Filters
190 # Checking filters
191 #
192         my @loopfilter;
193         for (my $i=0;$i<=10;$i++) {
194                 my %cell;
195                 (@$filters[$i]) or next;
196         if (($i==1) and (@$filters[$i-1])) {
197             $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
198         }
199             # format the dates filters, otherwise just fill as is
200         if ($i>=2) {
201                 $cell{filter} = @$filters[$i];
202         } else {
203                 $cell{filter} = format_date(@$filters[$i]);
204                 }
205                 $cell{crit} = 
206                 ($i==0) ? "Period From"        :
207                 ($i==1) ? "Period To"          :
208                 ($i==2) ? "Patron Category ="  :
209                 ($i==3) ? "Item Type ="        :
210                 ($i==4) ? "Library ="          :
211                 ($i==5) ? "Collection ="       :
212                 ($i==6) ? "Location ="         :
213                 ($i==7) ? "Item callnumber >=" :
214                 ($i==8) ? "Item callnumber <"  :
215                 ($i==9) ? "sort1 ="            :
216                 ($i==10)? "sort2 ="            : "UNKNOWN FILTER ($i)";
217                 # FIXME - no translation mechanism !
218                 push @loopfilter, \%cell;
219     }
220         push @loopfilter,{crit=>"Event",       filter=>$type    };
221         push @loopfilter,{crit=>"Display by",  filter=>$dsp     } if ($dsp);
222         push @loopfilter,{crit=>"Select Day",  filter=>$daysel  } if ($daysel);
223         push @loopfilter,{crit=>"Select Month",filter=>$monthsel} if ($monthsel);
224
225         my @linefilter;
226         $debug and warn "filtres ". join "|", @filters;
227         my ($colsource, $linesource);
228         $linefilter[1] = @$filters[1] if ($line =~ /datetime/);
229         $linefilter[0] = ($line =~ /datetime/) ? @$filters[0]  :
230                                          ($line =~ /category/) ? @$filters[2]  :
231                                          ($line =~ /itemtype/) ? @$filters[3]  :
232                                          ($line =~ /branch/  ) ? @$filters[4]  :
233                                          ($line =~ /ccode/   ) ? @$filters[5]  :
234                                          ($line =~ /location/) ? @$filters[6]  :
235                                          ($line =~ /sort1/   ) ? @$filters[9]  :
236                                          ($line =~ /sort2/   ) ? @$filters[10] : undef ;
237         if ($line =~ /ccode/ or $line =~ /location/) {
238                 $linesource = 'items';
239         }
240
241         my @colfilter;
242         $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
243         $colfilter[0] = ($column =~ /datetime/) ? @$filters[0]  :
244                                         ($column =~ /category/) ? @$filters[2]  :
245                                         ($column =~ /itemtype/) ? @$filters[3]  :
246                                         ($column =~ /branch/  ) ? @$filters[4]  :
247                                         ($column =~ /ccode/   ) ? @$filters[5]  :
248                                         ($column =~ /location/) ? @$filters[6]  :
249                                         ($column =~ /sort1/   ) ? @$filters[9]  :
250                                         ($column =~ /sort1/   ) ? @$filters[10] : undef ;
251         if ($column =~ /ccode/ or $column =~ /location/) {
252                 $colsource = 'items';
253         }
254 # 1st, loop rows.
255         my $linefield;
256         if ($line =~ /datetime/) {
257                 # by Day, Month or Year (1,2,3 respectively)
258                 $linefield = ($dsp == 1) ? "  dayname($line)" :
259                                          ($dsp == 2) ? "monthname($line)" :
260                                          ($dsp == 3) ? "     Year($line)" :
261                                         'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
262         } else {
263                 $linefield = $line;
264         }
265         my $lineorder = ($linefield =~ /dayname/) ? "weekday($line)" :
266                                         ($linefield =~ /^month/ ) ? "  month($line)" : $linefield;
267
268         my $strsth = "SELECT distinctrow $linefield FROM statistics, ";
269                 # get stats on items if ccode or location, otherwise borrowers.
270         $strsth .= ($linesource eq 'items' ) ?
271                         " items     WHERE (statistics.itemnumber=items.itemnumber) " :
272                         " borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
273         $strsth .= " AND $line is not null ";
274
275         if ($line =~ /datetime/) {
276                 if ($linefilter[1] and ($linefilter[0])) {
277                         $strsth .= " AND $line between ? AND ? ";
278                 } elsif ($linefilter[1]) {
279                         $strsth .= " AND $line < ? ";
280                 } elsif ($linefilter[0]) {
281                 $strsth .= " AND $line > ? ";
282                 }
283                 $strsth .= " AND type ='".$type."' " if $type;
284                 $strsth .= " AND   dayname(datetime) ='".   $daysel ."' " if $daysel;
285                 $strsth .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
286         } elsif ($linefilter[0]) {
287                 $linefilter[0] =~ s/\*/%/g;
288                 $strsth .= " AND $line LIKE ? ";
289         }
290         $strsth .=" group by $linefield order by $lineorder ";
291         $debug and warn $strsth;
292         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth};
293         my $sth = $dbh->prepare( $strsth );
294         if ((@linefilter) and ($linefilter[1])){
295                 $sth->execute($linefilter[0],$linefilter[1]);
296         } elsif ($linefilter[0]) {
297                 $sth->execute($linefilter[0]);
298         } else {
299                 $sth->execute;
300         }
301
302         while (my ($celvalue) = $sth->fetchrow) {
303                 my %cell = (rowtitle => $celvalue, totalrow => 0); # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display
304                 $cell{rowtitle_display} =
305                         ($line =~ /ccode/   ) ? $ccodes->{$celvalue}    :
306                         ($line =~ /location/) ? $locations->{$celvalue} :
307                         ($line =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
308                         $celvalue; # default fallback
309                 if ($line =~ /sort1/) {
310                         foreach (@$Bsort1) {
311                                 ($celvalue eq $_->{authorised_value}) or next;
312                                 $cell{rowtitle_display} = $_->{lib} and last;
313                         }
314                 } elsif ($line =~ /sort2/) {
315                         foreach (@$Bsort2) {
316                                 ($celvalue eq $_->{authorised_value}) or next;
317                                 $cell{rowtitle_display} = $_->{lib} and last;
318                         }
319                 } elsif ($line =~ /category/) {
320                         foreach (@$categoryloop) {
321                                 ($celvalue eq $_->{categorycode}) or next;
322                                 $cell{rowtitle_display} = $_->{description} and last;
323                         }
324                 }
325                 push @loopline, \%cell;
326         }
327
328 # 2nd, loop cols.
329         my $colfield;
330         my $colorder;
331         if ($column =~ /datetime/) {
332                 #Display by Day, Month or Year (1,2,3 respectively)
333                 $colfield = ($dsp == 1) ? "  dayname($column)" :
334                                         ($dsp == 2) ? "monthname($column)" :
335                                         ($dsp == 3) ? "     Year($column)" :
336                                         'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
337         } else {
338                 $colfield = $column;
339         }
340         $colorder = ($colfield =~ /dayname/) ? "weekday($column)" :
341                                 ($colfield =~ /^month/ ) ? "  month($column)" : $colfield;
342         my $strsth2 = "SELECT distinctrow $colfield FROM statistics, ";
343         # get stats on items if ccode or location, otherwise borrowers.
344         $strsth2 .= ($colsource eq 'items' ) ?
345                                 "items     WHERE (statistics.itemnumber=items.itemnumber) " :
346                                 "borrowers WHERE (statistics.borrowernumber=borrowers.borrowernumber) ";
347         $strsth2 .= " AND $column IS NOT NULL ";
348
349         if ($column =~ /datetime/){
350         if (($colfilter[1]) and ($colfilter[0])){
351                         $strsth2 .= " AND $column BETWEEN ? AND ? " ;
352         } elsif ($colfilter[1]) {
353                         $strsth2 .= " AND $column < ? " ;
354         } elsif ($colfilter[0]) {
355                         $strsth2 .= " AND $column > ? " ;
356         }
357         $strsth2 .= " AND                type ='". $type     ."' " if $type;
358         $strsth2 .= " AND   dayname(datetime) ='". $daysel   ."' " if $daysel;
359         $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
360     } elsif ($colfilter[0]) {
361         $colfilter[0] =~ s/\*/%/g;
362         $strsth2 .= " AND $column LIKE ? " ;
363     }
364         $strsth2 .=" GROUP BY $colfield ORDER BY $colorder ";
365
366         my $sth2 = $dbh->prepare($strsth2);
367         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strsth2};
368         if ((@colfilter) and ($colfilter[1])){
369                 $sth2->execute($colfilter[0], $colfilter[1]);
370         } elsif ($colfilter[0]) {
371                 $sth2->execute($colfilter[0]);
372         } else {
373                 $sth2->execute;
374         }
375
376         while (my ($celvalue) = $sth2->fetchrow) {
377                 my %cell = (coltitle => $celvalue); # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display
378                 $cell{coltitle_display} =
379                         ($column =~ /ccode/   ) ?    $ccodes->{$celvalue} :
380                         ($column =~ /location/) ? $locations->{$celvalue} :
381                         ($column =~ /itemtype/) ? $itemtypes->{$celvalue}->{description} :
382                         $celvalue; # default fallback
383                 if ($column =~ /sort1/) {
384                         foreach (@$Bsort1) {
385                                 ($celvalue eq $_->{authorised_value}) or next;
386                                 $cell{coltitle_display} = $_->{lib} and last;
387                         }
388                 } elsif ($column =~ /sort2/) {
389                         foreach (@$Bsort2) {
390                                 ($celvalue eq $_->{authorised_value}) or next;
391                                 $cell{coltitle_display} = $_->{lib} and last;
392                         }
393                 } elsif ($column =~ /category/) {
394                         foreach (@$categoryloop) {
395                                 ($celvalue eq $_->{categorycode}) or next;
396                                 $cell{coltitle_display} = $_->{description} and last;
397                         }
398                 }
399                 push @loopcol, \%cell;
400         }
401
402         #Initialization of cell values.....
403         my %table;
404         foreach my $row (@loopline) {
405                 foreach my $col (@loopcol) {
406                         $debug and warn " init table : $row->{rowtitle} ( $row->{rowtitle_display} ) / $col->{coltitle} ( $col->{coltitle_display} )  ";
407                         $table{$row->{rowtitle}}->{$col->{coltitle}} = 0;
408                 }
409                 $table{$row->{rowtitle}}->{totalrow} = 0;
410         }
411
412 # preparing calculation
413     my $strcalc = "SELECT $linefield, $colfield, ";
414         $strcalc .= ($process == 1) ? " COUNT(*) "                                 :
415                                         ($process == 2) ? "(COUNT(DISTINCT borrowers.borrowernumber))" :
416                                 ($process == 3) ? "(COUNT(DISTINCT statistics.itemnumber))"        : '';
417         if ($process == 4) {
418                 my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
419                 $rqbookcount->execute;
420                 my ($bookcount) = $rqbookcount->fetchrow;
421                 $strcalc .= "100*(COUNT(DISTINCT statistics.itemnumber))/ $bookcount " ;
422         }
423         $strcalc .= "
424         FROM statistics
425         LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber
426         ";
427         $strcalc .= "LEFT JOIN items ON statistics.itemnumber=items.itemnumber "
428         if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or ($colsource eq 'items')
429             ||@$filters[5]||@$filters[6]||@$filters[7]||@$filters[8]);
430         
431         $strcalc .= "WHERE 1=1 ";
432         @$filters = map {defined($_) and s/\*/%/g; $_} @$filters;
433         $strcalc .= " AND statistics.datetime > '"       . @$filters[0] ."'" if (@$filters[0] );
434         $strcalc .= " AND statistics.datetime < '"       . @$filters[1] ."'" if (@$filters[1] );
435         $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] ."'" if (@$filters[2] );
436         $strcalc .= " AND statistics.itemtype LIKE '"    . @$filters[3] ."'" if (@$filters[3] );
437         $strcalc .= " AND statistics.branch LIKE '"      . @$filters[4] ."'" if (@$filters[4] );
438         $strcalc .= " AND items.ccode LIKE '"            . @$filters[5] ."'" if (@$filters[5] );
439         $strcalc .= " AND items.location LIKE '"         . @$filters[6] ."'" if (@$filters[6] );
440         $strcalc .= " AND items.itemcallnumber >='"      . @$filters[7] ."'" if (@$filters[7] );
441         $strcalc .= " AND items.itemcallnumber <'"       . @$filters[8] ."'" if (@$filters[8] );
442         $strcalc .= " AND borrowers.sort1 LIKE '"        . @$filters[9] ."'" if (@$filters[9] );
443         $strcalc .= " AND borrowers.sort2 LIKE '"        . @$filters[10]."'" if (@$filters[10]);
444         $strcalc .= " AND dayname(datetime) LIKE '"      . $daysel      ."'" if ($daysel  );
445         $strcalc .= " AND monthname(datetime) LIKE '"    . $monthsel    ."'" if ($monthsel);
446         $strcalc .= " AND statistics.type LIKE '"        . $type        ."'" if ($type    );
447
448         $strcalc .= " GROUP BY $linefield, $colfield order by $lineorder,$colorder";
449         ($debug) and warn $strcalc;
450         my $dbcalc = $dbh->prepare($strcalc);
451         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
452         $dbcalc->execute;
453         my ($emptycol,$emptyrow); 
454         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
455                 ($debug) and warn "filling table $row / $col / $value ";
456                 unless (defined $col) {
457                         $emptycol = 1; 
458                         $col = "zzEMPTY" ;
459                 }
460                 unless (defined $row) {
461                         $emptyrow = 1;
462                         $row = "zzEMPTY"; 
463                 }
464                 $table{$row}->{$col}     += $value;
465                 $table{$row}->{totalrow} += $value;
466                 $grantotal += $value;
467         }
468         push @loopcol, {coltitle => "NULL", coltitle_display => 'NULL'} if ($emptycol);
469         push @loopline,{rowtitle => "NULL", rowtitle_display => 'NULL'} if ($emptyrow);
470
471         foreach my $row (@loopline) {
472                 my @loopcell;
473                 #@loopcol ensures the order for columns is common with column titles
474                 # and the number matches the number of columns
475                 foreach my $col (@loopcol) {
476                         my $value = $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
477                         push @loopcell, {value => $value};
478                 }
479                 my $rowtitle = ($row->{rowtitle} eq "NULL") ? "zzEMPTY" : $row->{rowtitle};
480                 push @looprow, {
481                         'rowtitle_display' => $row->{rowtitle_display},
482                         'rowtitle' => $rowtitle,
483                         'loopcell' => \@loopcell,
484                         'totalrow' => $table{$rowtitle}->{totalrow}
485                 };
486         }
487         for my $col ( @loopcol ) {
488                 my $total = 0;
489                 foreach my $row (@looprow) {
490                         $total += $table{null_to_zzempty($row->{rowtitle})}->{null_to_zzempty($col->{coltitle})};
491                         $debug and warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
492                 }
493                 push @loopfooter, {'totalcol' => $total};
494         }
495
496         # the header of the table
497         $globalline{loopfilter}=\@loopfilter;
498         # the core of the table
499         $globalline{looprow} = \@looprow;
500         $globalline{loopcol} = \@loopcol;
501         #       # the foot (totals by borrower type)
502         $globalline{loopfooter} = \@loopfooter;
503         $globalline{total}  = $grantotal;
504         $globalline{line}   = $line;
505         $globalline{column} = $column;
506         return [(\%globalline)];
507 }
508
509 sub null_to_zzempty ($) {
510         my $string = shift;
511         defined($string)    or  return 'zzEMPTY';
512         ($string eq "NULL") and return 'zzEMPTY';
513         return $string;         # else return the valid value
514 }
515
516 1;