Bug 29723: Add a "Configure table" button for KohaTable tables
[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
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::Context;
25 use C4::Output qw( output_html_with_http_headers );
26 use C4::Reports qw( GetDelimiterChoices );
27
28 use Koha::DateUtils qw( dt_from_string output_pref );
29 use Koha::Patron::Categories;
30
31 =head1 NAME
32
33 reports/borrowers_out.pl
34
35 =head1 DESCRIPTION
36
37 Plugin that shows a stats on borrowers
38
39 =cut
40
41 my $input = CGI->new;
42 my $do_it=$input->param('do_it');
43 my $fullreportname = "reports/borrowers_out.tt";
44 my $limit = $input->param("Limit");
45 my $column = $input->param("Criteria");
46 my @filters = $input->multi_param("Filter");
47 $filters[1] = eval { output_pref( { dt => dt_from_string( $filters[1]), dateonly => 1, dateformat => 'iso' } ); }
48     if ( $filters[1] );
49
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                 flagsrequired => {reports => '*'},
59                 });
60 $template->param(do_it => $do_it,
61         );
62 if ($do_it) {
63 # Displaying results
64     my $results = calculate($limit, $column, \@filters);
65     if ($output eq "screen"){
66 # Printing results to screen
67         $template->param(mainloop => $results);
68         output_html_with_http_headers $input, $cookie, $template->output;
69         exit;
70     } else {
71 # Printing to a csv file
72         print $input->header(-type => 'application/vnd.sun.xml.calc',
73                             -encoding    => 'utf-8',
74                             -attachment=>"$basename.csv",
75                             -filename=>"$basename.csv" );
76         my $cols = @$results[0]->{loopcol};
77         my $lines = @$results[0]->{looprow};
78 # header top-right
79         print "num /". @$results[0]->{column} .$sep;
80 # Other header
81         foreach my $col ( @$cols ) {
82             print $col->{coltitle}.$sep;
83         }
84         print "Total\n";
85 # Table
86         foreach my $line ( @$lines ) {
87             my $x = $line->{loopcell};
88             print $line->{rowtitle}.$sep;
89             foreach my $cell (@$x) {
90                 my $cellvalue = defined $cell->{value} ? $cell->{value}.$sep : ''.$sep;
91                 print $cellvalue;
92             }
93 #            print $line->{totalrow};
94             print "\n";
95         }
96 # footer
97         print "TOTAL";
98         $cols = @$results[0]->{loopfooter};
99         foreach my $col ( @$cols ) {
100             print $sep.$col->{totalcol};
101         }
102         print $sep.@$results[0]->{total};
103         exit;
104     }
105 # Displaying choices
106 } else {
107     my $dbh = C4::Context->dbh;
108
109     my $CGIextChoice = ( 'CSV' ); # FIXME translation
110         my $CGIsepChoice = GetDelimiterChoices;
111
112     my $patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['categorycode']});
113     $template->param(
114                     CGIextChoice => $CGIextChoice,
115                     CGIsepChoice => $CGIsepChoice,
116                     patron_categories => $patron_categories,
117                     );
118 output_html_with_http_headers $input, $cookie, $template->output;
119 }
120
121
122 sub calculate {
123     my ($line, $column, $filters) = @_;
124     my @mainloop;
125     my @loopfooter;
126     my @loopcol;
127     my @looprow;
128     my %globalline;
129     my $grantotal =0;
130 # extract parameters
131     my $dbh = C4::Context->dbh;
132
133 # Filters
134 # Checking filters
135 #
136     my @loopfilter;
137     for (my $i=0;$i<=2;$i++) {
138         my %cell;
139         if ( @$filters[$i] ) {
140             if (($i==1) and (@$filters[$i-1])) {
141                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
142             }
143             $cell{filter} .= @$filters[$i];
144             $cell{crit} .="Bor Cat" if ($i==0);
145             $cell{crit} .="Without issues since" if ($i==1);
146             push @loopfilter, \%cell;
147         }
148     }
149     my $colfield;
150     my $colorder;
151     if ($column){
152         $column = "borrowers.".$column if $column=~/categorycode/ || $column=~/branchcode/;
153         my @colfilter ;
154         $colfilter[0] = @$filters[0] if ($column =~ /category/ )  ;
155     #   $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
156     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
157                                                 
158     # loop cols.
159         $colfield .= $column;
160         $colorder .= $column;
161         
162         my $strsth2;
163         $strsth2 .= "select distinct " . $dbh->quote($colfield) . " FROM borrowers WHERE 1";
164         my @query_args;
165         if ( $colfilter[0] ) {
166             $colfilter[0] =~ s/\*/%/g;
167             $strsth2 .= " and " . $dbh->quote($column) . "LIKE ?" ;
168             push @query_args, $colfilter[0];
169         }
170         $strsth2 .=" group by " . $dbh->quote($colfield);
171         $strsth2 .=" order by " . $dbh->quote($colorder);
172         # warn "". $strsth2;
173         
174         my $sth2 = $dbh->prepare( $strsth2 );
175         $sth2->execute( @query_args );
176         while (my ($celvalue) = $sth2->fetchrow) {
177             my %cell;
178     #           my %ft;
179     #           warn "coltitle :".$celvalue;
180             $cell{coltitle} = $celvalue;
181     #           $ft{totalcol} = 0;
182             push @loopcol, \%cell;
183         }
184     #   warn "fin des titres colonnes";
185     }
186     
187     my $i=0;
188 #       my @totalcol;
189     
190     #Initialization of cell values.....
191     my @table;
192     
193 #       warn "init table";
194     if($line) {
195         for (my $i=1;$i<=$line;$i++) {
196             foreach my $col ( @loopcol ) {
197                 $table[$i]->{($col->{coltitle})?$col->{coltitle}:"Global"}=0;
198             }
199         }
200     }
201
202
203 # preparing calculation
204     my $strcalc ;
205     
206 # Processing calculation
207     $strcalc .= "SELECT CONCAT( borrowers.surname , \"\\t\",borrowers.firstname, \"\\t\", borrowers.cardnumber)";
208     $strcalc .= " , " . $dbh->quote($colfield) if ($colfield);
209     $strcalc .= " FROM borrowers ";
210     $strcalc .= "WHERE 1 ";
211     my @query_args;
212     if ( @$filters[0] ) {
213         @$filters[0]=~ s/\*/%/g;
214         $strcalc .= " AND borrowers.categorycode like ?";
215         push @query_args, @$filters[0];
216     }
217     $strcalc .= " AND NOT EXISTS (SELECT * FROM issues WHERE issues.borrowernumber=borrowers.borrowernumber ";
218     if ( @$filters[1] ) {
219         $strcalc .= " AND issues.timestamp > ?";
220         push @query_args, @$filters[1];
221     }
222     $strcalc .= ") ";
223     $strcalc .= " AND NOT EXISTS (SELECT * FROM old_issues WHERE old_issues.borrowernumber=borrowers.borrowernumber ";
224     if ( @$filters[1] ) {
225         $strcalc .= " AND old_issues.timestamp > ?";
226         push @query_args, @$filters[1];
227     }
228     $strcalc .= ") ";
229     $strcalc .= " group by borrowers.borrowernumber";
230     $strcalc .= ", " . $dbh->quote($colfield) if ($column);
231     $strcalc .= " order by " . $dbh->quote($colfield) if ($colfield);
232     my $max;
233     if ($line) {
234         if (@loopcol) {
235             $max = $line*@loopcol;
236         } else { $max=$line;}
237         $strcalc .= " LIMIT 0,$max";
238      } 
239     
240     my $dbcalc = $dbh->prepare($strcalc);
241     $dbcalc->execute( @query_args );
242 #       warn "filling table";
243     my $previous_col;
244     $i=1;
245     while (my  @data = $dbcalc->fetchrow) {
246         my ($row, $col )=@data;
247         $col = "zzEMPTY" if (!defined($col));
248         $i=1 if (($previous_col) and not($col eq $previous_col));
249         $table[$i]->{$col}=$row;
250 #               warn " $i $col $row";
251         $i++;
252         $previous_col=$col;
253     }
254     
255     push @loopcol,{coltitle => "Global"} if not($column);
256     
257     $max =(($line)?$line:@table -1);
258     for ($i=1; $i<=$max;$i++) {
259         my @loopcell;
260         #@loopcol ensures the order for columns is common with column titles
261         # and the number matches the number of columns
262         my $colcount=0;
263         foreach my $col ( @loopcol ) {
264             my $value;
265             if (@loopcol){
266                 $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}};
267             } else {
268                 $value =$table[$i]->{"zzEMPTY"};
269             }
270             push @loopcell, {value => $value} ;
271         }
272         push @looprow,{ 'rowtitle' => $i ,
273                         'loopcell' => \@loopcell,
274                     };
275     }
276     
277             
278
279     # the header of the table
280     $globalline{loopfilter}=\@loopfilter;
281     # the core of the table
282     $globalline{looprow} = \@looprow;
283     $globalline{loopcol} = \@loopcol;
284 #       # the foot (totals by borrower type)
285     $globalline{loopfooter} = \@loopfooter;
286     $globalline{total}= $grantotal;
287     $globalline{line} = $line;
288     $globalline{column} = $column;
289     push @mainloop,\%globalline;
290     return \@mainloop;
291 }
292
293 1;
294 __END__