Bug 21468: Add 'checkout' action for _after_circ_actions
[koha.git] / reports / bor_issues_top.pl
blob63bdd6db1f001dc00d77ebbcd815ce5c49f8b4df
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 Modern::Perl;
22 use CGI qw ( -utf8 );
23 use C4::Auth;
24 use C4::Output;
25 use C4::Context;
26 use C4::Koha;
27 use C4::Circulation;
28 use C4::Members;
29 use C4::Reports;
30 use C4::Debug;
32 use Koha::DateUtils;
33 use Koha::ItemTypes;
34 use Koha::Patron::Categories;
36 =head1 NAME
38 plugin that shows a stats on borrowers
40 =head1 DESCRIPTION
42 =cut
44 $debug and open my $debugfh, '>', '/tmp/bor_issues_top.debug.log';
46 my $input = new CGI;
47 my $fullreportname = "reports/bor_issues_top.tt";
48 my $do_it = $input->param('do_it');
49 my $limit = $input->param("Limit");
50 my $column = $input->param("Criteria");
51 my @filters = $input->multi_param("Filter");
52 foreach ( @filters[0..3] ) {
53 $_ and $_ = eval { output_pref( { dt => dt_from_string ( $_ ), dateonly => 1, dateformat => 'iso' }); };
55 my $output = $input->param("output");
56 my $basename = $input->param("basename");
57 my ($template, $borrowernumber, $cookie)
58 = get_template_and_user({template_name => $fullreportname,
59 query => $input,
60 type => "intranet",
61 authnotrequired => 0,
62 flagsrequired => {reports => '*'},
63 debug => 1,
64 });
65 our $sep = $input->param("sep") || C4::Context->preference('delimiter') || ',';
66 $sep = "\t" if ($sep eq 'tabulation');
67 $template->param(do_it => $do_it,
69 if ($do_it) {
70 # Displaying results
71 my $results = calculate($limit, $column, \@filters);
72 if ($output eq "screen"){
73 # Printing results to screen
74 $template->param(mainloop => $results, limit=>$limit);
75 output_html_with_http_headers $input, $cookie, $template->output;
76 } else {
77 # Printing to a csv file
78 print $input->header(-type => 'application/vnd.sun.xml.calc',
79 -encoding => 'utf-8',
80 -attachment=>"$basename.csv",
81 -filename=>"$basename.csv" );
82 my $cols = @$results[0]->{loopcol};
83 my $lines = @$results[0]->{looprow};
84 # header top-right
85 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
86 # Other header
87 print join($sep, map {$_->{coltitle}} @$cols);
88 print $sep . "Total\n";
89 # Table
90 foreach my $line ( @$lines ) {
91 my $x = $line->{loopcell};
92 print $line->{rowtitle}.$sep;
93 print join($sep, map {$_->{value}} @$x);
94 print $sep,$line->{totalrow};
95 print "\n";
97 # footer
98 print "TOTAL";
99 $cols = @$results[0]->{loopfooter};
100 print join($sep, map {$_->{totalcol}} @$cols);
101 print $sep.@$results[0]->{total};
103 exit;
106 my $dbh = C4::Context->dbh;
108 # here each element returned by map is a hashref, get it?
109 my @mime = ( map { {type =>$_} } (split /[;:]/, 'CSV') ); # FIXME translation
110 my $delims = GetDelimiterChoices;
112 my $patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['categorycode']});
113 my $itemtypes = Koha::ItemTypes->search_with_localization;
114 $template->param(
115 mimeloop => \@mime,
116 CGIseplist => $delims,
117 itemtypes => $itemtypes,
118 patron_categories => $patron_categories,
120 output_html_with_http_headers $input, $cookie, $template->output;
123 sub calculate {
124 my ($limit, $column, $filters) = @_;
126 my @loopcol;
127 my @looprow;
128 my %globalline;
129 my %columns;
130 my $grantotal =0;
131 my $dbh = C4::Context->dbh;
134 # Checking filters
135 my @loopfilter;
136 my @cellmap = (
137 "Issue From",
138 "Issue To",
139 "Return From",
140 "Return To",
141 "Branch",
142 "Doc Type",
143 "Bor Cat",
144 "Day",
145 "Month",
146 "Year"
148 for (my $i=0;$i<=6;$i++) {
149 my %cell;
150 if ( @$filters[$i] ) {
151 if (($i==1) and (@$filters[$i-1])) {
152 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
154 # format the dates filters, otherwise just fill as is
155 $cell{filter} .= @$filters[$i];
156 defined ($cellmap[$i]) and
157 $cell{crit} .= $cellmap[$i];
158 push @loopfilter, \%cell;
161 my $colfield;
162 my $colorder;
163 if ($column){
164 $column = "old_issues." .$column if (($column=~/branchcode/) or ($column=~/timestamp/));
165 $column = "biblioitems.".$column if $column=~/itemtype/;
166 $column = "borrowers." .$column if $column=~/categorycode/;
167 my @colfilter ;
168 if ($column =~ /timestamp/) {
169 $colfilter[0] = @$filters[0];
170 $colfilter[1] = @$filters[1];
171 } elsif ($column =~ /returndate/) {
172 $colfilter[0] = @$filters[2];
173 $colfilter[1] = @$filters[3];
174 } elsif ($column =~ /branchcode/) {
175 $colfilter[0] = @$filters[4];
176 } elsif ($column =~ /itemtype/) {
177 $colfilter[0] = @$filters[5];
178 } elsif ($column =~ /category/) {
179 $colfilter[0] = @$filters[6];
180 } elsif ($column =~ /sort2/ ) {
181 # $colfilter[0] = @$filters[11];
184 # loop cols.
185 if ($column eq "Day") {
186 #Display by day
187 $column = "old_issues.timestamp";
188 $colfield .="dayname($column)";
189 $colorder .="weekday($column)";
190 } elsif ($column eq "Month") {
191 #Display by Month
192 $column = "old_issues.timestamp";
193 $colfield .="monthname($column)";
194 $colorder .="month($column)";
195 } elsif ($column eq "Year") {
196 #Display by Year
197 $column = "old_issues.timestamp";
198 $colfield .="Year($column)";
199 $colorder .= $column;
200 } else {
201 $colfield .= $column;
202 $colorder .= $column;
205 my $strsth2;
206 $strsth2 .= "SELECT DISTINCTROW $colfield
207 FROM `old_issues`
208 LEFT JOIN borrowers ON old_issues.borrowernumber=borrowers.borrowernumber
209 LEFT JOIN items ON old_issues.itemnumber=items.itemnumber
210 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
211 WHERE 1";
212 if (($column=~/timestamp/) or ($column=~/returndate/)){
213 if ($colfilter[1] and $colfilter[0]){
214 $strsth2 .= " AND $column between '$colfilter[0]' AND '$colfilter[1]' " ;
215 } elsif ($colfilter[1]) {
216 $strsth2 .= " AND $column < '$colfilter[1]' " ;
217 } elsif ($colfilter[0]) {
218 $strsth2 .= " AND $column > '$colfilter[0]' " ;
220 } elsif ($colfilter[0]) {
221 $colfilter[0] =~ s/\*/%/g;
222 $strsth2 .= " AND $column LIKE '$colfilter[0]' " ;
224 $strsth2 .=" GROUP BY $colfield";
225 $strsth2 .=" ORDER BY $colorder";
227 $debug and print $debugfh "bor_issues_top (old_issues) SQL: $strsth2\n";
228 my $sth2 = $dbh->prepare($strsth2);
229 $sth2->execute;
230 print $debugfh "rows: ", $sth2->rows, "\n";
231 while (my @row = $sth2->fetchrow) {
232 $columns{($row[0] ||'NULL')}++;
233 push @loopcol, { coltitle => $row[0] || 'NULL' };
236 $strsth2 =~ s/old_issues/issues/g;
237 $debug and print $debugfh "bor_issues_top (issues) SQL: $strsth2\n";
238 $sth2 = $dbh->prepare($strsth2);
239 $sth2->execute;
240 $debug and print $debugfh "rows: ", $sth2->rows, "\n";
241 while (my @row = $sth2->fetchrow) {
242 $columns{($row[0] ||'NULL')}++;
243 push @loopcol, { coltitle => $row[0] || 'NULL' };
245 $debug and print $debugfh "full array: ", Dumper(\%columns), "\n";
246 }else{
247 $columns{''} = 1;
250 my $strcalc ;
252 # Processing average loanperiods
253 $strcalc .= "SELECT CONCAT_WS('', borrowers.surname , \",\\t\", borrowers.firstname), COUNT(*) AS RANK, borrowers.borrowernumber AS ID";
254 $strcalc .= " , $colfield " if ($colfield);
255 $strcalc .= " FROM `old_issues`
256 LEFT JOIN borrowers USING(borrowernumber)
257 LEFT JOIN items USING(itemnumber)
258 LEFT JOIN biblioitems USING(biblioitemnumber)
259 WHERE old_issues.borrowernumber IS NOT NULL
261 my @filterterms = (
262 'old_issues.issuedate >',
263 'old_issues.issuedate <',
264 'old_issues.returndate >',
265 'old_issues.returndate <',
266 'old_issues.branchcode like',
267 'biblioitems.itemtype like',
268 'borrowers.categorycode like',
270 foreach ((@$filters)[0..9]) {
271 my $term = shift @filterterms; # go through both arrays in step
272 ($_) or next;
273 s/\*/%/g;
274 $strcalc .= " AND $term '$_' ";
276 $strcalc .= " GROUP BY borrowers.borrowernumber";
277 $strcalc .= ", $colfield" if ($column);
278 $strcalc .= " ORDER BY RANK DESC";
279 $strcalc .= ",$colfield " if ($colfield);
280 $strcalc .= " LIMIT $limit" if ($limit);
282 $debug and print $debugfh "(old_issues) SQL : $strcalc\n";
283 my $dbcalc = $dbh->prepare($strcalc);
284 $dbcalc->execute;
285 $debug and print $debugfh "rows: ", $dbcalc->rows, "\n";
286 my %patrons = ();
287 # DATA STRUCTURE is going to look like this:
288 # (2253=> {name=>"John Doe",
289 # allcols=>{MAIN=>12, MEDIA_LIB=>3}
290 # },
292 while (my @data = $dbcalc->fetchrow) {
293 my ($row, $rank, $id, $col) = @data;
294 $col = "zzEMPTY" if (!defined($col));
295 unless ($patrons{$id}) {
296 $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}};
298 $patrons{$id}->{oldcols}->{$col} = $rank;
301 use Data::Dumper;
303 $strcalc =~ s/old_issues/issues/g;
304 $debug and print $debugfh "(issues) SQL : $strcalc\n";
305 $dbcalc = $dbh->prepare($strcalc);
306 $dbcalc->execute;
307 $debug and print $debugfh "rows: ", $dbcalc->rows, "\n";
308 while (my @data = $dbcalc->fetchrow) {
309 my ($row, $rank, $id, $col) = @data;
310 $col = "zzEMPTY" if (!defined($col));
311 unless ($patrons{$id}) {
312 $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}};
314 $patrons{$id}->{newcols}->{$col} = $rank;
317 foreach my $id (keys %patrons) {
318 my @uniq = keys %{{ %{$patrons{$id}->{newcols}}, %{$patrons{$id}->{oldcols}} }}; # get uniq keys, see perlfaq4
319 foreach (@uniq) {
320 my $count = ($patrons{$id}->{newcols}->{$_} || 0) +
321 ($patrons{$id}->{oldcols}->{$_} || 0);
322 $patrons{$id}->{allcols}->{$_} = $count;
323 $patrons{$id}->{total} += $count;
326 $debug and print $debugfh "\n\npatrons: ", Dumper(\%patrons);
328 my $i = 1;
329 my @cols_in_order = sort keys %columns; # if you want to order the columns, do something here
330 my @ranked_ids = sort {
331 $patrons{$b}->{total} <=> $patrons{$a}->{total}
332 || $patrons{$a}->{name} cmp $patrons{$b}->{name}
333 } keys %patrons;
334 foreach my $id (@ranked_ids) {
335 my @loopcell;
337 foreach my $key (@cols_in_order) {
338 if($column){
339 push @loopcell, {
340 value => $patrons{$id}->{name},
341 reference => $id,
342 count => $patrons{$id}->{allcols}->{$key},
344 }else{
345 push @loopcell, {
346 value => $patrons{$id}->{name},
347 reference => $id,
348 count => $patrons{$id}->{total},
352 push @looprow,{ 'rowtitle' => $i++ ,
353 'loopcell' => \@loopcell,
354 'hilighted' => ($i%2),
356 # use a limit, if a limit is defined
357 last if $i > $limit and $limit
360 # the header of the table
361 $globalline{loopfilter}=\@loopfilter;
362 # the core of the table
363 $globalline{looprow} = \@looprow;
364 $globalline{loopcol} = [ map {{coltitle=>$_}} @cols_in_order ];
365 # the foot (totals by borrower type)
366 $globalline{loopfooter} = [];
367 $globalline{total}= $grantotal; # FIXME: useless
368 $globalline{column} = $column;
369 return [\%globalline]; # reference to a 1 element array: that element is a hashref
372 $debug and close $debugfh;
374 __END__