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