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