Bug 14788: Move opac-topissues.pl code into C4::Circulation
[koha.git] / reports / bor_issues_top.pl
blobb158b7bb29053d919c1a2a456973730db570f4eb
1 #!/usr/bin/perl
3 # Copyright 2000-2002 Katipo Communications
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 strict;
21 #use warnings; FIXME - Bug 2505
22 use CGI qw ( -utf8 );
23 use C4::Auth;
24 use C4::Output;
25 use C4::Context;
26 use C4::Branch; # GetBranches
27 use C4::Koha;
28 use C4::Circulation;
29 use C4::Members;
30 use C4::Reports;
31 use C4::Debug;
32 use C4::Dates qw(format_date format_date_in_iso);
34 =head1 NAME
36 plugin that shows a stats on borrowers
38 =head1 DESCRIPTION
40 =over 2
42 =cut
44 $debug = 1;
45 $debug and open DEBUG, ">/tmp/bor_issues_top.debug.log";
47 my $input = new CGI;
48 my $fullreportname = "reports/bor_issues_top.tt";
49 my $do_it = $input->param('do_it');
50 my $limit = $input->param("Limit");
51 my $column = $input->param("Criteria");
52 my @filters = $input->param("Filter");
53 foreach ( @filters[0..3] ) {
54 $_ and $_ = format_date_in_iso($_);
56 my $output = $input->param("output");
57 my $basename = $input->param("basename");
58 my ($template, $borrowernumber, $cookie)
59 = get_template_and_user({template_name => $fullreportname,
60 query => $input,
61 type => "intranet",
62 authnotrequired => 0,
63 flagsrequired => {reports => '*'},
64 debug => 1,
65 });
66 our $sep = $input->param("sep");
67 $sep = "\t" if ($sep eq 'tabulation');
68 $template->param(do_it => $do_it,
70 if ($do_it) {
71 # Displaying results
72 my $results = calculate($limit, $column, \@filters);
73 if ($output eq "screen"){
74 # Printing results to screen
75 $template->param(mainloop => $results, limit=>$limit);
76 output_html_with_http_headers $input, $cookie, $template->output;
77 } else {
78 # Printing to a csv file
79 print $input->header(-type => 'application/vnd.sun.xml.calc',
80 -encoding => 'utf-8',
81 -attachment=>"$basename.csv",
82 -filename=>"$basename.csv" );
83 my $cols = @$results[0]->{loopcol};
84 my $lines = @$results[0]->{looprow};
85 # header top-right
86 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
87 # Other header
88 print join($sep, map {$_->{coltitle}} @$cols);
89 print $sep . "Total\n";
90 # Table
91 foreach my $line ( @$lines ) {
92 my $x = $line->{loopcell};
93 print $line->{rowtitle}.$sep;
94 print join($sep, map {$_->{value}} @$x);
95 print $sep,$line->{totalrow};
96 print "\n";
98 # footer
99 print "TOTAL";
100 $cols = @$results[0]->{loopfooter};
101 print join($sep, map {$_->{totalcol}} @$cols);
102 print $sep.@$results[0]->{total};
104 exit;
107 my $dbh = C4::Context->dbh;
108 my @values;
110 # here each element returned by map is a hashref, get it?
111 my @mime = ( map { {type =>$_} } (split /[;:]/, 'CSV') ); # FIXME translation
112 my $delims = GetDelimiterChoices;
113 my $branches = GetBranches;
114 my @branchloop;
115 foreach (sort keys %$branches) {
116 # my $selected = 1 if $thisbranch eq $branch;
117 my %row = ( value => $_,
118 # selected => $selected,
119 branchname => $branches->{$_}->{branchname},
121 push @branchloop, \%row;
124 my $itemtypes = GetItemTypes;
125 my @itemtypeloop;
126 foreach (sort {$itemtypes->{$a}->{description} cmp $itemtypes->{$b}->{description}} keys %$itemtypes) {
127 my %row = (value => $_,
128 description => $itemtypes->{$_}->{description},
130 push @itemtypeloop, \%row;
133 my ($codes,$labels) = GetborCatFromCatType(undef,undef);
134 my @borcatloop;
135 foreach (sort keys %$labels) {
136 my %row =(value => $_,
137 description => $labels->{$_},
139 push @borcatloop, \%row;
142 $template->param(
143 mimeloop => \@mime,
144 CGIseplist => $delims,
145 branchloop => \@branchloop,
146 itemtypeloop => \@itemtypeloop,
147 borcatloop => \@borcatloop,
149 output_html_with_http_headers $input, $cookie, $template->output;
152 sub calculate {
153 my ($limit, $column, $filters) = @_;
155 my @loopcol;
156 my @loopline;
157 my @looprow;
158 my %globalline;
159 my %columns;
160 my $grantotal =0;
161 my $dbh = C4::Context->dbh;
163 # Checking filters
164 my @loopfilter;
165 my @cellmap = (
166 "Issue From",
167 "Issue To",
168 "Return From",
169 "Return To",
170 "Branch",
171 "Doc Type",
172 "Bor Cat",
173 "Day",
174 "Month",
175 "Year"
177 for (my $i=0;$i<=6;$i++) {
178 my %cell;
179 if ( @$filters[$i] ) {
180 if (($i==1) and (@$filters[$i-1])) {
181 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
183 # format the dates filters, otherwise just fill as is
184 $cell{filter} .= @$filters[$i];
185 defined ($cellmap[$i]) and
186 $cell{crit} .= $cellmap[$i];
187 push @loopfilter, \%cell;
190 my $colfield;
191 my $colorder;
192 if ($column){
193 $column = "old_issues." .$column if (($column=~/branchcode/) or ($column=~/timestamp/));
194 $column = "biblioitems.".$column if $column=~/itemtype/;
195 $column = "borrowers." .$column if $column=~/categorycode/;
196 my @colfilter ;
197 if ($column =~ /timestamp/) {
198 $colfilter[0] = @$filters[0];
199 $colfilter[1] = @$filters[1];
200 } elsif ($column =~ /returndate/) {
201 $colfilter[0] = @$filters[2];
202 $colfilter[1] = @$filters[3];
203 } elsif ($column =~ /branchcode/) {
204 $colfilter[0] = @$filters[4];
205 } elsif ($column =~ /itemtype/) {
206 $colfilter[0] = @$filters[5];
207 } elsif ($column =~ /category/) {
208 $colfilter[0] = @$filters[6];
209 } elsif ($column =~ /sort2/ ) {
210 # $colfilter[0] = @$filters[11];
213 # loop cols.
214 if ($column eq "Day") {
215 #Display by day
216 $column = "old_issues.timestamp";
217 $colfield .="dayname($column)";
218 $colorder .="weekday($column)";
219 } elsif ($column eq "Month") {
220 #Display by Month
221 $column = "old_issues.timestamp";
222 $colfield .="monthname($column)";
223 $colorder .="month($column)";
224 } elsif ($column eq "Year") {
225 #Display by Year
226 $column = "old_issues.timestamp";
227 $colfield .="Year($column)";
228 $colorder .= $column;
229 } else {
230 $colfield .= $column;
231 $colorder .= $column;
234 my $strsth2;
235 $strsth2 .= "SELECT DISTINCTROW $colfield
236 FROM `old_issues`
237 LEFT JOIN borrowers ON old_issues.borrowernumber=borrowers.borrowernumber
238 LEFT JOIN items ON old_issues.itemnumber=items.itemnumber
239 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
240 WHERE 1";
241 if (($column=~/timestamp/) or ($column=~/returndate/)){
242 if ($colfilter[1] and $colfilter[0]){
243 $strsth2 .= " AND $column between '$colfilter[0]' AND '$colfilter[1]' " ;
244 } elsif ($colfilter[1]) {
245 $strsth2 .= " AND $column < '$colfilter[1]' " ;
246 } elsif ($colfilter[0]) {
247 $strsth2 .= " AND $column > '$colfilter[0]' " ;
249 } elsif ($colfilter[0]) {
250 $colfilter[0] =~ s/\*/%/g;
251 $strsth2 .= " AND $column LIKE '$colfilter[0]' " ;
253 $strsth2 .=" GROUP BY $colfield";
254 $strsth2 .=" ORDER BY $colorder";
256 $debug and print DEBUG "bor_issues_top (old_issues) SQL: $strsth2\n";
257 my $sth2 = $dbh->prepare($strsth2);
258 $sth2->execute;
259 print DEBUG "rows: ", $sth2->rows, "\n";
260 while (my @row = $sth2->fetchrow) {
261 $columns{($row[0] ||'NULL')}++;
262 push @loopcol, { coltitle => $row[0] || 'NULL' };
265 $strsth2 =~ s/old_issues/issues/g;
266 $debug and print DEBUG "bor_issues_top (issues) SQL: $strsth2\n";
267 $sth2 = $dbh->prepare($strsth2);
268 $sth2->execute;
269 $debug and print DEBUG "rows: ", $sth2->rows, "\n";
270 while (my @row = $sth2->fetchrow) {
271 $columns{($row[0] ||'NULL')}++;
272 push @loopcol, { coltitle => $row[0] || 'NULL' };
274 $debug and print DEBUG "full array: ", Dumper(\%columns), "\n";
275 }else{
276 $columns{''} = 1;
279 my $strcalc ;
281 # Processing average loanperiods
282 $strcalc .= "SELECT CONCAT(borrowers.surname , \",\\t\",borrowers.firstname), COUNT(*) AS RANK, borrowers.borrowernumber AS ID";
283 $strcalc .= " , $colfield " if ($colfield);
284 $strcalc .= " FROM `old_issues`
285 LEFT JOIN borrowers USING(borrowernumber)
286 LEFT JOIN items USING(itemnumber)
287 LEFT JOIN biblioitems USING(biblioitemnumber)
288 WHERE old_issues.borrowernumber IS NOT NULL
290 my @filterterms = (
291 'old_issues.issuedate >',
292 'old_issues.issuedate <',
293 'old_issues.returndate >',
294 'old_issues.returndate <',
295 'old_issues.branchcode like',
296 'biblioitems.itemtype like',
297 'borrowers.categorycode like',
299 foreach ((@$filters)[0..9]) {
300 my $term = shift @filterterms; # go through both arrays in step
301 ($_) or next;
302 s/\*/%/g;
303 $strcalc .= " AND $term '$_' ";
305 $strcalc .= " GROUP BY borrowers.borrowernumber";
306 $strcalc .= ", $colfield" if ($column);
307 $strcalc .= " ORDER BY RANK DESC";
308 $strcalc .= ",$colfield " if ($colfield);
309 $strcalc .= " LIMIT $limit" if ($limit);
311 $debug and print DEBUG "(old_issues) SQL : $strcalc\n";
312 my $dbcalc = $dbh->prepare($strcalc);
313 $dbcalc->execute;
314 $debug and print DEBUG "rows: ", $dbcalc->rows, "\n";
315 my %patrons = ();
316 # DATA STRUCTURE is going to look like this:
317 # (2253=> {name=>"John Doe",
318 # allcols=>{MAIN=>12, MEDIA_LIB=>3}
319 # },
321 while (my @data = $dbcalc->fetchrow) {
322 my ($row, $rank, $id, $col) = @data;
323 $col = "zzEMPTY" if (!defined($col));
324 unless ($patrons{$id}) {
325 $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}};
327 $patrons{$id}->{oldcols}->{$col} = $rank;
330 use Data::Dumper;
332 $strcalc =~ s/old_issues/issues/g;
333 $debug and print DEBUG "(issues) SQL : $strcalc\n";
334 $dbcalc = $dbh->prepare($strcalc);
335 $dbcalc->execute;
336 $debug and print DEBUG "rows: ", $dbcalc->rows, "\n";
337 while (my @data = $dbcalc->fetchrow) {
338 my ($row, $rank, $id, $col) = @data;
339 $col = "zzEMPTY" if (!defined($col));
340 unless ($patrons{$id}) {
341 $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}};
343 $patrons{$id}->{newcols}->{$col} = $rank;
346 foreach my $id (keys %patrons) {
347 my @uniq = keys %{{ %{$patrons{$id}->{newcols}}, %{$patrons{$id}->{oldcols}} }}; # get uniq keys, see perlfaq4
348 foreach (@uniq) {
349 my $count = ($patrons{$id}->{newcols}->{$_} || 0) +
350 ($patrons{$id}->{oldcols}->{$_} || 0);
351 $patrons{$id}->{allcols}->{$_} = $count;
352 $patrons{$id}->{total} += $count;
355 $debug and print DEBUG "\n\npatrons: ", Dumper(\%patrons);
357 my $i = 1;
358 my @cols_in_order = sort keys %columns; # if you want to order the columns, do something here
359 my @ranked_ids = sort {
360 $patrons{$b}->{total} <=> $patrons{$a}->{total}
361 || $patrons{$a}->{name} cmp $patrons{$b}->{name}
362 } keys %patrons;
363 foreach my $id (@ranked_ids) {
364 my @loopcell;
365 foreach my $key (@cols_in_order) {
366 if($column){
367 push @loopcell, {
368 value => $patrons{$id}->{name},
369 reference => $id,
370 count => $patrons{$id}->{allcols}->{$key},
372 }else{
373 push @loopcell, {
374 value => $patrons{$id}->{name},
375 reference => $id,
376 count => $patrons{$id}->{total},
380 push @looprow,{ 'rowtitle' => $i++ ,
381 'loopcell' => \@loopcell,
382 'hilighted' => ($i%2),
386 # the header of the table
387 $globalline{loopfilter}=\@loopfilter;
388 # the core of the table
389 $globalline{looprow} = \@looprow;
390 $globalline{loopcol} = [ map {{coltitle=>$_}} @cols_in_order ];
391 # the foot (totals by borrower type)
392 $globalline{loopfooter} = [];
393 $globalline{total}= $grantotal; # FIXME: useless
394 $globalline{column} = $column;
395 return [\%globalline]; # reference to a 1 element array: that element is a hashref
398 $debug and close DEBUG;
400 __END__