Bug 11569: Correcting typos in userpermissions.sql
[koha.git] / reports / reserves_stats.pl
blob792a7721e221b1ec54db8b1f2a3ee7e7f45d2bde
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 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.
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.
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.
21 use strict;
22 use warnings;
24 use CGI qw ( -utf8 );
26 use C4::Auth;
27 use C4::Debug;
28 use C4::Context;
29 use C4::Branch; # GetBranches
30 use C4::Koha;
31 use C4::Output;
32 use C4::Reports;
33 use C4::Members;
34 use C4::Category;
35 use Koha::DateUtils;
36 use List::MoreUtils qw/any/;
37 use YAML;
39 =head1 NAME
41 plugin that shows circulation stats
43 =head1 DESCRIPTION
45 =over 2
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 $podsp = $input->param("DisplayBy");
56 my $type = $input->param("PeriodTypeSel");
57 my $daysel = $input->param("PeriodDaySel");
58 my $monthsel = $input->param("PeriodMonthSel");
59 my $calc = $input->param("Cellvalue");
60 my $output = $input->param("output");
61 my $basename = $input->param("basename");
62 my $mime = $input->param("MIME");
63 my $hash_params = $input->Vars;
64 my $filter_hashref;
65 foreach my $filter (grep {$_ =~/^filter/} keys %$hash_params){
66 my $filterstring=$filter;
67 $filterstring=~s/^filter_//g;
68 $$filter_hashref{$filterstring}=$$hash_params{$filter} if (defined $$hash_params{$filter} && $$hash_params{$filter} ne "");
70 my ($template, $borrowernumber, $cookie) = get_template_and_user({
71 template_name => $fullreportname,
72 query => $input,
73 type => "intranet",
74 authnotrequired => 0,
75 flagsrequired => {reports => '*'},
76 debug => 0,
77 });
78 our $sep = $input->param("sep") || '';
79 $sep = "\t" if ($sep eq 'tabulation');
80 $template->param(do_it => $do_it,
83 my $itemtypes = GetItemTypes();
84 my $categoryloop = GetBorrowercategoryList;
86 my $ccodes = GetKohaAuthorisedValues("items.ccode");
87 my $locations = GetKohaAuthorisedValues("items.location");
88 my $authvalue = GetKohaAuthorisedValues("items.authvalue");
90 my $Bsort1 = GetAuthorisedValues("Bsort1");
91 my $Bsort2 = GetAuthorisedValues("Bsort2");
92 my ($hassort1,$hassort2);
93 $hassort1=1 if $Bsort1;
94 $hassort2=1 if $Bsort2;
97 if ($do_it) {
98 # Displaying results
99 my $results = calculate($line, $column, $calc, $filter_hashref);
100 if ($output eq "screen"){
101 # Printing results to screen
102 $template->param(mainloop => $results);
103 output_html_with_http_headers $input, $cookie, $template->output;
104 } else {
105 # Printing to a csv file
106 print $input->header(-type => 'application/vnd.sun.xml.calc',
107 -encoding => 'utf-8',
108 -attachment=>"$basename.csv",
109 -filename=>"$basename.csv" );
110 my $cols = @$results[0]->{loopcol};
111 my $lines = @$results[0]->{looprow};
112 # header top-right
113 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
114 # Other header
115 foreach my $col ( @$cols ) {
116 print $col->{coltitle}.$sep;
118 print "Total\n";
119 # Table
120 foreach my $line ( @$lines ) {
121 my $x = $line->{loopcell};
122 print $line->{rowtitle}.$sep;
123 print map {$_->{value}.$sep} @$x;
124 print $line->{totalrow}, "\n";
126 # footer
127 print "TOTAL";
128 $cols = @$results[0]->{loopfooter};
129 print map {$sep.$_->{totalcol}} @$cols;
130 print $sep.@$results[0]->{total};
132 exit; # exit either way after $do_it
135 my $dbh = C4::Context->dbh;
136 my @values;
137 my %labels;
138 my %select;
140 # create itemtype arrayref for <select>.
141 my @itemtypeloop;
142 for my $itype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description}} keys(%$itemtypes)) {
143 push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{translated_description} } ;
146 # location list
147 my @locations;
148 foreach (sort keys %$locations) {
149 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
152 my @ccodes;
153 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
154 push @ccodes, { code => $_, description => $ccodes->{$_} };
157 # various
158 my $CGIextChoice = ( 'CSV' ); # FIXME translation
159 my $CGIsepChoice=GetDelimiterChoices;
161 $template->param(
162 categoryloop => $categoryloop,
163 itemtypeloop => \@itemtypeloop,
164 locationloop => \@locations,
165 ccodeloop => \@ccodes,
166 branchloop => GetBranchesLoop(C4::Context->userenv->{'branch'}),
167 hassort1=> $hassort1,
168 hassort2=> $hassort2,
169 Bsort1 => $Bsort1,
170 Bsort2 => $Bsort2,
171 CGIextChoice => $CGIextChoice,
172 CGIsepChoice => $CGIsepChoice,
174 output_html_with_http_headers $input, $cookie, $template->output;
176 sub calculate {
177 my ($linefield, $colfield, $process, $filters_hashref) = @_;
178 my @loopfooter;
179 my @loopcol;
180 my @loopline;
181 my @looprow;
182 my %globalline;
183 my $grantotal =0;
184 # extract parameters
185 my $dbh = C4::Context->dbh;
187 # Filters
188 # Checking filters
190 my @loopfilter;
191 foreach my $filter ( keys %$filters_hashref ) {
192 $filters_hashref->{$filter} =~ s/\*/%/;
193 if ( $filter =~ /date/ ) {
194 $filters_hashref->{$filter} =
195 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
199 #display
200 @loopfilter = map {
202 crit => $_,
203 filter => (
204 $_ =~ /date/
205 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
206 : $filters_hashref->{$_}
209 } sort keys %$filters_hashref;
214 my $linesql=changeifreservestatus($linefield);
215 my $colsql=changeifreservestatus($colfield);
216 #Initialization of cell values.....
218 # preparing calculation
219 my $strcalc = "(SELECT $linesql line, $colsql col, ";
220 $strcalc .= ($process == 1) ? " COUNT(*) calculation" :
221 ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation" :
222 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation" :
223 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation" : '*';
224 $strcalc .= "
225 FROM reserves
226 LEFT JOIN borrowers USING (borrowernumber)
228 $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
229 if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
230 $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
231 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
233 my @sqlparams;
234 my @sqlorparams;
235 my @sqlor;
236 my @sqlwhere;
237 ($debug) and print STDERR Dump($filters_hashref);
238 foreach my $filter (keys %$filters_hashref){
239 my $string;
240 my $stringfield=$filter;
241 $stringfield=~s/\_[a-z_]+$//;
242 if ($filter=~/ /){
243 $string=$stringfield;
245 elsif ($filter=~/_or/){
246 push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
247 push @sqlorparams, $$filters_hashref{$filter};
249 elsif ($filter=~/_endex$/){
250 $string = " $stringfield < ? ";
252 elsif ($filter=~/_end$/){
253 $string = " $stringfield <= ? ";
255 elsif ($filter=~/_begin$/){
256 $string = " $stringfield >= ? ";
258 else {
259 $string = " $stringfield LIKE ? ";
261 if ($string){
262 push @sqlwhere, $string;
263 push @sqlparams, $$filters_hashref{$filter};
267 $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
268 $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
269 $strcalc .= " GROUP BY line, col )";
270 my $strcalc_old=$strcalc;
271 $strcalc_old=~s/reserves/old_reserves/g;
272 $strcalc.=qq{ UNION $strcalc_old ORDER BY line, col};
273 ($debug) and print STDERR $strcalc;
274 my $dbcalc = $dbh->prepare($strcalc);
275 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
276 @sqlparams=(@sqlparams,@sqlorparams);
277 $dbcalc->execute(@sqlparams,@sqlparams);
278 my ($emptycol,$emptyrow);
279 my $data = $dbcalc->fetchall_hashref([qw(line col)]);
280 my %cols_hash;
281 foreach my $row (keys %$data){
282 push @loopline, $row;
283 foreach my $col (keys %{$$data{$row}}){
284 $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
285 $grantotal+=$$data{$row}{$col}{calculation};
286 $cols_hash{$col}=1 ;
289 my $urlbase="do_it=1&amp;".join("&amp;",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
290 foreach my $row (sort @loopline) {
291 my @loopcell;
292 #@loopcol ensures the order for columns is common with column titles
293 # and the number matches the number of columns
294 foreach my $col (sort keys %cols_hash) {
295 push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
296 # url_complement=>($urlbase=~/&amp;$/?$urlbase."&amp;":$urlbase)."filter_$linefield=$row&amp;filter_$colfield=$col"
299 push @looprow, {
300 'rowtitle_display' => display_value($linefield,$row),
301 'rowtitle' => $row,
302 'loopcell' => \@loopcell,
303 'totalrow' => $$data{$row}{totalrow}
306 for my $col ( sort keys %cols_hash ) {
307 my $total = 0;
308 foreach my $row (@loopline) {
309 $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
310 $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
312 push @loopfooter, {'totalcol' => $total};
313 push @loopcol, {'coltitle' => $col,
314 coltitle_display=>display_value($colfield,$col)};
316 # the header of the table
317 $globalline{loopfilter}=\@loopfilter;
318 # the core of the table
319 $globalline{looprow} = \@looprow;
320 $globalline{loopcol} = \@loopcol;
321 # # the foot (totals by borrower type)
322 $globalline{loopfooter} = \@loopfooter;
323 $globalline{total} = $grantotal;
324 $globalline{line} = $linefield;
325 $globalline{column} = $colfield;
326 return [(\%globalline)];
329 sub null_to_zzempty ($) {
330 my $string = shift;
331 defined($string) or return 'zzEMPTY';
332 ($string eq "NULL") and return 'zzEMPTY';
333 return $string; # else return the valid value
335 sub display_value {
336 my ( $crit, $value ) = @_;
337 my $display_value =
338 ( $crit =~ /ccode/ ) ? $ccodes->{$value}
339 : ( $crit =~ /location/ ) ? $locations->{$value}
340 : ( $crit =~ /itemtype/ ) ? $itemtypes->{$value}->{description}
341 : ( $crit =~ /branch/ ) ? GetBranchName($value)
342 : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
343 : $value; # default fallback
344 if ($crit =~ /sort1/) {
345 foreach (@$Bsort1) {
346 ($value eq $_->{authorised_value}) or next;
347 $display_value = $_->{lib} and last;
350 elsif ($crit =~ /sort2/) {
351 foreach (@$Bsort2) {
352 ($value eq $_->{authorised_value}) or next;
353 $display_value = $_->{lib} and last;
356 elsif ( $crit =~ /category/ ) {
357 foreach (@$categoryloop) {
358 ( $value eq $_->{categorycode} ) or next;
359 $display_value = $_->{description} and last;
362 return $display_value;
364 sub reservestatushuman{
365 my ($val)=@_;
366 my %hashhuman=(
367 1=>"1- placed",
368 2=>"2- processed",
369 3=>"3- pending",
370 4=>"4- satisfied",
371 5=>"5- cancelled",
372 6=>"6- not a status"
374 $hashhuman{$val};
376 sub changeifreservestatus{
377 my ($val)=@_;
378 ($val=~/reservestatus/
379 ?$val=qq{ case
380 when priority>0 then 1
381 when priority=0 then
382 (case
383 when found='f' then 4
384 when found='w' then
385 (case
386 when cancellationdate is null then 3
387 else 5
388 end )
389 else 2
390 end )
391 else 6
392 end }
393 :$val);