Merge branch 'new/security-release-19.11.10' into 19.11.x
[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         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 );
76
77 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
78
79 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
80 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
81
82 my $Bsort1 = GetAuthorisedValues("Bsort1");
83 my $Bsort2 = GetAuthorisedValues("Bsort2");
84 my ($hassort1,$hassort2);
85 $hassort1=1 if $Bsort1;
86 $hassort2=1 if $Bsort2;
87
88
89 if ($do_it) {
90 # Displaying results
91         my $results = calculate($line, $column,  $calc, $filter_hashref);
92         if ($output eq "screen"){
93 # Printing results to screen
94                 $template->param(mainloop => $results);
95                 output_html_with_http_headers $input, $cookie, $template->output;
96         } else {
97 # Printing to a csv file
98         print $input->header(-type => 'application/vnd.sun.xml.calc',
99                             -encoding    => 'utf-8',
100                             -attachment=>"$basename.csv",
101                             -filename=>"$basename.csv" );
102                 my $cols  = @$results[0]->{loopcol};
103                 my $lines = @$results[0]->{looprow};
104 # header top-right
105                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
106 # Other header
107                 foreach my $col ( @$cols ) {
108                         print $col->{coltitle}.$sep;
109                 }
110                 print "Total\n";
111 # Table
112                 foreach my $line ( @$lines ) {
113                         my $x = $line->{loopcell};
114                         print $line->{rowtitle}.$sep;
115                         print map {$_->{value}.$sep} @$x;
116                         print $line->{totalrow}, "\n";
117                 }
118 # footer
119         print "TOTAL";
120         $cols = @$results[0]->{loopfooter};
121                 print map {$sep.$_->{totalcol}} @$cols;
122         print $sep.@$results[0]->{total};
123         }
124         exit; # exit either way after $do_it
125 }
126
127 my $dbh = C4::Context->dbh;
128 my @values;
129 my %labels;
130 my %select;
131
132 my $itemtypes = Koha::ItemTypes->search_with_localization;
133
134     # location list
135 my @locations;
136 foreach (sort keys %$locations) {
137         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
138 }
139     
140 my @ccodes;
141 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
142         push @ccodes, { code => $_, description => $ccodes->{$_} };
143 }
144
145 # various
146 my $CGIextChoice = ( 'CSV' ); # FIXME translation
147 my $CGIsepChoice=GetDelimiterChoices;
148  
149 $template->param(
150     categoryloop => \@patron_categories,
151     itemtypes => $itemtypes,
152         locationloop => \@locations,
153            ccodeloop => \@ccodes,
154         hassort1=> $hassort1,
155         hassort2=> $hassort2,
156         Bsort1 => $Bsort1,
157         Bsort2 => $Bsort2,
158         CGIextChoice => $CGIextChoice,
159         CGIsepChoice => $CGIsepChoice,
160 );
161 output_html_with_http_headers $input, $cookie, $template->output;
162
163 sub calculate {
164         my ($linefield, $colfield, $process, $filters_hashref) = @_;
165         my @loopfooter;
166         my @loopcol;
167         my @loopline;
168         my @looprow;
169         my %globalline;
170         my $grantotal =0;
171 # extract parameters
172         my $dbh = C4::Context->dbh;
173
174 # Filters
175 # Checking filters
176 #
177     my @loopfilter;
178     foreach my $filter ( keys %$filters_hashref ) {
179         $filters_hashref->{$filter} =~ s/\*/%/;
180         if ( $filter =~ /date/ ) {
181             $filters_hashref->{$filter} =
182                 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
183         }
184     }
185
186     #display
187     @loopfilter = map {
188         {
189             crit   => $_,
190             filter => (
191                 $_ =~ /date/
192                 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
193                 : $filters_hashref->{$_}
194             )
195         }
196     } sort keys %$filters_hashref;
197
198
199
200
201         my $linesql=changeifreservestatus($linefield);
202         my $colsql=changeifreservestatus($colfield);
203         #Initialization of cell values.....
204
205         # preparing calculation
206     my $strcalc = "(SELECT $linesql line, $colsql col, ";
207         $strcalc .= ($process == 1) ? " COUNT(*)  calculation"                                 :
208                                         ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation"  :
209                                 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation"      : 
210                                 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation"    : '*';
211         $strcalc .= "
212         FROM (select * from reserves union select * from old_reserves) reserves
213         LEFT JOIN borrowers USING (borrowernumber)
214         ";
215         $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
216         if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
217         $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
218         if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
219
220         my @sqlparams;
221         my @sqlorparams;
222         my @sqlor;
223         my @sqlwhere;
224         ($debug) and print STDERR Dump($filters_hashref);
225         foreach my $filter (keys %$filters_hashref){
226                 my $string;
227                 my $stringfield=$filter;
228                 $stringfield=~s/\_[a-z_]+$//;
229                 if ($filter=~/ /){
230                         $string=$stringfield;
231                 }
232                 elsif ($filter=~/_or/){
233                          push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
234                          push @sqlorparams, $$filters_hashref{$filter};
235                 }
236                 elsif ($filter=~/_endex$/){
237                         $string = " $stringfield < ? ";
238                 }
239                 elsif ($filter=~/_end$/){
240                         $string = " $stringfield <= ? ";
241                 }
242                 elsif ($filter=~/_begin$/){
243                         $string = " $stringfield >= ? ";
244                 }
245                 else {
246                         $string = " $stringfield LIKE ? ";
247                 }
248                 if ($string){
249                         push @sqlwhere, $string;
250                         push @sqlparams, $$filters_hashref{$filter};
251                 }
252         }
253
254         $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
255         $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
256         $strcalc .= " GROUP BY line, col )";
257         ($debug) and print STDERR $strcalc;
258         my $dbcalc = $dbh->prepare($strcalc);
259         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
260         @sqlparams=(@sqlparams,@sqlorparams);
261         $dbcalc->execute(@sqlparams);
262         my ($emptycol,$emptyrow); 
263         my $data = $dbcalc->fetchall_hashref([qw(line col)]);
264         my %cols_hash;
265         foreach my $row (keys %$data){
266                 push @loopline, $row;
267                 foreach my $col (keys %{$$data{$row}}){
268                         $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
269                         $grantotal+=$$data{$row}{$col}{calculation};
270                         $cols_hash{$col}=1 ;
271                 }
272         }
273         my $urlbase="do_it=1&amp;".join("&amp;",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
274         foreach my $row (sort @loopline) {
275                 my @loopcell;
276                 #@loopcol ensures the order for columns is common with column titles
277                 # and the number matches the number of columns
278                 foreach my $col (sort keys %cols_hash) {
279                         push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
280         #                                               url_complement=>($urlbase=~/&amp;$/?$urlbase."&amp;":$urlbase)."filter_$linefield=$row&amp;filter_$colfield=$col"
281                                                         }
282                 }
283                 push @looprow, {
284                         'rowtitle_display' => display_value($linefield,$row),
285                         'rowtitle' => $row,
286                         'loopcell' => \@loopcell,
287                         'totalrow' => $$data{$row}{totalrow}
288                 };
289         }
290         for my $col ( sort keys %cols_hash ) {
291                 my $total = 0;
292                 foreach my $row (@loopline) {
293                         $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
294                         $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
295                 }
296                 push @loopfooter, {'totalcol' => $total};
297                 push @loopcol, {'coltitle' => $col,
298                                                 coltitle_display=>display_value($colfield,$col)};
299         }
300         # the header of the table
301         $globalline{loopfilter}=\@loopfilter;
302         # the core of the table
303         $globalline{looprow} = \@looprow;
304         $globalline{loopcol} = \@loopcol;
305         #       # the foot (totals by borrower type)
306         $globalline{loopfooter} = \@loopfooter;
307         $globalline{total}  = $grantotal;
308         $globalline{line}   = $linefield;
309         $globalline{column} = $colfield;
310         return [(\%globalline)];
311 }
312
313 sub display_value {
314     my ( $crit, $value ) = @_;
315     my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
316     my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
317     my $Bsort1 = GetAuthorisedValues("Bsort1");
318     my $Bsort2 = GetAuthorisedValues("Bsort2");
319     my $display_value =
320         ( $crit =~ /ccode/ )         ? $ccodes->{$value}
321       : ( $crit =~ /location/ )      ? $locations->{$value}
322       : ( $crit =~ /itemtype/ )      ? Koha::ItemTypes->find( $value )->translated_description
323       : ( $crit =~ /branch/ )        ? Koha::Libraries->find($value)->branchname
324       : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
325       :                                $value;    # default fallback
326     if ($crit =~ /sort1/) {
327         foreach (@$Bsort1) {
328             ($value eq $_->{authorised_value}) or next;
329             $display_value = $_->{lib} and last;
330         }
331     }
332     elsif ($crit =~ /sort2/) {
333         foreach (@$Bsort2) {
334             ($value eq $_->{authorised_value}) or next;
335             $display_value = $_->{lib} and last;
336         }
337     }
338     elsif ( $crit =~ /category/ ) {
339         my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
340         foreach my $patron_category ( @patron_categories ) {
341             ( $value eq $patron_category->categorycode ) or next;
342             $display_value = $patron_category->description and last;
343         }
344     }
345     return $display_value;
346 }
347
348 sub reservestatushuman{
349         my ($val)=@_;
350         my %hashhuman=(
351         1=>"1- placed",
352         2=>"2- processed",
353         3=>"3- pending",
354         4=>"4- satisfied",
355         5=>"5- cancelled",
356         6=>"6- not a status"
357         );
358         $hashhuman{$val};
359 }
360
361 sub changeifreservestatus{
362         my ($val)=@_;
363         ($val=~/reservestatus/
364                 ?$val=qq{ case 
365                                         when priority>0 then 1 
366                                         when priority=0 then
367                                                 (case 
368                                                    when found='f' then 4
369                                                    when found='w' then 
370                                                    (case 
371                                                     when cancellationdate is null then 3
372                                                         else 5
373                                                         end )
374                                                    else 2 
375                                                  end )
376                                     else 6 
377                                         end }
378                 :$val);
379 }