Bug 9634: Allow for combining same paraneters in SQL reports
[koha.git] / reports / reserves_stats.pl
1 #!/usr/bin/perl
2
3 # Copyright 2010 BibLibre
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use Modern::Perl;
21
22 use CGI qw ( -utf8 );
23
24 use C4::Auth;
25 use C4::Debug;
26 use C4::Context;
27 use C4::Koha;
28 use C4::Output;
29 use C4::Reports;
30 use C4::Members;
31 use Koha::AuthorisedValues;
32 use Koha::DateUtils;
33 use Koha::ItemTypes;
34 use Koha::Libraries;
35 use Koha::Patron::Categories;
36 use List::MoreUtils qw/any/;
37 use YAML;
38
39 =head1 NAME
40
41     reports/reserve_stats.pl
42
43 =head1 DESCRIPTION
44
45     Plugin that shows reserve stats
46
47 =cut
48
49 # my $debug = 1;        # override for now.
50 my $input = new CGI;
51 my $fullreportname = "reports/reserves_stats.tt";
52 my $do_it    = $input->param('do_it');
53 my $line     = $input->param("Line");
54 my $column   = $input->param("Column");
55 my $calc     = $input->param("Cellvalue");
56 my $output   = $input->param("output");
57 my $basename = $input->param("basename");
58 my $hash_params = $input->Vars;
59 my $filter_hashref;
60 foreach my $filter (grep {$_ =~/^filter/} keys %$hash_params){
61         my $filterstring=$filter;
62         $filterstring=~s/^filter_//g;
63         $$filter_hashref{$filterstring}=$$hash_params{$filter} if (defined $$hash_params{$filter} && $$hash_params{$filter} ne "");
64 }
65 my ($template, $borrowernumber, $cookie) = get_template_and_user({
66         template_name => $fullreportname,
67         query => $input,
68         type => "intranet",
69         authnotrequired => 0,
70         flagsrequired => {reports => '*'},
71         debug => 0,
72 });
73 our $sep     = $input->param("sep") || '';
74 $sep = "\t" if ($sep eq 'tabulation');
75 $template->param(do_it => $do_it,
76 );
77
78 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
79
80 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
81 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
82
83 my $Bsort1 = GetAuthorisedValues("Bsort1");
84 my $Bsort2 = GetAuthorisedValues("Bsort2");
85 my ($hassort1,$hassort2);
86 $hassort1=1 if $Bsort1;
87 $hassort2=1 if $Bsort2;
88
89
90 if ($do_it) {
91 # Displaying results
92         my $results = calculate($line, $column,  $calc, $filter_hashref);
93         if ($output eq "screen"){
94 # Printing results to screen
95                 $template->param(mainloop => $results);
96                 output_html_with_http_headers $input, $cookie, $template->output;
97         } else {
98 # Printing to a csv file
99         print $input->header(-type => 'application/vnd.sun.xml.calc',
100                             -encoding    => 'utf-8',
101                             -attachment=>"$basename.csv",
102                             -filename=>"$basename.csv" );
103                 my $cols  = @$results[0]->{loopcol};
104                 my $lines = @$results[0]->{looprow};
105 # header top-right
106                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
107 # Other header
108                 foreach my $col ( @$cols ) {
109                         print $col->{coltitle}.$sep;
110                 }
111                 print "Total\n";
112 # Table
113                 foreach my $line ( @$lines ) {
114                         my $x = $line->{loopcell};
115                         print $line->{rowtitle}.$sep;
116                         print map {$_->{value}.$sep} @$x;
117                         print $line->{totalrow}, "\n";
118                 }
119 # footer
120         print "TOTAL";
121         $cols = @$results[0]->{loopfooter};
122                 print map {$sep.$_->{totalcol}} @$cols;
123         print $sep.@$results[0]->{total};
124         }
125         exit; # exit either way after $do_it
126 }
127
128 my $dbh = C4::Context->dbh;
129 my @values;
130 my %labels;
131 my %select;
132
133 my $itemtypes = Koha::ItemTypes->search_with_localization;
134
135     # location list
136 my @locations;
137 foreach (sort keys %$locations) {
138         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
139 }
140     
141 my @ccodes;
142 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
143         push @ccodes, { code => $_, description => $ccodes->{$_} };
144 }
145
146 # various
147 my $CGIextChoice = ( 'CSV' ); # FIXME translation
148 my $CGIsepChoice=GetDelimiterChoices;
149  
150 $template->param(
151     categoryloop => \@patron_categories,
152     itemtypes => $itemtypes,
153         locationloop => \@locations,
154            ccodeloop => \@ccodes,
155         hassort1=> $hassort1,
156         hassort2=> $hassort2,
157         Bsort1 => $Bsort1,
158         Bsort2 => $Bsort2,
159         CGIextChoice => $CGIextChoice,
160         CGIsepChoice => $CGIsepChoice,
161 );
162 output_html_with_http_headers $input, $cookie, $template->output;
163
164 sub calculate {
165         my ($linefield, $colfield, $process, $filters_hashref) = @_;
166         my @loopfooter;
167         my @loopcol;
168         my @loopline;
169         my @looprow;
170         my %globalline;
171         my $grantotal =0;
172 # extract parameters
173         my $dbh = C4::Context->dbh;
174
175 # Filters
176 # Checking filters
177 #
178     my @loopfilter;
179     foreach my $filter ( keys %$filters_hashref ) {
180         $filters_hashref->{$filter} =~ s/\*/%/;
181         if ( $filter =~ /date/ ) {
182             $filters_hashref->{$filter} =
183                 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
184         }
185     }
186
187     #display
188     @loopfilter = map {
189         {
190             crit   => $_,
191             filter => (
192                 $_ =~ /date/
193                 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
194                 : $filters_hashref->{$_}
195             )
196         }
197     } sort keys %$filters_hashref;
198
199
200
201
202         my $linesql=changeifreservestatus($linefield);
203         my $colsql=changeifreservestatus($colfield);
204         #Initialization of cell values.....
205
206         # preparing calculation
207     my $strcalc = "(SELECT $linesql line, $colsql col, ";
208         $strcalc .= ($process == 1) ? " COUNT(*)  calculation"                                 :
209                                         ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation"  :
210                                 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation"      : 
211                                 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation"    : '*';
212         $strcalc .= "
213         FROM (select * from reserves union select * from old_reserves) reserves
214         LEFT JOIN borrowers USING (borrowernumber)
215         ";
216         $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
217         if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
218         $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
219         if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
220
221         my @sqlparams;
222         my @sqlorparams;
223         my @sqlor;
224         my @sqlwhere;
225         ($debug) and print STDERR Dump($filters_hashref);
226         foreach my $filter (keys %$filters_hashref){
227                 my $string;
228                 my $stringfield=$filter;
229                 $stringfield=~s/\_[a-z_]+$//;
230                 if ($filter=~/ /){
231                         $string=$stringfield;
232                 }
233                 elsif ($filter=~/_or/){
234                          push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
235                          push @sqlorparams, $$filters_hashref{$filter};
236                 }
237                 elsif ($filter=~/_endex$/){
238                         $string = " $stringfield < ? ";
239                 }
240                 elsif ($filter=~/_end$/){
241                         $string = " $stringfield <= ? ";
242                 }
243                 elsif ($filter=~/_begin$/){
244                         $string = " $stringfield >= ? ";
245                 }
246                 else {
247                         $string = " $stringfield LIKE ? ";
248                 }
249                 if ($string){
250                         push @sqlwhere, $string;
251                         push @sqlparams, $$filters_hashref{$filter};
252                 }
253         }
254
255         $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
256         $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
257         $strcalc .= " GROUP BY line, col )";
258         ($debug) and print STDERR $strcalc;
259         my $dbcalc = $dbh->prepare($strcalc);
260         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
261         @sqlparams=(@sqlparams,@sqlorparams);
262         $dbcalc->execute(@sqlparams);
263         my ($emptycol,$emptyrow); 
264         my $data = $dbcalc->fetchall_hashref([qw(line col)]);
265         my %cols_hash;
266         foreach my $row (keys %$data){
267                 push @loopline, $row;
268                 foreach my $col (keys %{$$data{$row}}){
269                         $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
270                         $grantotal+=$$data{$row}{$col}{calculation};
271                         $cols_hash{$col}=1 ;
272                 }
273         }
274         my $urlbase="do_it=1&amp;".join("&amp;",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
275         foreach my $row (sort @loopline) {
276                 my @loopcell;
277                 #@loopcol ensures the order for columns is common with column titles
278                 # and the number matches the number of columns
279                 foreach my $col (sort keys %cols_hash) {
280                         push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
281         #                                               url_complement=>($urlbase=~/&amp;$/?$urlbase."&amp;":$urlbase)."filter_$linefield=$row&amp;filter_$colfield=$col"
282                                                         }
283                 }
284                 push @looprow, {
285                         'rowtitle_display' => display_value($linefield,$row),
286                         'rowtitle' => $row,
287                         'loopcell' => \@loopcell,
288                         'totalrow' => $$data{$row}{totalrow}
289                 };
290         }
291         for my $col ( sort keys %cols_hash ) {
292                 my $total = 0;
293                 foreach my $row (@loopline) {
294                         $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
295                         $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
296                 }
297                 push @loopfooter, {'totalcol' => $total};
298                 push @loopcol, {'coltitle' => $col,
299                                                 coltitle_display=>display_value($colfield,$col)};
300         }
301         # the header of the table
302         $globalline{loopfilter}=\@loopfilter;
303         # the core of the table
304         $globalline{looprow} = \@looprow;
305         $globalline{loopcol} = \@loopcol;
306         #       # the foot (totals by borrower type)
307         $globalline{loopfooter} = \@loopfooter;
308         $globalline{total}  = $grantotal;
309         $globalline{line}   = $linefield;
310         $globalline{column} = $colfield;
311         return [(\%globalline)];
312 }
313
314 sub display_value {
315     my ( $crit, $value ) = @_;
316     my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
317     my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
318     my $Bsort1 = GetAuthorisedValues("Bsort1");
319     my $Bsort2 = GetAuthorisedValues("Bsort2");
320     my $display_value =
321         ( $crit =~ /ccode/ )         ? $ccodes->{$value}
322       : ( $crit =~ /location/ )      ? $locations->{$value}
323       : ( $crit =~ /itemtype/ )      ? Koha::ItemTypes->find( $value )->translated_description
324       : ( $crit =~ /branch/ )        ? Koha::Libraries->find($value)->branchname
325       : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
326       :                                $value;    # default fallback
327     if ($crit =~ /sort1/) {
328         foreach (@$Bsort1) {
329             ($value eq $_->{authorised_value}) or next;
330             $display_value = $_->{lib} and last;
331         }
332     }
333     elsif ($crit =~ /sort2/) {
334         foreach (@$Bsort2) {
335             ($value eq $_->{authorised_value}) or next;
336             $display_value = $_->{lib} and last;
337         }
338     }
339     elsif ( $crit =~ /category/ ) {
340         my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
341         foreach my $patron_category ( @patron_categories ) {
342             ( $value eq $patron_category->categorycode ) or next;
343             $display_value = $patron_category->description and last;
344         }
345     }
346     return $display_value;
347 }
348
349 sub reservestatushuman{
350         my ($val)=@_;
351         my %hashhuman=(
352         1=>"1- placed",
353         2=>"2- processed",
354         3=>"3- pending",
355         4=>"4- satisfied",
356         5=>"5- cancelled",
357         6=>"6- not a status"
358         );
359         $hashhuman{$val};
360 }
361
362 sub changeifreservestatus{
363         my ($val)=@_;
364         ($val=~/reservestatus/
365                 ?$val=qq{ case 
366                                         when priority>0 then 1 
367                                         when priority=0 then
368                                                 (case 
369                                                    when found='f' then 4
370                                                    when found='w' then 
371                                                    (case 
372                                                     when cancellationdate is null then 3
373                                                         else 5
374                                                         end )
375                                                    else 2 
376                                                  end )
377                                     else 6 
378                                         end }
379                 :$val);
380 }