Bug 6078: Request to find borrowers without issues overload the server
[koha.git] / reports / borrowers_out.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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 use warnings;
22
23 use CGI;
24 use C4::Auth;
25 use C4::Context;
26 use C4::Koha;
27 use C4::Output;
28 use C4::Circulation;
29 use C4::Reports;
30 use C4::Members;
31 use C4::Dates qw/format_date_in_iso/;
32
33 =head1 NAME
34
35 plugin that shows a stats on borrowers
36
37 =head1 DESCRIPTION
38
39 =over 2
40
41 =cut
42
43 my $input = new CGI;
44 my $do_it=$input->param('do_it');
45 my $fullreportname = "reports/borrowers_out.tmpl";
46 my $limit = $input->param("Limit");
47 my $column = $input->param("Criteria");
48 my @filters = $input->param("Filter");
49 $filters[1] = format_date_in_iso($filters[1]) if $filters[1];
50 my $output = $input->param("output");
51 my $basename = $input->param("basename");
52 our $sep     = $input->param("sep") || '';
53 $sep = "\t" if ($sep eq 'tabulation');
54 my ($template, $borrowernumber, $cookie)
55     = get_template_and_user({template_name => $fullreportname,
56                 query => $input,
57                 type => "intranet",
58                 authnotrequired => 0,
59                 flagsrequired => {reports => '*'},
60                 debug => 1,
61                 });
62 $template->param(do_it => $do_it,
63         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
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);
71         output_html_with_http_headers $input, $cookie, $template->output;
72         exit(1);
73     } else {
74 # Printing to a csv file
75         print $input->header(-type => 'application/vnd.sun.xml.calc',
76                             -encoding    => 'utf-8',
77                             -attachment=>"$basename.csv",
78                             -filename=>"$basename.csv" );
79         my $cols = @$results[0]->{loopcol};
80         my $lines = @$results[0]->{looprow};
81 # header top-right
82         print "num /". @$results[0]->{column} .$sep;
83 # Other header
84         foreach my $col ( @$cols ) {
85             print $col->{coltitle}.$sep;
86         }
87         print "Total\n";
88 # Table
89         foreach my $line ( @$lines ) {
90             my $x = $line->{loopcell};
91             print $line->{rowtitle}.$sep;
92             foreach my $cell (@$x) {
93                 my $cellvalue = defined $cell->{value} ? $cell->{value}.$sep : ''.$sep;
94                 print $cellvalue;
95             }
96 #            print $line->{totalrow};
97             print "\n";
98         }
99 # footer
100         print "TOTAL";
101         $cols = @$results[0]->{loopfooter};
102         foreach my $col ( @$cols ) {
103             print $sep.$col->{totalcol};
104         }
105         print $sep.@$results[0]->{total};
106         exit(1);
107     }
108 # Displaying choices
109 } else {
110     my $dbh = C4::Context->dbh;
111     my @values;
112     my %labels;
113     my %select;
114     my $req;
115     
116     my $CGIextChoice=CGI::scrolling_list(
117                 -name     => 'MIME',
118                 -id       => 'MIME',
119                 -values   => ['CSV'], # FIXME translation
120                 -size     => 1,
121                 -multiple => 0 );
122     
123         my $CGIsepChoice = GetDelimiterChoices;
124     
125     my ($codes,$labels) = GetborCatFromCatType(undef,undef);
126     my @borcatloop;
127     foreach my $thisborcat (sort keys %$labels) {
128             my %row =(value => $thisborcat,
129                                     description => $labels->{$thisborcat},
130                             );
131             push @borcatloop, \%row;
132     }
133     $template->param(
134                     CGIextChoice => $CGIextChoice,
135                     CGIsepChoice => $CGIsepChoice,
136                     borcatloop =>\@borcatloop,
137                     );
138 output_html_with_http_headers $input, $cookie, $template->output;
139 }
140
141
142 sub calculate {
143     my ($line, $column, $filters) = @_;
144     my @mainloop;
145     my @loopfooter;
146     my @loopcol;
147     my @loopline;
148     my @looprow;
149     my %globalline;
150     my $grantotal =0;
151 # extract parameters
152     my $dbh = C4::Context->dbh;
153
154 # Filters
155 # Checking filters
156 #
157     my @loopfilter;
158     for (my $i=0;$i<=2;$i++) {
159         my %cell;
160         if ( @$filters[$i] ) {
161             if (($i==1) and (@$filters[$i-1])) {
162                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
163             }
164             $cell{filter} .= @$filters[$i];
165             $cell{crit} .="Bor Cat" if ($i==0);
166             $cell{crit} .="Without issues since" if ($i==1);
167             push @loopfilter, \%cell;
168         }
169     }
170     my $colfield;
171     my $colorder;
172     if ($column){
173         $column = "borrowers.".$column if $column=~/categorycode/ || $column=~/branchcode/;
174         my @colfilter ;
175         $colfilter[0] = @$filters[0] if ($column =~ /category/ )  ;
176     #   $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
177     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
178                                                 
179     # loop cols.
180         $colfield .= $column;
181         $colorder .= $column;
182         
183         my $strsth2;
184         $strsth2 .= "select distinct $colfield FROM borrowers WHERE 1";
185         if ($colfilter[0]) {
186             $colfilter[0] =~ s/\*/%/g;
187             $strsth2 .= " and $column LIKE '$colfilter[0]' " ;
188         }
189         $strsth2 .=" group by $colfield";
190         $strsth2 .=" order by $colorder";
191         # warn "". $strsth2;
192         
193         my $sth2 = $dbh->prepare( $strsth2 );
194         $sth2->execute;
195         while (my ($celvalue) = $sth2->fetchrow) {
196             my %cell;
197     #           my %ft;
198     #           warn "coltitle :".$celvalue;
199             $cell{coltitle} = $celvalue;
200     #           $ft{totalcol} = 0;
201             push @loopcol, \%cell;
202         }
203     #   warn "fin des titres colonnes";
204     }
205     
206     my $i=0;
207 #       my @totalcol;
208     
209     #Initialization of cell values.....
210     my @table;
211     
212 #       warn "init table";
213     if($line) {
214         for (my $i=1;$i<=$line;$i++) {
215             foreach my $col ( @loopcol ) {
216                 $table[$i]->{($col->{coltitle})?$col->{coltitle}:"Global"}=0;
217             }
218         }
219     }
220
221
222 # preparing calculation
223     my $strcalc ;
224     
225 # Processing calculation
226     $strcalc .= "SELECT CONCAT( borrowers.surname , \"\\t\",borrowers.firstname, \"\\t\", borrowers.cardnumber)";
227     $strcalc .= " , $colfield " if ($colfield);
228     $strcalc .= " FROM borrowers ";
229     $strcalc .= "WHERE 1 ";
230     @$filters[0]=~ s/\*/%/g if (@$filters[0]);
231     $strcalc .= " AND borrowers.categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
232
233     $strcalc .= " AND NOT EXISTS (SELECT * FROM issues WHERE issues.borrowernumber=borrowers.borrowernumber ";
234     $strcalc .= " AND issues.timestamp> '" . @$filters[1] . "'" if (@$filters[1]);
235     $strcalc .= ") ";
236     $strcalc .= " AND NOT EXISTS (SELECT * FROM old_issues WHERE old_issues.borrowernumber=borrowers.borrowernumber ";
237     $strcalc .= " AND old_issues.timestamp> '" . @$filters[1] . "'" if (@$filters[1]);
238     $strcalc .= ") ";
239     $strcalc .= " group by borrowers.borrowernumber";
240     $strcalc .= ", $colfield" if ($column);
241     $strcalc .= " order by $colfield " if ($colfield);
242     my $max;
243     if ($line) {
244         if (@loopcol) {
245             $max = $line*@loopcol;
246         } else { $max=$line;}
247         $strcalc .= " LIMIT 0,$max";
248      } 
249     
250     my $dbcalc = $dbh->prepare($strcalc);
251     $dbcalc->execute;
252 #       warn "filling table";
253     my $previous_col;
254     $i=1;
255     while (my  @data = $dbcalc->fetchrow) {
256         my ($row, $col )=@data;
257         $col = "zzEMPTY" if (!defined($col));
258         $i=1 if (($previous_col) and not($col eq $previous_col));
259         $table[$i]->{$col}=$row;
260 #               warn " $i $col $row";
261         $i++;
262         $previous_col=$col;
263     }
264     
265     push @loopcol,{coltitle => "Global"} if not($column);
266     
267     $max =(($line)?$line:@table -1);
268     for ($i=1; $i<=$max;$i++) {
269         my @loopcell;
270         #@loopcol ensures the order for columns is common with column titles
271         # and the number matches the number of columns
272         my $colcount=0;
273         foreach my $col ( @loopcol ) {
274             my $value;
275             if (@loopcol){
276                 $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}};
277             } else {
278                 $value =$table[$i]->{"zzEMPTY"};
279             }
280             push @loopcell, {value => $value} ;
281         }
282         push @looprow,{ 'rowtitle' => $i ,
283                         'loopcell' => \@loopcell,
284                     };
285     }
286     
287             
288
289     # the header of the table
290     $globalline{loopfilter}=\@loopfilter;
291     # the core of the table
292     $globalline{looprow} = \@looprow;
293     $globalline{loopcol} = \@loopcol;
294 #       # the foot (totals by borrower type)
295     $globalline{loopfooter} = \@loopfooter;
296     $globalline{total}= $grantotal;
297     $globalline{line} = $line;
298     $globalline{column} = $column;
299     push @mainloop,\%globalline;
300     return \@mainloop;
301 }
302
303 1;
304 __END__