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>.
31 use Koha::AuthorisedValues;
35 use Koha::Patron::Categories;
36 use List::MoreUtils qw/any/;
40 reports/reserve_stats.pl
44 Plugin that shows reserve stats
48 # my $debug = 1; # override for now.
50 my $fullreportname = "reports/reserves_stats.tt";
51 my $do_it = $input->param('do_it');
52 my $line = $input->param("Line");
53 my $column = $input->param("Column");
54 my $calc = $input->param("Cellvalue");
55 my $output = $input->param("output");
56 my $basename = $input->param("basename");
57 my $hash_params = $input->Vars;
59 foreach my $filter (grep {$_ =~/^filter/} keys %$hash_params){
60 my $filterstring=$filter;
61 $filterstring=~s/^filter_//g;
62 $$filter_hashref{$filterstring}=$$hash_params{$filter} if (defined $$hash_params{$filter} && $$hash_params{$filter} ne "");
64 my ($template, $borrowernumber, $cookie) = get_template_and_user({
65 template_name => $fullreportname,
68 flagsrequired => {reports => '*'},
70 our $sep = $input->param("sep") || '';
71 $sep = "\t" if ($sep eq 'tabulation');
72 $template->param(do_it => $do_it,
75 my @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']});
77 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
78 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
80 my $Bsort1 = GetAuthorisedValues("Bsort1");
81 my $Bsort2 = GetAuthorisedValues("Bsort2");
82 my ($hassort1,$hassort2);
83 $hassort1=1 if $Bsort1;
84 $hassort2=1 if $Bsort2;
89 my $results = calculate($line, $column, $calc, $filter_hashref);
90 if ($output eq "screen"){
91 # Printing results to screen
92 $template->param(mainloop => $results);
93 output_html_with_http_headers $input, $cookie, $template->output;
95 # Printing to a csv file
96 print $input->header(-type => 'application/vnd.sun.xml.calc',
98 -attachment=>"$basename.csv",
99 -filename=>"$basename.csv" );
100 my $cols = @$results[0]->{loopcol};
101 my $lines = @$results[0]->{looprow};
103 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
105 foreach my $col ( @$cols ) {
106 print $col->{coltitle}.$sep;
110 foreach my $line ( @$lines ) {
111 my $x = $line->{loopcell};
112 print $line->{rowtitle}.$sep;
113 print map {$_->{value}.$sep} @$x;
114 print $line->{totalrow}, "\n";
118 $cols = @$results[0]->{loopfooter};
119 print map {$sep.$_->{totalcol}} @$cols;
120 print $sep.@$results[0]->{total};
122 exit; # exit either way after $do_it
125 my $dbh = C4::Context->dbh;
127 my $itemtypes = Koha::ItemTypes->search_with_localization;
131 foreach (sort keys %$locations) {
132 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
136 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
137 push @ccodes, { code => $_, description => $ccodes->{$_} };
141 my $CGIextChoice = ( 'CSV' ); # FIXME translation
142 my $CGIsepChoice=GetDelimiterChoices;
145 categoryloop => \@patron_categories,
146 itemtypes => $itemtypes,
147 locationloop => \@locations,
148 ccodeloop => \@ccodes,
149 hassort1=> $hassort1,
150 hassort2=> $hassort2,
153 CGIextChoice => $CGIextChoice,
154 CGIsepChoice => $CGIsepChoice,
156 output_html_with_http_headers $input, $cookie, $template->output;
159 my ($linefield, $colfield, $process, $filters_hashref) = @_;
167 my $dbh = C4::Context->dbh;
173 foreach my $filter ( keys %$filters_hashref ) {
174 $filters_hashref->{$filter} =~ s/\*/%/;
175 if ( $filter =~ /date/ ) {
176 $filters_hashref->{$filter} =
177 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
187 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
188 : $filters_hashref->{$_}
191 } sort keys %$filters_hashref;
196 my $linesql=changeifreservestatus($linefield);
197 my $colsql=changeifreservestatus($colfield);
198 #Initialization of cell values.....
200 # preparing calculation
201 my $strcalc = "(SELECT $linesql line, $colsql col, ";
202 $strcalc .= ($process == 1) ? " COUNT(*) calculation" :
203 ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation" :
204 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation" :
205 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation" : '*';
207 FROM (select * from reserves union select * from old_reserves) reserves
208 LEFT JOIN borrowers USING (borrowernumber)
210 $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
211 if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
212 $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
213 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
219 foreach my $filter (keys %$filters_hashref){
221 my $stringfield=$filter;
222 $stringfield=~s/\_[a-z_]+$//;
224 $string=$stringfield;
226 elsif ($filter=~/_or/){
227 push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
228 push @sqlorparams, $$filters_hashref{$filter};
230 elsif ($filter=~/_endex$/){
231 $string = " $stringfield < ? ";
233 elsif ($filter=~/_end$/){
234 $string = " $stringfield <= ? ";
236 elsif ($filter=~/_begin$/){
237 $string = " $stringfield >= ? ";
240 $string = " $stringfield LIKE ? ";
243 push @sqlwhere, $string;
244 push @sqlparams, $$filters_hashref{$filter};
248 $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
249 $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
250 $strcalc .= " GROUP BY line, col )";
251 ($debug) and print STDERR $strcalc;
252 my $dbcalc = $dbh->prepare($strcalc);
253 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
254 @sqlparams=(@sqlparams,@sqlorparams);
255 $dbcalc->execute(@sqlparams);
256 my $data = $dbcalc->fetchall_hashref([qw(line col)]);
258 foreach my $row (keys %$data){
259 push @loopline, $row;
260 foreach my $col (keys %{$$data{$row}}){
261 $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
262 $grantotal+=$$data{$row}{$col}{calculation};
266 my $urlbase="do_it=1&".join("&",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
267 foreach my $row (sort @loopline) {
269 #@loopcol ensures the order for columns is common with column titles
270 # and the number matches the number of columns
271 foreach my $col (sort keys %cols_hash) {
272 push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
273 # url_complement=>($urlbase=~/&$/?$urlbase."&":$urlbase)."filter_$linefield=$row&filter_$colfield=$col"
277 'rowtitle_display' => display_value($linefield,$row),
279 'loopcell' => \@loopcell,
280 'totalrow' => $$data{$row}{totalrow}
283 for my $col ( sort keys %cols_hash ) {
285 foreach my $row (@loopline) {
286 $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
287 $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
289 push @loopfooter, {'totalcol' => $total};
290 push @loopcol, {'coltitle' => $col,
291 coltitle_display=>display_value($colfield,$col)};
293 # the header of the table
294 $globalline{loopfilter}=\@loopfilter;
295 # the core of the table
296 $globalline{looprow} = \@looprow;
297 $globalline{loopcol} = \@loopcol;
298 # # the foot (totals by borrower type)
299 $globalline{loopfooter} = \@loopfooter;
300 $globalline{total} = $grantotal;
301 $globalline{line} = $linefield;
302 $globalline{column} = $colfield;
303 return [(\%globalline)];
307 my ( $crit, $value ) = @_;
308 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
309 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
310 my $Bsort1 = GetAuthorisedValues("Bsort1");
311 my $Bsort2 = GetAuthorisedValues("Bsort2");
313 ( $crit =~ /ccode/ ) ? $ccodes->{$value}
314 : ( $crit =~ /location/ ) ? $locations->{$value}
315 : ( $crit =~ /itemtype/ ) ? Koha::ItemTypes->find( $value )->translated_description
316 : ( $crit =~ /branch/ ) ? Koha::Libraries->find($value)->branchname
317 : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
318 : $value; # default fallback
319 if ($crit =~ /sort1/) {
321 ($value eq $_->{authorised_value}) or next;
322 $display_value = $_->{lib} and last;
325 elsif ($crit =~ /sort2/) {
327 ($value eq $_->{authorised_value}) or next;
328 $display_value = $_->{lib} and last;
331 elsif ( $crit =~ /category/ ) {
332 my @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']});
333 foreach my $patron_category ( @patron_categories ) {
334 ( $value eq $patron_category->categorycode ) or next;
335 $display_value = $patron_category->description and last;
338 return $display_value;
341 sub reservestatushuman{
354 sub changeifreservestatus{
356 ($val=~/reservestatus/
358 when priority>0 then 1
361 when found='f' then 4
364 when cancellationdate is null then 3