Bug 17585: Replace ->get_account_lines with ->account
[koha.git] / reports / reserves_stats.pl
blob79dd39190e1af640eff2a46542521e6e04315011
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::Koha;
30 use C4::Output;
31 use C4::Reports;
32 use C4::Members;
33 use Koha::AuthorisedValues;
34 use Koha::DateUtils;
35 use Koha::Libraries;
36 use Koha::Patron::Categories;
37 use List::MoreUtils qw/any/;
38 use YAML;
40 =head1 NAME
42 reports/reserve_stats.pl
44 =head1 DESCRIPTION
46 Plugin that shows circulation stats
48 =cut
50 # my $debug = 1; # override for now.
51 my $input = new CGI;
52 my $fullreportname = "reports/reserves_stats.tt";
53 my $do_it = $input->param('do_it');
54 my $line = $input->param("Line");
55 my $column = $input->param("Column");
56 my $podsp = $input->param("DisplayBy");
57 my $type = $input->param("PeriodTypeSel");
58 my $daysel = $input->param("PeriodDaySel");
59 my $monthsel = $input->param("PeriodMonthSel");
60 my $calc = $input->param("Cellvalue");
61 my $output = $input->param("output");
62 my $basename = $input->param("basename");
63 my $mime = $input->param("MIME");
64 my $hash_params = $input->Vars;
65 my $filter_hashref;
66 foreach my $filter (grep {$_ =~/^filter/} keys %$hash_params){
67 my $filterstring=$filter;
68 $filterstring=~s/^filter_//g;
69 $$filter_hashref{$filterstring}=$$hash_params{$filter} if (defined $$hash_params{$filter} && $$hash_params{$filter} ne "");
71 my ($template, $borrowernumber, $cookie) = get_template_and_user({
72 template_name => $fullreportname,
73 query => $input,
74 type => "intranet",
75 authnotrequired => 0,
76 flagsrequired => {reports => '*'},
77 debug => 0,
78 });
79 our $sep = $input->param("sep") || '';
80 $sep = "\t" if ($sep eq 'tabulation');
81 $template->param(do_it => $do_it,
84 my $itemtypes = GetItemTypes();
85 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
87 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
88 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
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 => \@patron_categories,
163 itemtypeloop => \@itemtypeloop,
164 locationloop => \@locations,
165 ccodeloop => \@ccodes,
166 hassort1=> $hassort1,
167 hassort2=> $hassort2,
168 Bsort1 => $Bsort1,
169 Bsort2 => $Bsort2,
170 CGIextChoice => $CGIextChoice,
171 CGIsepChoice => $CGIsepChoice,
173 output_html_with_http_headers $input, $cookie, $template->output;
175 sub calculate {
176 my ($linefield, $colfield, $process, $filters_hashref) = @_;
177 my @loopfooter;
178 my @loopcol;
179 my @loopline;
180 my @looprow;
181 my %globalline;
182 my $grantotal =0;
183 # extract parameters
184 my $dbh = C4::Context->dbh;
186 # Filters
187 # Checking filters
189 my @loopfilter;
190 foreach my $filter ( keys %$filters_hashref ) {
191 $filters_hashref->{$filter} =~ s/\*/%/;
192 if ( $filter =~ /date/ ) {
193 $filters_hashref->{$filter} =
194 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
198 #display
199 @loopfilter = map {
201 crit => $_,
202 filter => (
203 $_ =~ /date/
204 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
205 : $filters_hashref->{$_}
208 } sort keys %$filters_hashref;
213 my $linesql=changeifreservestatus($linefield);
214 my $colsql=changeifreservestatus($colfield);
215 #Initialization of cell values.....
217 # preparing calculation
218 my $strcalc = "(SELECT $linesql line, $colsql col, ";
219 $strcalc .= ($process == 1) ? " COUNT(*) calculation" :
220 ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation" :
221 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation" :
222 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation" : '*';
223 $strcalc .= "
224 FROM (select * from reserves union select * from old_reserves) reserves
225 LEFT JOIN borrowers USING (borrowernumber)
227 $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
228 if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
229 $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
230 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
232 my @sqlparams;
233 my @sqlorparams;
234 my @sqlor;
235 my @sqlwhere;
236 ($debug) and print STDERR Dump($filters_hashref);
237 foreach my $filter (keys %$filters_hashref){
238 my $string;
239 my $stringfield=$filter;
240 $stringfield=~s/\_[a-z_]+$//;
241 if ($filter=~/ /){
242 $string=$stringfield;
244 elsif ($filter=~/_or/){
245 push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
246 push @sqlorparams, $$filters_hashref{$filter};
248 elsif ($filter=~/_endex$/){
249 $string = " $stringfield < ? ";
251 elsif ($filter=~/_end$/){
252 $string = " $stringfield <= ? ";
254 elsif ($filter=~/_begin$/){
255 $string = " $stringfield >= ? ";
257 else {
258 $string = " $stringfield LIKE ? ";
260 if ($string){
261 push @sqlwhere, $string;
262 push @sqlparams, $$filters_hashref{$filter};
266 $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
267 $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
268 $strcalc .= " GROUP BY line, col )";
269 ($debug) and print STDERR $strcalc;
270 my $dbcalc = $dbh->prepare($strcalc);
271 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
272 @sqlparams=(@sqlparams,@sqlorparams);
273 $dbcalc->execute(@sqlparams);
274 my ($emptycol,$emptyrow);
275 my $data = $dbcalc->fetchall_hashref([qw(line col)]);
276 my %cols_hash;
277 foreach my $row (keys %$data){
278 push @loopline, $row;
279 foreach my $col (keys %{$$data{$row}}){
280 $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
281 $grantotal+=$$data{$row}{$col}{calculation};
282 $cols_hash{$col}=1 ;
285 my $urlbase="do_it=1&amp;".join("&amp;",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
286 foreach my $row (sort @loopline) {
287 my @loopcell;
288 #@loopcol ensures the order for columns is common with column titles
289 # and the number matches the number of columns
290 foreach my $col (sort keys %cols_hash) {
291 push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
292 # url_complement=>($urlbase=~/&amp;$/?$urlbase."&amp;":$urlbase)."filter_$linefield=$row&amp;filter_$colfield=$col"
295 push @looprow, {
296 'rowtitle_display' => display_value($linefield,$row),
297 'rowtitle' => $row,
298 'loopcell' => \@loopcell,
299 'totalrow' => $$data{$row}{totalrow}
302 for my $col ( sort keys %cols_hash ) {
303 my $total = 0;
304 foreach my $row (@loopline) {
305 $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
306 $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
308 push @loopfooter, {'totalcol' => $total};
309 push @loopcol, {'coltitle' => $col,
310 coltitle_display=>display_value($colfield,$col)};
312 # the header of the table
313 $globalline{loopfilter}=\@loopfilter;
314 # the core of the table
315 $globalline{looprow} = \@looprow;
316 $globalline{loopcol} = \@loopcol;
317 # # the foot (totals by borrower type)
318 $globalline{loopfooter} = \@loopfooter;
319 $globalline{total} = $grantotal;
320 $globalline{line} = $linefield;
321 $globalline{column} = $colfield;
322 return [(\%globalline)];
325 sub null_to_zzempty ($) {
326 my $string = shift;
327 defined($string) or return 'zzEMPTY';
328 ($string eq "NULL") and return 'zzEMPTY';
329 return $string; # else return the valid value
331 sub display_value {
332 my ( $crit, $value ) = @_;
333 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
334 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
335 my $itemtypes = GetItemTypes();
336 my $Bsort1 = GetAuthorisedValues("Bsort1");
337 my $Bsort2 = GetAuthorisedValues("Bsort2");
338 my $display_value =
339 ( $crit =~ /ccode/ ) ? $ccodes->{$value}
340 : ( $crit =~ /location/ ) ? $locations->{$value}
341 : ( $crit =~ /itemtype/ ) ? $itemtypes->{$value}->{description}
342 : ( $crit =~ /branch/ ) ? Koha::Libraries->find($value)->branchname
343 : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
344 : $value; # default fallback
345 if ($crit =~ /sort1/) {
346 foreach (@$Bsort1) {
347 ($value eq $_->{authorised_value}) or next;
348 $display_value = $_->{lib} and last;
351 elsif ($crit =~ /sort2/) {
352 foreach (@$Bsort2) {
353 ($value eq $_->{authorised_value}) or next;
354 $display_value = $_->{lib} and last;
357 elsif ( $crit =~ /category/ ) {
358 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
359 foreach my $patron_category ( @patron_categories ) {
360 ( $value eq $patron_category->categorycode ) or next;
361 $display_value = $patron_category->description and last;
364 return $display_value;
366 sub reservestatushuman{
367 my ($val)=@_;
368 my %hashhuman=(
369 1=>"1- placed",
370 2=>"2- processed",
371 3=>"3- pending",
372 4=>"4- satisfied",
373 5=>"5- cancelled",
374 6=>"6- not a status"
376 $hashhuman{$val};
378 sub changeifreservestatus{
379 my ($val)=@_;
380 ($val=~/reservestatus/
381 ?$val=qq{ case
382 when priority>0 then 1
383 when priority=0 then
384 (case
385 when found='f' then 4
386 when found='w' then
387 (case
388 when cancellationdate is null then 3
389 else 5
390 end )
391 else 2
392 end )
393 else 6
394 end }
395 :$val);