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