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,
70 flagsrequired => {reports => '*'},
73 our $sep = $input->param("sep") || '';
74 $sep = "\t" if ($sep eq 'tabulation');
75 $template->param(do_it => $do_it,
78 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
80 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
81 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
83 my $Bsort1 = GetAuthorisedValues("Bsort1");
84 my $Bsort2 = GetAuthorisedValues("Bsort2");
85 my ($hassort1,$hassort2);
86 $hassort1=1 if $Bsort1;
87 $hassort2=1 if $Bsort2;
92 my $results = calculate($line, $column, $calc, $filter_hashref);
93 if ($output eq "screen"){
94 # Printing results to screen
95 $template->param(mainloop => $results);
96 output_html_with_http_headers $input, $cookie, $template->output;
98 # Printing to a csv file
99 print $input->header(-type => 'application/vnd.sun.xml.calc',
100 -encoding => 'utf-8',
101 -attachment=>"$basename.csv",
102 -filename=>"$basename.csv" );
103 my $cols = @$results[0]->{loopcol};
104 my $lines = @$results[0]->{looprow};
106 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
108 foreach my $col ( @$cols ) {
109 print $col->{coltitle}.$sep;
113 foreach my $line ( @$lines ) {
114 my $x = $line->{loopcell};
115 print $line->{rowtitle}.$sep;
116 print map {$_->{value}.$sep} @$x;
117 print $line->{totalrow}, "\n";
121 $cols = @$results[0]->{loopfooter};
122 print map {$sep.$_->{totalcol}} @$cols;
123 print $sep.@$results[0]->{total};
125 exit; # exit either way after $do_it
128 my $dbh = C4::Context->dbh;
133 my $itemtypes = Koha::ItemTypes->search_with_localization;
137 foreach (sort keys %$locations) {
138 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
142 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
143 push @ccodes, { code => $_, description => $ccodes->{$_} };
147 my $CGIextChoice = ( 'CSV' ); # FIXME translation
148 my $CGIsepChoice=GetDelimiterChoices;
151 categoryloop => \@patron_categories,
152 itemtypes => $itemtypes,
153 locationloop => \@locations,
154 ccodeloop => \@ccodes,
155 hassort1=> $hassort1,
156 hassort2=> $hassort2,
159 CGIextChoice => $CGIextChoice,
160 CGIsepChoice => $CGIsepChoice,
162 output_html_with_http_headers $input, $cookie, $template->output;
165 my ($linefield, $colfield, $process, $filters_hashref) = @_;
173 my $dbh = C4::Context->dbh;
179 foreach my $filter ( keys %$filters_hashref ) {
180 $filters_hashref->{$filter} =~ s/\*/%/;
181 if ( $filter =~ /date/ ) {
182 $filters_hashref->{$filter} =
183 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
193 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
194 : $filters_hashref->{$_}
197 } sort keys %$filters_hashref;
202 my $linesql=changeifreservestatus($linefield);
203 my $colsql=changeifreservestatus($colfield);
204 #Initialization of cell values.....
206 # preparing calculation
207 my $strcalc = "(SELECT $linesql line, $colsql col, ";
208 $strcalc .= ($process == 1) ? " COUNT(*) calculation" :
209 ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation" :
210 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation" :
211 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation" : '*';
213 FROM (select * from reserves union select * from old_reserves) reserves
214 LEFT JOIN borrowers USING (borrowernumber)
216 $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
217 if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
218 $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
219 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
225 ($debug) and print STDERR Dump($filters_hashref);
226 foreach my $filter (keys %$filters_hashref){
228 my $stringfield=$filter;
229 $stringfield=~s/\_[a-z_]+$//;
231 $string=$stringfield;
233 elsif ($filter=~/_or/){
234 push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
235 push @sqlorparams, $$filters_hashref{$filter};
237 elsif ($filter=~/_endex$/){
238 $string = " $stringfield < ? ";
240 elsif ($filter=~/_end$/){
241 $string = " $stringfield <= ? ";
243 elsif ($filter=~/_begin$/){
244 $string = " $stringfield >= ? ";
247 $string = " $stringfield LIKE ? ";
250 push @sqlwhere, $string;
251 push @sqlparams, $$filters_hashref{$filter};
255 $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
256 $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
257 $strcalc .= " GROUP BY line, col )";
258 ($debug) and print STDERR $strcalc;
259 my $dbcalc = $dbh->prepare($strcalc);
260 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
261 @sqlparams=(@sqlparams,@sqlorparams);
262 $dbcalc->execute(@sqlparams);
263 my ($emptycol,$emptyrow);
264 my $data = $dbcalc->fetchall_hashref([qw(line col)]);
266 foreach my $row (keys %$data){
267 push @loopline, $row;
268 foreach my $col (keys %{$$data{$row}}){
269 $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
270 $grantotal+=$$data{$row}{$col}{calculation};
274 my $urlbase="do_it=1&".join("&",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
275 foreach my $row (sort @loopline) {
277 #@loopcol ensures the order for columns is common with column titles
278 # and the number matches the number of columns
279 foreach my $col (sort keys %cols_hash) {
280 push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
281 # url_complement=>($urlbase=~/&$/?$urlbase."&":$urlbase)."filter_$linefield=$row&filter_$colfield=$col"
285 'rowtitle_display' => display_value($linefield,$row),
287 'loopcell' => \@loopcell,
288 'totalrow' => $$data{$row}{totalrow}
291 for my $col ( sort keys %cols_hash ) {
293 foreach my $row (@loopline) {
294 $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
295 $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
297 push @loopfooter, {'totalcol' => $total};
298 push @loopcol, {'coltitle' => $col,
299 coltitle_display=>display_value($colfield,$col)};
301 # the header of the table
302 $globalline{loopfilter}=\@loopfilter;
303 # the core of the table
304 $globalline{looprow} = \@looprow;
305 $globalline{loopcol} = \@loopcol;
306 # # the foot (totals by borrower type)
307 $globalline{loopfooter} = \@loopfooter;
308 $globalline{total} = $grantotal;
309 $globalline{line} = $linefield;
310 $globalline{column} = $colfield;
311 return [(\%globalline)];
315 my ( $crit, $value ) = @_;
316 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
317 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
318 my $Bsort1 = GetAuthorisedValues("Bsort1");
319 my $Bsort2 = GetAuthorisedValues("Bsort2");
321 ( $crit =~ /ccode/ ) ? $ccodes->{$value}
322 : ( $crit =~ /location/ ) ? $locations->{$value}
323 : ( $crit =~ /itemtype/ ) ? Koha::ItemTypes->find( $value )->translated_description
324 : ( $crit =~ /branch/ ) ? Koha::Libraries->find($value)->branchname
325 : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
326 : $value; # default fallback
327 if ($crit =~ /sort1/) {
329 ($value eq $_->{authorised_value}) or next;
330 $display_value = $_->{lib} and last;
333 elsif ($crit =~ /sort2/) {
335 ($value eq $_->{authorised_value}) or next;
336 $display_value = $_->{lib} and last;
339 elsif ( $crit =~ /category/ ) {
340 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
341 foreach my $patron_category ( @patron_categories ) {
342 ( $value eq $patron_category->categorycode ) or next;
343 $display_value = $patron_category->description and last;
346 return $display_value;
349 sub reservestatushuman{
362 sub changeifreservestatus{
364 ($val=~/reservestatus/
366 when priority>0 then 1
369 when found='f' then 4
372 when cancellationdate is null then 3