Bug 22789: (QA follow-up) Some minor formatting changes
[koha.git] / reports / reserves_stats.pl
blob1d22561b19155b928ccb87823fd7ee54c716db64
1 #!/usr/bin/perl
3 # Copyright 2010 BibLibre
5 # This file is part of Koha.
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.
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.
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>.
20 use Modern::Perl;
22 use CGI qw ( -utf8 );
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;
39 =head1 NAME
41 reports/reserve_stats.pl
43 =head1 DESCRIPTION
45 Plugin that shows reserve stats
47 =cut
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 "");
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,
78 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
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'] } ) };
83 my $Bsort1 = GetAuthorisedValues("Bsort1");
84 my $Bsort2 = GetAuthorisedValues("Bsort2");
85 my ($hassort1,$hassort2);
86 $hassort1=1 if $Bsort1;
87 $hassort2=1 if $Bsort2;
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;
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";
119 # footer
120 print "TOTAL";
121 $cols = @$results[0]->{loopfooter};
122 print map {$sep.$_->{totalcol}} @$cols;
123 print $sep.@$results[0]->{total};
125 exit; # exit either way after $do_it
128 my $dbh = C4::Context->dbh;
130 my $itemtypes = Koha::ItemTypes->search_with_localization;
132 # location list
133 my @locations;
134 foreach (sort keys %$locations) {
135 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
138 my @ccodes;
139 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
140 push @ccodes, { code => $_, description => $ccodes->{$_} };
143 # various
144 my $CGIextChoice = ( 'CSV' ); # FIXME translation
145 my $CGIsepChoice=GetDelimiterChoices;
147 $template->param(
148 categoryloop => \@patron_categories,
149 itemtypes => $itemtypes,
150 locationloop => \@locations,
151 ccodeloop => \@ccodes,
152 hassort1=> $hassort1,
153 hassort2=> $hassort2,
154 Bsort1 => $Bsort1,
155 Bsort2 => $Bsort2,
156 CGIextChoice => $CGIextChoice,
157 CGIsepChoice => $CGIsepChoice,
159 output_html_with_http_headers $input, $cookie, $template->output;
161 sub calculate {
162 my ($linefield, $colfield, $process, $filters_hashref) = @_;
163 my @loopfooter;
164 my @loopcol;
165 my @loopline;
166 my @looprow;
167 my %globalline;
168 my $grantotal =0;
169 # extract parameters
170 my $dbh = C4::Context->dbh;
172 # Filters
173 # Checking filters
175 my @loopfilter;
176 foreach my $filter ( keys %$filters_hashref ) {
177 $filters_hashref->{$filter} =~ s/\*/%/;
178 if ( $filter =~ /date/ ) {
179 $filters_hashref->{$filter} =
180 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
184 #display
185 @loopfilter = map {
187 crit => $_,
188 filter => (
189 $_ =~ /date/
190 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
191 : $filters_hashref->{$_}
194 } sort keys %$filters_hashref;
199 my $linesql=changeifreservestatus($linefield);
200 my $colsql=changeifreservestatus($colfield);
201 #Initialization of cell values.....
203 # preparing calculation
204 my $strcalc = "(SELECT $linesql line, $colsql col, ";
205 $strcalc .= ($process == 1) ? " COUNT(*) calculation" :
206 ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation" :
207 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation" :
208 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation" : '*';
209 $strcalc .= "
210 FROM (select * from reserves union select * from old_reserves) reserves
211 LEFT JOIN borrowers USING (borrowernumber)
213 $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
214 if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
215 $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
216 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
218 my @sqlparams;
219 my @sqlorparams;
220 my @sqlor;
221 my @sqlwhere;
222 ($debug) and print STDERR Dump($filters_hashref);
223 foreach my $filter (keys %$filters_hashref){
224 my $string;
225 my $stringfield=$filter;
226 $stringfield=~s/\_[a-z_]+$//;
227 if ($filter=~/ /){
228 $string=$stringfield;
230 elsif ($filter=~/_or/){
231 push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
232 push @sqlorparams, $$filters_hashref{$filter};
234 elsif ($filter=~/_endex$/){
235 $string = " $stringfield < ? ";
237 elsif ($filter=~/_end$/){
238 $string = " $stringfield <= ? ";
240 elsif ($filter=~/_begin$/){
241 $string = " $stringfield >= ? ";
243 else {
244 $string = " $stringfield LIKE ? ";
246 if ($string){
247 push @sqlwhere, $string;
248 push @sqlparams, $$filters_hashref{$filter};
252 $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
253 $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
254 $strcalc .= " GROUP BY line, col )";
255 ($debug) and print STDERR $strcalc;
256 my $dbcalc = $dbh->prepare($strcalc);
257 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
258 @sqlparams=(@sqlparams,@sqlorparams);
259 $dbcalc->execute(@sqlparams);
260 my $data = $dbcalc->fetchall_hashref([qw(line col)]);
261 my %cols_hash;
262 foreach my $row (keys %$data){
263 push @loopline, $row;
264 foreach my $col (keys %{$$data{$row}}){
265 $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
266 $grantotal+=$$data{$row}{$col}{calculation};
267 $cols_hash{$col}=1 ;
270 my $urlbase="do_it=1&amp;".join("&amp;",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
271 foreach my $row (sort @loopline) {
272 my @loopcell;
273 #@loopcol ensures the order for columns is common with column titles
274 # and the number matches the number of columns
275 foreach my $col (sort keys %cols_hash) {
276 push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
277 # url_complement=>($urlbase=~/&amp;$/?$urlbase."&amp;":$urlbase)."filter_$linefield=$row&amp;filter_$colfield=$col"
280 push @looprow, {
281 'rowtitle_display' => display_value($linefield,$row),
282 'rowtitle' => $row,
283 'loopcell' => \@loopcell,
284 'totalrow' => $$data{$row}{totalrow}
287 for my $col ( sort keys %cols_hash ) {
288 my $total = 0;
289 foreach my $row (@loopline) {
290 $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
291 $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
293 push @loopfooter, {'totalcol' => $total};
294 push @loopcol, {'coltitle' => $col,
295 coltitle_display=>display_value($colfield,$col)};
297 # the header of the table
298 $globalline{loopfilter}=\@loopfilter;
299 # the core of the table
300 $globalline{looprow} = \@looprow;
301 $globalline{loopcol} = \@loopcol;
302 # # the foot (totals by borrower type)
303 $globalline{loopfooter} = \@loopfooter;
304 $globalline{total} = $grantotal;
305 $globalline{line} = $linefield;
306 $globalline{column} = $colfield;
307 return [(\%globalline)];
310 sub display_value {
311 my ( $crit, $value ) = @_;
312 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
313 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
314 my $Bsort1 = GetAuthorisedValues("Bsort1");
315 my $Bsort2 = GetAuthorisedValues("Bsort2");
316 my $display_value =
317 ( $crit =~ /ccode/ ) ? $ccodes->{$value}
318 : ( $crit =~ /location/ ) ? $locations->{$value}
319 : ( $crit =~ /itemtype/ ) ? Koha::ItemTypes->find( $value )->translated_description
320 : ( $crit =~ /branch/ ) ? Koha::Libraries->find($value)->branchname
321 : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
322 : $value; # default fallback
323 if ($crit =~ /sort1/) {
324 foreach (@$Bsort1) {
325 ($value eq $_->{authorised_value}) or next;
326 $display_value = $_->{lib} and last;
329 elsif ($crit =~ /sort2/) {
330 foreach (@$Bsort2) {
331 ($value eq $_->{authorised_value}) or next;
332 $display_value = $_->{lib} and last;
335 elsif ( $crit =~ /category/ ) {
336 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
337 foreach my $patron_category ( @patron_categories ) {
338 ( $value eq $patron_category->categorycode ) or next;
339 $display_value = $patron_category->description and last;
342 return $display_value;
345 sub reservestatushuman{
346 my ($val)=@_;
347 my %hashhuman=(
348 1=>"1- placed",
349 2=>"2- processed",
350 3=>"3- pending",
351 4=>"4- satisfied",
352 5=>"5- cancelled",
353 6=>"6- not a status"
355 $hashhuman{$val};
358 sub changeifreservestatus{
359 my ($val)=@_;
360 ($val=~/reservestatus/
361 ?$val=qq{ case
362 when priority>0 then 1
363 when priority=0 then
364 (case
365 when found='f' then 4
366 when found='w' then
367 (case
368 when cancellationdate is null then 3
369 else 5
370 end )
371 else 2
372 end )
373 else 6
374 end }
375 :$val);