Bug 18958: Make hold_fill_targets specific to reserves
[koha.git] / reports / reserves_stats.pl
blob77d6eea72b385399e0c6253a22b874875db3fbcf
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 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,
77 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
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'] } ) };
82 my $Bsort1 = GetAuthorisedValues("Bsort1");
83 my $Bsort2 = GetAuthorisedValues("Bsort2");
84 my ($hassort1,$hassort2);
85 $hassort1=1 if $Bsort1;
86 $hassort2=1 if $Bsort2;
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;
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";
118 # footer
119 print "TOTAL";
120 $cols = @$results[0]->{loopfooter};
121 print map {$sep.$_->{totalcol}} @$cols;
122 print $sep.@$results[0]->{total};
124 exit; # exit either way after $do_it
127 my $dbh = C4::Context->dbh;
129 my $itemtypes = Koha::ItemTypes->search_with_localization;
131 # location list
132 my @locations;
133 foreach (sort keys %$locations) {
134 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
137 my @ccodes;
138 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
139 push @ccodes, { code => $_, description => $ccodes->{$_} };
142 # various
143 my $CGIextChoice = ( 'CSV' ); # FIXME translation
144 my $CGIsepChoice=GetDelimiterChoices;
146 $template->param(
147 categoryloop => \@patron_categories,
148 itemtypes => $itemtypes,
149 locationloop => \@locations,
150 ccodeloop => \@ccodes,
151 hassort1=> $hassort1,
152 hassort2=> $hassort2,
153 Bsort1 => $Bsort1,
154 Bsort2 => $Bsort2,
155 CGIextChoice => $CGIextChoice,
156 CGIsepChoice => $CGIsepChoice,
158 output_html_with_http_headers $input, $cookie, $template->output;
160 sub calculate {
161 my ($linefield, $colfield, $process, $filters_hashref) = @_;
162 my @loopfooter;
163 my @loopcol;
164 my @loopline;
165 my @looprow;
166 my %globalline;
167 my $grantotal =0;
168 # extract parameters
169 my $dbh = C4::Context->dbh;
171 # Filters
172 # Checking filters
174 my @loopfilter;
175 foreach my $filter ( keys %$filters_hashref ) {
176 $filters_hashref->{$filter} =~ s/\*/%/;
177 if ( $filter =~ /date/ ) {
178 $filters_hashref->{$filter} =
179 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
183 #display
184 @loopfilter = map {
186 crit => $_,
187 filter => (
188 $_ =~ /date/
189 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
190 : $filters_hashref->{$_}
193 } sort keys %$filters_hashref;
198 my $linesql=changeifreservestatus($linefield);
199 my $colsql=changeifreservestatus($colfield);
200 #Initialization of cell values.....
202 # preparing calculation
203 my $strcalc = "(SELECT $linesql line, $colsql col, ";
204 $strcalc .= ($process == 1) ? " COUNT(*) calculation" :
205 ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation" :
206 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation" :
207 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation" : '*';
208 $strcalc .= "
209 FROM (select * from reserves union select * from old_reserves) reserves
210 LEFT JOIN borrowers USING (borrowernumber)
212 $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
213 if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
214 $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
215 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
217 my @sqlparams;
218 my @sqlorparams;
219 my @sqlor;
220 my @sqlwhere;
221 ($debug) and print STDERR Dump($filters_hashref);
222 foreach my $filter (keys %$filters_hashref){
223 my $string;
224 my $stringfield=$filter;
225 $stringfield=~s/\_[a-z_]+$//;
226 if ($filter=~/ /){
227 $string=$stringfield;
229 elsif ($filter=~/_or/){
230 push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
231 push @sqlorparams, $$filters_hashref{$filter};
233 elsif ($filter=~/_endex$/){
234 $string = " $stringfield < ? ";
236 elsif ($filter=~/_end$/){
237 $string = " $stringfield <= ? ";
239 elsif ($filter=~/_begin$/){
240 $string = " $stringfield >= ? ";
242 else {
243 $string = " $stringfield LIKE ? ";
245 if ($string){
246 push @sqlwhere, $string;
247 push @sqlparams, $$filters_hashref{$filter};
251 $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
252 $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
253 $strcalc .= " GROUP BY line, col )";
254 ($debug) and print STDERR $strcalc;
255 my $dbcalc = $dbh->prepare($strcalc);
256 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
257 @sqlparams=(@sqlparams,@sqlorparams);
258 $dbcalc->execute(@sqlparams);
259 my $data = $dbcalc->fetchall_hashref([qw(line col)]);
260 my %cols_hash;
261 foreach my $row (keys %$data){
262 push @loopline, $row;
263 foreach my $col (keys %{$$data{$row}}){
264 $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
265 $grantotal+=$$data{$row}{$col}{calculation};
266 $cols_hash{$col}=1 ;
269 my $urlbase="do_it=1&amp;".join("&amp;",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
270 foreach my $row (sort @loopline) {
271 my @loopcell;
272 #@loopcol ensures the order for columns is common with column titles
273 # and the number matches the number of columns
274 foreach my $col (sort keys %cols_hash) {
275 push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
276 # url_complement=>($urlbase=~/&amp;$/?$urlbase."&amp;":$urlbase)."filter_$linefield=$row&amp;filter_$colfield=$col"
279 push @looprow, {
280 'rowtitle_display' => display_value($linefield,$row),
281 'rowtitle' => $row,
282 'loopcell' => \@loopcell,
283 'totalrow' => $$data{$row}{totalrow}
286 for my $col ( sort keys %cols_hash ) {
287 my $total = 0;
288 foreach my $row (@loopline) {
289 $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
290 $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
292 push @loopfooter, {'totalcol' => $total};
293 push @loopcol, {'coltitle' => $col,
294 coltitle_display=>display_value($colfield,$col)};
296 # the header of the table
297 $globalline{loopfilter}=\@loopfilter;
298 # the core of the table
299 $globalline{looprow} = \@looprow;
300 $globalline{loopcol} = \@loopcol;
301 # # the foot (totals by borrower type)
302 $globalline{loopfooter} = \@loopfooter;
303 $globalline{total} = $grantotal;
304 $globalline{line} = $linefield;
305 $globalline{column} = $colfield;
306 return [(\%globalline)];
309 sub display_value {
310 my ( $crit, $value ) = @_;
311 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
312 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
313 my $Bsort1 = GetAuthorisedValues("Bsort1");
314 my $Bsort2 = GetAuthorisedValues("Bsort2");
315 my $display_value =
316 ( $crit =~ /ccode/ ) ? $ccodes->{$value}
317 : ( $crit =~ /location/ ) ? $locations->{$value}
318 : ( $crit =~ /itemtype/ ) ? Koha::ItemTypes->find( $value )->translated_description
319 : ( $crit =~ /branch/ ) ? Koha::Libraries->find($value)->branchname
320 : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
321 : $value; # default fallback
322 if ($crit =~ /sort1/) {
323 foreach (@$Bsort1) {
324 ($value eq $_->{authorised_value}) or next;
325 $display_value = $_->{lib} and last;
328 elsif ($crit =~ /sort2/) {
329 foreach (@$Bsort2) {
330 ($value eq $_->{authorised_value}) or next;
331 $display_value = $_->{lib} and last;
334 elsif ( $crit =~ /category/ ) {
335 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
336 foreach my $patron_category ( @patron_categories ) {
337 ( $value eq $patron_category->categorycode ) or next;
338 $display_value = $patron_category->description and last;
341 return $display_value;
344 sub reservestatushuman{
345 my ($val)=@_;
346 my %hashhuman=(
347 1=>"1- placed",
348 2=>"2- processed",
349 3=>"3- pending",
350 4=>"4- satisfied",
351 5=>"5- cancelled",
352 6=>"6- not a status"
354 $hashhuman{$val};
357 sub changeifreservestatus{
358 my ($val)=@_;
359 ($val=~/reservestatus/
360 ?$val=qq{ case
361 when priority>0 then 1
362 when priority=0 then
363 (case
364 when found='f' then 4
365 when found='w' then
366 (case
367 when cancellationdate is null then 3
368 else 5
369 end )
370 else 2
371 end )
372 else 6
373 end }
374 :$val);