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