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