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