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.
29 use C4::Branch; # GetBranches
35 use List::MoreUtils qw/any/;
40 plugin that shows circulation 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 $podsp = $input->param("DisplayBy");
55 my $type = $input->param("PeriodTypeSel");
56 my $daysel = $input->param("PeriodDaySel");
57 my $monthsel = $input->param("PeriodMonthSel");
58 my $calc = $input->param("Cellvalue");
59 my $output = $input->param("output");
60 my $basename = $input->param("basename");
61 my $mime = $input->param("MIME");
62 my $hash_params = $input->Vars;
64 foreach my $filter (grep {$_ =~/^filter/} keys %$hash_params){
65 my $filterstring=$filter;
66 $filterstring=~s/^filter_//g;
67 $$filter_hashref{$filterstring}=$$hash_params{$filter} if (defined $$hash_params{$filter} && $$hash_params{$filter} ne "");
69 my ($template, $borrowernumber, $cookie) = get_template_and_user({
70 template_name => $fullreportname,
74 flagsrequired => {reports => '*'},
77 our $sep = $input->param("sep") || '';
78 $sep = "\t" if ($sep eq 'tabulation');
79 $template->param(do_it => $do_it,
82 my $itemtypes = GetItemTypes();
83 my $categoryloop = GetBorrowercategoryList;
85 my $ccodes = GetKohaAuthorisedValues("items.ccode");
86 my $locations = GetKohaAuthorisedValues("items.location");
87 my $authvalue = GetKohaAuthorisedValues("items.authvalue");
89 my $Bsort1 = GetAuthorisedValues("Bsort1");
90 my $Bsort2 = GetAuthorisedValues("Bsort2");
91 my ($hassort1,$hassort2);
92 $hassort1=1 if $Bsort1;
93 $hassort2=1 if $Bsort2;
98 my $results = calculate($line, $column, $calc, $filter_hashref);
99 if ($output eq "screen"){
100 # Printing results to screen
101 $template->param(mainloop => $results);
102 output_html_with_http_headers $input, $cookie, $template->output;
104 # Printing to a csv file
105 print $input->header(-type => 'application/vnd.sun.xml.calc',
106 -encoding => 'utf-8',
107 -attachment=>"$basename.csv",
108 -filename=>"$basename.csv" );
109 my $cols = @$results[0]->{loopcol};
110 my $lines = @$results[0]->{looprow};
112 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
114 foreach my $col ( @$cols ) {
115 print $col->{coltitle}.$sep;
119 foreach my $line ( @$lines ) {
120 my $x = $line->{loopcell};
121 print $line->{rowtitle}.$sep;
122 print map {$_->{value}.$sep} @$x;
123 print $line->{totalrow}, "\n";
127 $cols = @$results[0]->{loopfooter};
128 print map {$sep.$_->{totalcol}} @$cols;
129 print $sep.@$results[0]->{total};
131 exit; # exit either way after $do_it
134 my $dbh = C4::Context->dbh;
139 # create itemtype arrayref for <select>.
141 for my $itype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description}} keys(%$itemtypes)) {
142 push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{translated_description} } ;
147 foreach (sort keys %$locations) {
148 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
152 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
153 push @ccodes, { code => $_, description => $ccodes->{$_} };
157 my $CGIextChoice = ( 'CSV' ); # FIXME translation
158 my $CGIsepChoice=GetDelimiterChoices;
161 categoryloop => $categoryloop,
162 itemtypeloop => \@itemtypeloop,
163 locationloop => \@locations,
164 ccodeloop => \@ccodes,
165 branchloop => GetBranchesLoop(C4::Context->userenv->{'branch'}),
166 hassort1=> $hassort1,
167 hassort2=> $hassort2,
170 CGIextChoice => $CGIextChoice,
171 CGIsepChoice => $CGIsepChoice,
173 output_html_with_http_headers $input, $cookie, $template->output;
176 my ($linefield, $colfield, $process, $filters_hashref) = @_;
184 my $dbh = C4::Context->dbh;
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' }); };
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" : '*';
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);
236 ($debug) and print STDERR Dump($filters_hashref);
237 foreach my $filter (keys %$filters_hashref){
239 my $stringfield=$filter;
240 $stringfield=~s/\_[a-z_]+$//;
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 >= ? ";
258 $string = " $stringfield LIKE ? ";
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 my $strcalc_old=$strcalc;
270 $strcalc_old=~s/reserves/old_reserves/g;
271 $strcalc.=qq{ UNION $strcalc_old ORDER BY line, col};
272 ($debug) and print STDERR $strcalc;
273 my $dbcalc = $dbh->prepare($strcalc);
274 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
275 @sqlparams=(@sqlparams,@sqlorparams);
276 $dbcalc->execute(@sqlparams,@sqlparams);
277 my ($emptycol,$emptyrow);
278 my $data = $dbcalc->fetchall_hashref([qw(line col)]);
280 foreach my $row (keys %$data){
281 push @loopline, $row;
282 foreach my $col (keys %{$$data{$row}}){
283 $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
284 $grantotal+=$$data{$row}{$col}{calculation};
288 my $urlbase="do_it=1&".join("&",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
289 foreach my $row (sort @loopline) {
291 #@loopcol ensures the order for columns is common with column titles
292 # and the number matches the number of columns
293 foreach my $col (sort keys %cols_hash) {
294 push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
295 # url_complement=>($urlbase=~/&$/?$urlbase."&":$urlbase)."filter_$linefield=$row&filter_$colfield=$col"
299 'rowtitle_display' => display_value($linefield,$row),
301 'loopcell' => \@loopcell,
302 'totalrow' => $$data{$row}{totalrow}
305 for my $col ( sort keys %cols_hash ) {
307 foreach my $row (@loopline) {
308 $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
309 $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
311 push @loopfooter, {'totalcol' => $total};
312 push @loopcol, {'coltitle' => $col,
313 coltitle_display=>display_value($colfield,$col)};
315 # the header of the table
316 $globalline{loopfilter}=\@loopfilter;
317 # the core of the table
318 $globalline{looprow} = \@looprow;
319 $globalline{loopcol} = \@loopcol;
320 # # the foot (totals by borrower type)
321 $globalline{loopfooter} = \@loopfooter;
322 $globalline{total} = $grantotal;
323 $globalline{line} = $linefield;
324 $globalline{column} = $colfield;
325 return [(\%globalline)];
328 sub null_to_zzempty ($) {
330 defined($string) or return 'zzEMPTY';
331 ($string eq "NULL") and return 'zzEMPTY';
332 return $string; # else return the valid value
335 my ( $crit, $value ) = @_;
337 ( $crit =~ /ccode/ ) ? $ccodes->{$value}
338 : ( $crit =~ /location/ ) ? $locations->{$value}
339 : ( $crit =~ /itemtype/ ) ? $itemtypes->{$value}->{description}
340 : ( $crit =~ /branch/ ) ? GetBranchName($value)
341 : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
342 : $value; # default fallback
343 if ($crit =~ /sort1/) {
345 ($value eq $_->{authorised_value}) or next;
346 $display_value = $_->{lib} and last;
349 elsif ($crit =~ /sort2/) {
351 ($value eq $_->{authorised_value}) or next;
352 $display_value = $_->{lib} and last;
355 elsif ( $crit =~ /category/ ) {
356 foreach (@$categoryloop) {
357 ( $value eq $_->{categorycode} ) or next;
358 $display_value = $_->{description} and last;
361 return $display_value;
363 sub reservestatushuman{
375 sub changeifreservestatus{
377 ($val=~/reservestatus/
379 when priority>0 then 1
382 when found='f' then 4
385 when cancellationdate is null then 3