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