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
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.
31 use Koha::AuthorisedValues;
35 use Koha::Patron::Categories;
36 use List::MoreUtils qw/any/;
41 reports/reserve_stats.pl
45 Plugin that shows reserve stats
49 # my $debug = 1; # override for now.
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;
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,
69 flagsrequired => {reports => '*'},
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;
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;
97 # Printing to a csv file
98 print $input->header(-type => 'application/vnd.sun.xml.calc',
100 -attachment=>"$basename.csv",
101 -filename=>"$basename.csv" );
102 my $cols = @$results[0]->{loopcol};
103 my $lines = @$results[0]->{looprow};
105 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
107 foreach my $col ( @$cols ) {
108 print $col->{coltitle}.$sep;
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";
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;
132 my $itemtypes = Koha::ItemTypes->search_with_localization;
136 foreach (sort keys %$locations) {
137 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
141 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
142 push @ccodes, { code => $_, description => $ccodes->{$_} };
146 my $CGIextChoice = ( 'CSV' ); # FIXME translation
147 my $CGIsepChoice=GetDelimiterChoices;
150 categoryloop => \@patron_categories,
151 itemtypes => $itemtypes,
152 locationloop => \@locations,
153 ccodeloop => \@ccodes,
154 hassort1=> $hassort1,
155 hassort2=> $hassort2,
158 CGIextChoice => $CGIextChoice,
159 CGIsepChoice => $CGIsepChoice,
161 output_html_with_http_headers $input, $cookie, $template->output;
164 my ($linefield, $colfield, $process, $filters_hashref) = @_;
172 my $dbh = C4::Context->dbh;
178 foreach my $filter ( keys %$filters_hashref ) {
179 $filters_hashref->{$filter} =~ s/\*/%/;
180 if ( $filter =~ /date/ ) {
181 $filters_hashref->{$filter} =
182 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
192 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
193 : $filters_hashref->{$_}
196 } sort keys %$filters_hashref;
201 my $linesql=changeifreservestatus($linefield);
202 my $colsql=changeifreservestatus($colfield);
203 #Initialization of cell values.....
205 # preparing calculation
206 my $strcalc = "(SELECT $linesql line, $colsql col, ";
207 $strcalc .= ($process == 1) ? " COUNT(*) calculation" :
208 ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation" :
209 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation" :
210 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation" : '*';
212 FROM (select * from reserves union select * from old_reserves) reserves
213 LEFT JOIN borrowers USING (borrowernumber)
215 $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
216 if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
217 $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
218 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
224 ($debug) and print STDERR Dump($filters_hashref);
225 foreach my $filter (keys %$filters_hashref){
227 my $stringfield=$filter;
228 $stringfield=~s/\_[a-z_]+$//;
230 $string=$stringfield;
232 elsif ($filter=~/_or/){
233 push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
234 push @sqlorparams, $$filters_hashref{$filter};
236 elsif ($filter=~/_endex$/){
237 $string = " $stringfield < ? ";
239 elsif ($filter=~/_end$/){
240 $string = " $stringfield <= ? ";
242 elsif ($filter=~/_begin$/){
243 $string = " $stringfield >= ? ";
246 $string = " $stringfield LIKE ? ";
249 push @sqlwhere, $string;
250 push @sqlparams, $$filters_hashref{$filter};
254 $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
255 $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
256 $strcalc .= " GROUP BY line, col )";
257 ($debug) and print STDERR $strcalc;
258 my $dbcalc = $dbh->prepare($strcalc);
259 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
260 @sqlparams=(@sqlparams,@sqlorparams);
261 $dbcalc->execute(@sqlparams);
262 my ($emptycol,$emptyrow);
263 my $data = $dbcalc->fetchall_hashref([qw(line col)]);
265 foreach my $row (keys %$data){
266 push @loopline, $row;
267 foreach my $col (keys %{$$data{$row}}){
268 $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
269 $grantotal+=$$data{$row}{$col}{calculation};
273 my $urlbase="do_it=1&".join("&",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
274 foreach my $row (sort @loopline) {
276 #@loopcol ensures the order for columns is common with column titles
277 # and the number matches the number of columns
278 foreach my $col (sort keys %cols_hash) {
279 push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
280 # url_complement=>($urlbase=~/&$/?$urlbase."&":$urlbase)."filter_$linefield=$row&filter_$colfield=$col"
284 'rowtitle_display' => display_value($linefield,$row),
286 'loopcell' => \@loopcell,
287 'totalrow' => $$data{$row}{totalrow}
290 for my $col ( sort keys %cols_hash ) {
292 foreach my $row (@loopline) {
293 $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
294 $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
296 push @loopfooter, {'totalcol' => $total};
297 push @loopcol, {'coltitle' => $col,
298 coltitle_display=>display_value($colfield,$col)};
300 # the header of the table
301 $globalline{loopfilter}=\@loopfilter;
302 # the core of the table
303 $globalline{looprow} = \@looprow;
304 $globalline{loopcol} = \@loopcol;
305 # # the foot (totals by borrower type)
306 $globalline{loopfooter} = \@loopfooter;
307 $globalline{total} = $grantotal;
308 $globalline{line} = $linefield;
309 $globalline{column} = $colfield;
310 return [(\%globalline)];
314 my ( $crit, $value ) = @_;
315 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
316 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
317 my $Bsort1 = GetAuthorisedValues("Bsort1");
318 my $Bsort2 = GetAuthorisedValues("Bsort2");
320 ( $crit =~ /ccode/ ) ? $ccodes->{$value}
321 : ( $crit =~ /location/ ) ? $locations->{$value}
322 : ( $crit =~ /itemtype/ ) ? Koha::ItemTypes->find( $value )->translated_description
323 : ( $crit =~ /branch/ ) ? Koha::Libraries->find($value)->branchname
324 : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
325 : $value; # default fallback
326 if ($crit =~ /sort1/) {
328 ($value eq $_->{authorised_value}) or next;
329 $display_value = $_->{lib} and last;
332 elsif ($crit =~ /sort2/) {
334 ($value eq $_->{authorised_value}) or next;
335 $display_value = $_->{lib} and last;
338 elsif ( $crit =~ /category/ ) {
339 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
340 foreach my $patron_category ( @patron_categories ) {
341 ( $value eq $patron_category->categorycode ) or next;
342 $display_value = $patron_category->description and last;
345 return $display_value;
348 sub reservestatushuman{
361 sub changeifreservestatus{
363 ($val=~/reservestatus/
365 when priority>0 then 1
368 when found='f' then 4
371 when cancellationdate is null then 3